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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-
Copyright (C) 2010, 2011, 2012 Jeroen Ketema and Jakob Grue Simonsen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
-- This module defines substitutions.
module Substitution (
Substitution,
match, substitute,
inSubstitution
) where
import SignatureAndVariables
import Term
import Prelude
import Data.Array
import Data.List
-- Substitutions are finite lists of (variable, term)-pairs.
type Substitution s v = [(v, Term s v)]
-- Match a term s with instance t and yield the matching substitution.
--
-- The function requires a match exists, which suffices. Error detection is
-- (and can be) only partial.
match :: (Signature s, Variables v)
=> Term s v -> Term s v -> Substitution s v
match s t = nubBy (\(x, _) (y, _) -> x == y) (computeMatch s t)
where computeMatch (Function f ss) (Function g ts)
| f == g = concat $ zipWith computeMatch (elems ss) (elems ts)
| otherwise = error "Cannot match terms"
computeMatch (Variable x) t'
= [(x, t')]
computeMatch _ _
= error "Cannot match terms"
-- Helper function for substitute, which substitutes a term for a variable
-- if the variable occurs in the subtitution.
substituteVariable :: (Signature s, Variables v)
=> Substitution s v -> v -> Term s v
substituteVariable [] x
= Variable x
substituteVariable ((y, t):sigma') x
| x == y = t
| otherwise = substituteVariable sigma' x
-- Apply a substitution sigma to a term t.
substitute :: (Signature s, Variables v)
=> Substitution s v -> Term s v -> Term s v
substitute sigma (Function f ss)
= Function f $ fmap (substitute sigma) ss
substitute sigma (Variable x)
= substituteVariable sigma x
-- Establish if a variable occurs in a substitution.
inSubstitution :: (Signature s, Variables v)
=> Substitution s v -> v -> Bool
inSubstitution [] _
= False
inSubstitution ((y, _):sigma') x
| x == y = True
| otherwise = inSubstitution sigma' x
|
jeroenk/iTRSsImplemented
|
Substitution.hs
|
agpl-3.0
| 2,585 | 0 | 11 | 578 | 565 | 294 | 271 | 40 | 3 |
module Handler.SupplierActions where
import Import
import Handler.Common
import qualified Data.Text as T
import Text.Blaze
getSupplierActionsR :: SupplierId -> Handler Html
getSupplierActionsR sId = do
mSup <- runDB $ get sId
case mSup of
Just sup ->
defaultLayout $ do
setTitleI (MsgSupplierActions (supplierIdent sup))
$(widgetFile "supplierActions")
Nothing -> do
setMessageI MsgSupplierUnknown
redirect SupplierR
data BevDigest = BevDigest
{ bdCrates :: Int
, bdTotal :: Int
, bdBev :: Beverage
}
getSupplierDigestR :: SupplierId -> Handler Html
getSupplierDigestR sId = do
mSup <- runDB $ get sId
case mSup of
Just sup -> do
master <- getYesod
bevs <- runDB $ selectList [BeverageSupplier ==. (Just sId)] [Asc BeverageIdent]
digests <- return $ map genBevDigest bevs
w <- return $ [whamlet|$newline always
<p>
#{supplierIdent sup}<br>
#{unTextarea $ supplierAddress sup}<br>
#{supplierTel sup}<br>
#{supplierEmail sup}<br>
<hr>
<p>
<b>
_{MsgCustomerId}: #{supplierCustomerId sup}
<p>
<table>
<thead>
<tr>
<th>
<span .transp>|
_{MsgArtNr}
<span .transp>|
<th>
_{MsgName}
<span .transp>|
<th>
_{MsgVolume}
<span .transp>|
<th>
_{MsgCrateCount}
<span .transp>|
<th>
_{MsgPricePerCrate}
<span .transp>|
<th>
_{MsgTotalValue}
<span .transp>|
<tr>
<th colspan="6" .transp>
|---:|---:|---:|---:|---:|---:|
$forall dig <- digests
$if bdCrates dig /= 0
<tr>
<td>
<span .transp>|
#{fromMaybe "" $ beverageArtNr $ bdBev dig}
<span .transp>|
<td>#{beverageIdent $ bdBev dig}
<span .transp>|
<td>#{formatIntVolume $ beverageMl $ bdBev dig}
<span .transp>|
<td>#{T.pack $ show $ bdCrates dig}
<span .transp>|
<td style="text-align: right;">#{formatIntCurrency $ fromMaybe 0 $ beveragePricePerCrate $ bdBev dig} #{appCurrency $ appSettings master}
<span .transp>|
<td style="text-align: right;">#{formatIntCurrency $ bdTotal dig} #{appCurrency $ appSettings master}
<span .transp>|
<tr>
<td colspan="3">
<span .transp>
|
|_{MsgTotalCrates}
<span .transp>
|
<span .transp>|
<td>#{T.pack $ show $ sum $ map bdCrates digests}
<span .transp>|
<td>_{MsgBuyValue}
<span .transp>|
<td style="text-align: right;">#{formatIntCurrency $ sum $ map bdTotal digests} #{appCurrency $ appSettings master}
<span .transp>|
|]
tableLayout w
Nothing -> do
setMessageI MsgSupplierUnknown
redirect SupplierR
-- tableLayout :: Widget -> WidgetT site0 IO ()
tableLayout :: WidgetT App IO () -> HandlerT App IO Markup
tableLayout widget = do
cont <- widgetToPageContent $ do
$(combineStylesheets 'StaticR
[ css_bootstrap_css
, css_main_css
])
widget
withUrlRenderer [hamlet|$newline never
$doctype 5
<html>
<head>
<meta charset="UTF-8">
^{pageHead cont}
<body>
^{pageBody cont}
|]
genBevDigest :: Entity Beverage -> BevDigest
genBevDigest bev =
BevDigest amount (amount * (fromMaybe 0 $ beveragePricePerCrate $ entityVal bev)) (entityVal bev)
where
amount =
if ((beverageMaxAmount (entityVal bev) - beverageAmount (entityVal bev)) `div` (fromMaybe 1 $ beveragePerCrate (entityVal bev))) < 0
then
0
else
((beverageMaxAmount (entityVal bev) - beverageAmount (entityVal bev)) `div` (fromMaybe 1 $ beveragePerCrate (entityVal bev)))
getDeleteSupplierR :: SupplierId -> Handler Html
getDeleteSupplierR sId = do
mSup <- runDB $ get sId
case mSup of
Just _ -> do
a <- runDB $ selectList [BeverageSupplier ==. (Just sId)] []
if null a
then do
runDB $ delete sId
setMessageI MsgSupplierDeleted
redirect SupplierR
else do
setMessageI MsgSupplierInUseError
redirect SupplierR
Nothing -> do
setMessageI MsgSupplierUnknown
redirect SupplierR
|
nek0/yammat
|
Handler/SupplierActions.hs
|
agpl-3.0
| 4,804 | 0 | 18 | 1,756 | 707 | 343 | 364 | -1 | -1 |
module Git.Command.UpdateRef (run) where
run :: [String] -> IO ()
run args = return ()
|
wereHamster/yag
|
Git/Command/UpdateRef.hs
|
unlicense
| 87 | 0 | 7 | 15 | 42 | 23 | 19 | 3 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Data.Foldable (traverse_)
import Data.Default
import Control.Monad.State
import Control.Lens (makeFields, (%=), use)
import System.IO (BufferMode(..), stdin, stdout, hSetBuffering)
import qualified Data.Chess as Chess
import qualified Data.UCI as UCI
data ChessState = ChessState { _chessStateChar :: Char
, _chessStateBoard :: Chess.Board
}
makeFields ''ChessState
instance Default ChessState where def = ChessState { _chessStateChar = 'a'
, _chessStateBoard = def
}
type ChessT = StateT ChessState
type Chess = State ChessState
data ChessRowPos = RowA | RowB | RowC | RowD | RowE | RowF | RowG | RowH
data ChessColPos = Col1 | Col2 | Col3 | Col4 | Col5 | Col6 | Col7 | Col8
type ChessPos = (ChessRowPos, ChessColPos)
type ChessMove = (ChessPos, ChessPos)
parseRowPos :: Char -> ChessRowPos
parseRowPos 'a' = RowA
parseRowPos 'b' = RowB
parseRowPos 'c' = RowC
parseRowPos 'd' = RowD
parseRowPos 'e' = RowE
parseRowPos 'f' = RowF
parseRowPos 'g' = RowG
parseRowPos 'h' = RowH
parseRowPos _ = undefined
parseColPos :: Char -> ChessColPos
parseColPos '1' = Col1
parseColPos '2' = Col2
parseColPos '3' = Col3
parseColPos '4' = Col4
parseColPos '5' = Col5
parseColPos '6' = Col6
parseColPos '7' = Col7
parseColPos '8' = Col8
parseColPos _ = undefined
parsePos :: String -> ChessPos
parsePos [r, c] = (parseRowPos r, parseColPos c)
parsePos _ = undefined
parseMove :: String -> ChessMove
parseMove [r1, c1, r2, c2] = (parsePos [r1, c1], parsePos [r2, c2])
parseMove _ = undefined
receive :: MonadIO m => m [UCI.MessageIn]
receive = UCI.readIn <$> liftIO getLine
send :: MonadIO m => UCI.MessageOut -> m ()
send = liftIO . traverse_ putStrLn . UCI.showOut
main :: IO ()
main = do
hSetBuffering stdin LineBuffering
hSetBuffering stdout LineBuffering
void $ runStateT (forever tick) def
tick :: ChessT IO ()
tick = receive >>= traverse_ handleIn
handleIn :: UCI.MessageIn -> ChessT IO ()
handleIn UCI.UCI = traverse_ send [UCI.ID "gameai-chess" "shockk", UCI.OK]
handleIn UCI.Quit = send (UCI.Info "bye")
handleIn UCI.IsReady = send UCI.ReadyOK
handleIn UCI.NewGame = pure ()
handleIn (UCI.Position _ _) = pure ()
handleIn (UCI.Debug _) = pure ()
handleIn UCI.Go = do
use char >>= \c -> send (UCI.BestMove [c, '7', c, '6'] Nothing)
char %= succ
|
shockkolate/gameai-chess
|
src/Main.hs
|
unlicense
| 2,773 | 0 | 12 | 708 | 857 | 464 | 393 | 71 | 1 |
module Main
( main ) where
import Control.Monad (void)
import System.Environment (getArgs)
import Language.JavaScript
import Language.JavaScript.Parser
import Language.JavaScript.Host.Console
main :: IO ()
main = do
(file:_) <- getArgs
source <- readFile file
let eAST = parseJavaScript source
void $ runHostedJavaScript source console
|
fabianbergmark/ECMA-262
|
Main.hs
|
bsd-2-clause
| 355 | 0 | 10 | 61 | 110 | 59 | 51 | 13 | 1 |
module SetConsole where
import Life.Engine.Set
import Life.Display.Console
import Life.Types
--import Life.Scenes
-- or
import Life.Formations
-- Runs Life indefinitely
life :: Config -> Scene -> IO Board
life c b = lifeConsole (scene c b :: Board)
-- Runs Life for the specified number of generations
-- Then it prints the final board configuration as a list of positions
lifeX :: Int -> Config -> Scene -> IO Board
lifeX x c b = lifeXConsole x (scene c b :: Board)
-- Runs the original version of Life (size 20x20 with wrapping edges) starting with the "glider" board
originalLife = life ((20,20),True) $ glider (0,0)
main = originalLife
|
ku-fpg/better-life
|
examples/simulations/SetConsole.hs
|
bsd-2-clause
| 648 | 0 | 8 | 116 | 158 | 89 | 69 | 11 | 1 |
module Main where
import ProjectEuler.Problem001
import ProjectEuler.Problem002
import ProjectEuler.Problem003
import ProjectEuler.Problem004
import ProjectEuler.Problem005
import ProjectEuler.Problem006
import ProjectEuler.Problem007
import ProjectEuler.Problem008
import ProjectEuler.Problem009
import ProjectEuler.Problem010
import Util
import qualified Data.Map as M
import System.Environment (getArgs)
import System.Exit (exitSuccess)
solutions :: M.Map Int String
solutions = M.fromList [
(1,show solution001),
(2,show solution002),
(3,show solution003),
(4,show solution004),
(5,show solution005),
(6,show solution006),
(7,show solution007),
(8,show solution008),
(9,show solution009),
(10,show solution010)]
main :: IO ()
main = do
args <- getArgs
case args of
[number] -> case M.lookup (read number :: Int) solutions of
Just result -> time result >>= print
Nothing -> putStrLn("No solutions found.") >> exitSuccess
_ -> putStrLn("Help? cabal run [number]") >> exitSuccess
|
ThermalSpan/haskell-euler
|
src/Main.hs
|
bsd-3-clause
| 1,150 | 0 | 15 | 279 | 333 | 186 | 147 | 35 | 3 |
module IrcScanner.LogWatcher(watchLogFile) where
import IrcScanner.Types
import Data.IORef
import System.INotify
import Control.Monad.Trans.Reader as R
import Control.Monad.IO.Class(liftIO)
import System.IO as I
import Data.Time.LocalTime(localTimeToUTC)--, hoursToTimeZone)
import Parser.Irssi.Log.Util.Import(importIrssiDataContents)
import IrcScanner.Index(addFileLines,addLogFileToState)
import Data.Text as T (length,Text)--,unpack)
import Data.Text.IO as T (hGetContents)
--import IrcScanner.Index
--import Control.Concurrent (threadDelay)
data WatchData =
WatchData {
fileNickName :: T.Text,
fileName :: FilePath,
currPos :: Integer
} deriving (Show)
-- | watches the log file for updates, and adds rows to state when new lines appear
watchLogFile :: T.Text -- ^ file "nick name". We lovingly refer to files by these, internally
-> FilePath -- ^ full path to filename
-> IConfig
-> IO ()
watchLogFile fnn fn ic = do
-- add the file to the internal state
runReaderT
(addLogFileToState fnn) ic
inotify <- initINotify
wd <- liftIO $ newIORef (WatchData fnn fn 0)
_ <- liftIO $ addWatch inotify [Modify, CloseWrite] fn (handleEvent wd ic)
handleEvent wd ic Ignored
return ()
handleEvent :: IORef WatchData -> IConfig -> Event -> IO ()
handleEvent wdir ic _ =
do
putStrLn("handleEvent start");
--this assumes that the haskell inotify code doesn't use multiple threads for
--events that occur one after another
--open the file and read the data
wd <- readIORef wdir
h <- openFile (fileName wd) ReadMode
hSeek h AbsoluteSeek (currPos wd)
hSetEncoding h latin1
contents <- T.hGetContents h
irssiData <- importIrssiDataContents contents
if (T.length contents > 0) then putStrLn("currPos "++(show $ currPos wd)++" read "++(show (T.length contents))++" bytes") else return ()
if (T.length contents < 10000) then putStrLn("contents "++(show $ contents)) else return ()
--update our internal state for the new current pos
writeIORef wdir $ wd { currPos = (currPos wd) + (fromIntegral (T.length contents)) }
--notify the main code that there are new lines
runReaderT
(addFileLines (fileNickName wd) $ fmap (\(t,l) -> ILine (localTimeToUTC (_ctimeZone ic) t) l) irssiData)
ic
putStrLn("handleEvent end");
-- _watchLogTest :: IO ()
-- _watchLogTest =
-- do
-- es <- _demoIState
-- case es of
-- Left x -> putStrLn("Error: " ++ (unpack x))
-- Right s ->
-- do
-- i <- newIORef s
-- ic <- return $ IConfig i (hoursToTimeZone 0)
-- watchLogFile "t2.log" ic
-- loopAndPrintStatus ic
-- where
-- loopAndPrintStatus :: IConfig -> IO ()
-- loopAndPrintStatus ic = do
-- s <- readIORef (_cstate ic)
-- putStrLn $ show (_sfile s)
-- threadDelay (10 * 1000 * 1000)
-- loopAndPrintStatus ic
|
redfish64/IrcScanner
|
src/IrcScanner/LogWatcher.hs
|
bsd-3-clause
| 2,944 | 0 | 17 | 667 | 674 | 366 | 308 | 47 | 3 |
{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls, FlexibleContexts, FlexibleInstances, RankNTypes,MultiParamTypeClasses #-}
module Language.Java.JVM.API where
import Language.Java.JVM.Types
import Control.Monad
import qualified Data.Map as Map
import Foreign.C
import Foreign.Ptr
import Foreign.Marshal.Alloc
import Foreign.Marshal.Array
import Control.Concurrent.MVar
import Control.Monad.IO.Class
import Control.Monad.State
import Text.Printf
foreign import ccall safe "start" f_start ::CString -> IO (CLong)
foreign import ccall safe "end" f_end :: IO ()
--foreign import ccall "test" test ::CInt -> IO (CInt)
foreign import ccall safe "findClass" f_findClass :: CString -> IO (JClassPtr)
foreign import ccall safe "freeClass" f_freeClass :: JClassPtr -> IO ()
foreign import ccall safe "freeObject" f_freeObject :: JObjectPtr -> IO ()
foreign import ccall safe "findMethod" f_findMethod :: JClassPtr -> CString -> CString -> IO (JMethodPtr)
foreign import ccall safe "findStaticMethod" f_findStaticMethod :: JClassPtr -> CString -> CString -> IO (JMethodPtr)
foreign import ccall safe "findField" f_findField :: JClassPtr -> CString -> CString -> IO (JFieldPtr)
foreign import ccall safe "findStaticField" f_findStaticField :: JClassPtr -> CString -> CString -> IO (JFieldPtr)
foreign import ccall safe "newObject" f_newObject :: JClassPtr -> JMethodPtr -> JValuePtr -> CWString -> IO (JObjectPtr)
foreign import ccall safe "newString" f_newString :: CWString -> CLong -> CWString-> IO (JObjectPtr)
foreign import ccall safe "callIntMethod" f_callIntMethod :: JObjectPtr -> JMethodPtr -> JValuePtr -> CWString-> IO (CLong)
foreign import ccall safe "callCharMethod" f_callCharMethod :: JObjectPtr -> JMethodPtr -> JValuePtr -> CWString-> IO (CUShort)
foreign import ccall safe "callVoidMethod" f_callVoidMethod :: JObjectPtr -> JMethodPtr -> JValuePtr -> CWString-> IO ()
foreign import ccall safe "callBooleanMethod" f_callBooleanMethod :: JObjectPtr -> JMethodPtr -> JValuePtr -> CWString-> IO (CUChar)
foreign import ccall safe "callByteMethod" f_callByteMethod :: JObjectPtr -> JMethodPtr -> JValuePtr -> CWString-> IO (CChar)
foreign import ccall safe "callLongMethod" f_callLongMethod :: JObjectPtr -> JMethodPtr -> JValuePtr -> CWString-> IO (CLong)
foreign import ccall safe "callShortMethod" f_callShortMethod :: JObjectPtr -> JMethodPtr -> JValuePtr -> CWString-> IO (CShort)
foreign import ccall safe "callFloatMethod" f_callFloatMethod :: JObjectPtr -> JMethodPtr -> JValuePtr -> CWString-> IO (CFloat)
foreign import ccall safe "callDoubleMethod" f_callDoubleMethod :: JObjectPtr -> JMethodPtr -> JValuePtr -> CWString-> IO (CDouble)
foreign import ccall safe "callObjectMethod" f_callObjectMethod :: JObjectPtr -> JMethodPtr -> JValuePtr -> CWString-> IO (JObjectPtr)
foreign import ccall safe "callStaticIntMethod" f_callStaticIntMethod :: JClassPtr -> JMethodPtr -> JValuePtr -> CWString-> IO (CLong)
foreign import ccall safe "callStaticCharMethod" f_callStaticCharMethod :: JClassPtr -> JMethodPtr -> JValuePtr -> CWString-> IO (CUShort)
foreign import ccall safe "callStaticVoidMethod" f_callStaticVoidMethod :: JClassPtr -> JMethodPtr -> JValuePtr -> CWString-> IO ()
foreign import ccall safe "callStaticBooleanMethod" f_callStaticBooleanMethod :: JClassPtr -> JMethodPtr -> JValuePtr -> CWString-> IO (CUChar)
foreign import ccall safe "callStaticByteMethod" f_callStaticByteMethod :: JClassPtr -> JMethodPtr -> JValuePtr -> CWString-> IO (CChar)
foreign import ccall safe "callStaticLongMethod" f_callStaticLongMethod :: JClassPtr -> JMethodPtr -> JValuePtr -> CWString-> IO (CLong)
foreign import ccall safe "callStaticShortMethod" f_callStaticShortMethod :: JClassPtr -> JMethodPtr -> JValuePtr -> CWString-> IO (CShort)
foreign import ccall safe "callStaticFloatMethod" f_callStaticFloatMethod :: JClassPtr -> JMethodPtr -> JValuePtr -> CWString-> IO (CFloat)
foreign import ccall safe "callStaticDoubleMethod" f_callStaticDoubleMethod :: JClassPtr -> JMethodPtr -> JValuePtr -> CWString-> IO (CDouble)
foreign import ccall safe "callStaticObjectMethod" f_callStaticObjectMethod :: JClassPtr -> JMethodPtr -> JValuePtr -> CWString-> IO (JObjectPtr)
foreign import ccall safe "getStaticIntField" f_getStaticIntField :: JClassPtr -> JFieldPtr -> CWString-> IO (CLong)
foreign import ccall safe "getStaticBooleanField" f_getStaticBooleanField :: JClassPtr -> JFieldPtr -> CWString-> IO (CUChar)
foreign import ccall safe "getStaticCharField" f_getStaticCharField :: JClassPtr -> JFieldPtr -> CWString-> IO (CUShort)
foreign import ccall safe "getStaticShortField" f_getStaticShortField :: JClassPtr -> JFieldPtr -> CWString-> IO (CShort)
foreign import ccall safe "getStaticByteField" f_getStaticByteField :: JClassPtr -> JFieldPtr -> CWString-> IO (CChar)
foreign import ccall safe "getStaticLongField" f_getStaticLongField :: JClassPtr -> JFieldPtr -> CWString-> IO (CLong)
foreign import ccall safe "getStaticDoubleField" f_getStaticDoubleField :: JClassPtr -> JFieldPtr -> CWString-> IO (CDouble)
foreign import ccall safe "getStaticFloatField" f_getStaticFloatField :: JClassPtr -> JFieldPtr -> CWString-> IO (CFloat)
foreign import ccall safe "getStaticObjectField" f_getStaticObjectField :: JClassPtr -> JFieldPtr -> CWString-> IO (JObjectPtr)
foreign import ccall safe "setStaticIntField" f_setStaticIntField :: JClassPtr -> JFieldPtr-> CLong -> CWString -> IO ()
foreign import ccall safe "setStaticBooleanField" f_setStaticBooleanField :: JClassPtr -> JFieldPtr-> CUChar -> CWString -> IO ()
foreign import ccall safe "setStaticCharField" f_setStaticCharField :: JClassPtr -> JFieldPtr-> CUShort -> CWString-> IO ()
foreign import ccall safe "setStaticShortField" f_setStaticShortField :: JClassPtr -> JFieldPtr-> CShort -> CWString -> IO ()
foreign import ccall safe "setStaticByteField" f_setStaticByteField :: JClassPtr -> JFieldPtr -> CChar -> CWString-> IO ()
foreign import ccall safe "setStaticLongField" f_setStaticLongField :: JClassPtr -> JFieldPtr -> CLong -> CWString-> IO ()
foreign import ccall safe "setStaticDoubleField" f_setStaticDoubleField :: JClassPtr -> JFieldPtr-> CDouble -> CWString-> IO ()
foreign import ccall safe "setStaticFloatField" f_setStaticFloatField :: JClassPtr -> JFieldPtr-> CFloat -> CWString -> IO ()
foreign import ccall safe "setStaticObjectField" f_setStaticObjectField :: JClassPtr -> JFieldPtr -> JObjectPtr -> CWString -> IO ()
foreign import ccall safe "getIntField" f_getIntField :: JObjectPtr -> JFieldPtr -> CWString-> IO (CLong)
foreign import ccall safe "getBooleanField" f_getBooleanField :: JObjectPtr -> JFieldPtr -> CWString-> IO (CUChar)
foreign import ccall safe "getCharField" f_getCharField :: JObjectPtr -> JFieldPtr -> CWString-> IO (CUShort)
foreign import ccall safe "getShortField" f_getShortField :: JObjectPtr -> JFieldPtr -> CWString-> IO (CShort)
foreign import ccall safe "getByteField" f_getByteField :: JObjectPtr -> JFieldPtr -> CWString-> IO (CChar)
foreign import ccall safe "getLongField" f_getLongField :: JObjectPtr -> JFieldPtr -> CWString-> IO (CLong)
foreign import ccall safe "getDoubleField" f_getDoubleField :: JObjectPtr -> JFieldPtr -> CWString-> IO (CDouble)
foreign import ccall safe "getFloatField" f_getFloatField :: JObjectPtr -> JFieldPtr -> CWString-> IO (CFloat)
foreign import ccall safe "getObjectField" f_getObjectField :: JObjectPtr -> JFieldPtr -> CWString-> IO (JObjectPtr)
foreign import ccall safe "setIntField" f_setIntField :: JObjectPtr -> JFieldPtr-> CLong -> CWString -> IO ()
foreign import ccall safe "setBooleanField" f_setBooleanField :: JObjectPtr -> JFieldPtr-> CUChar -> CWString -> IO ()
foreign import ccall safe "setCharField" f_setCharField :: JObjectPtr -> JFieldPtr-> CUShort -> CWString-> IO ()
foreign import ccall safe "setShortField" f_setShortField :: JObjectPtr -> JFieldPtr-> CShort -> CWString -> IO ()
foreign import ccall safe "setByteField" f_setByteField :: JObjectPtr -> JFieldPtr -> CChar -> CWString-> IO ()
foreign import ccall safe "setLongField" f_setLongField :: JObjectPtr -> JFieldPtr -> CLong -> CWString-> IO ()
foreign import ccall safe "setDoubleField" f_setDoubleField :: JObjectPtr -> JFieldPtr-> CDouble -> CWString-> IO ()
foreign import ccall safe "setFloatField" f_setFloatField :: JObjectPtr -> JFieldPtr-> CFloat -> CWString -> IO ()
foreign import ccall safe "setObjectField" f_setObjectField :: JObjectPtr -> JFieldPtr -> JObjectPtr -> CWString -> IO ()
foreign import ccall safe "registerCallback" f_registerCallback :: CString -> CString -> CString -> FunPtr CallbackInternal -> IO()
foreign import ccall "wrapper" wrap :: CallbackInternal -> IO (FunPtr CallbackInternal)
withJava :: String -> JavaT a -> IO a
withJava = withJava' True
withJava' :: Bool -> String -> JavaT a -> IO a
withJava' end options f= do
ret<-withCString options (\s->f_start s)
when (ret < 0) (ioError $ userError "could not start JVM")
(a,s)<-runStateT f (JavaCache Map.empty Map.empty Map.empty)
when end (evalStateT endJava s)
return a
endJava :: JavaT()
endJava = do
jc<-getJavaCache
liftIO $ mapM_ (\ptr->f_freeClass ptr) (Map.elems $ jc_classes jc)
putJavaCache (JavaCache Map.empty Map.empty Map.empty)
liftIO $ f_end
--withJavaRT :: (JRuntimePtr -> IO (a)) -> JavaT a
--withJavaRT f=do
-- rt<-get
-- r<-liftIO $ f rt
-- return r
registerCallBackMethod:: (WithJava m) => String -> String -> String -> m (CallbackMapRef)
registerCallBackMethod cls method eventCls =do
jc<-getJavaCache
ior<-liftIO $ newMVar Map.empty
eventW<-liftIO $ wrap (event jc ior )
liftIO $ withCString cls
(\clsn->withCString method
(\methodn->withCString eventCls
(\eventClsn->f_registerCallback clsn methodn eventClsn eventW)))
return ior
addCallBack :: (WithJava m) => CallbackMapRef -> Callback -> m(CLong)
addCallBack cmr cb=do
liftIO $ modifyMVar cmr (\m-> do
let index=fromIntegral $ Map.size m
return (Map.insert index cb m,index))
findClass :: (WithJava m) => ClassName -> m JClassPtr
findClass name=do
jc<-getJavaCache
let mptr=Map.lookup name (jc_classes jc)
case mptr of
Just ptr->return ptr
Nothing->do
ptr<-liftIO $ withCString name (\s->f_findClass s)
putJavaCache (jc{jc_classes=Map.insert name ptr $ jc_classes jc})
return ptr
withClass :: (WithJava m) => ClassName -> (JClassPtr->m a) -> m a
withClass className f= findClass (className)>>=(\cls->do
when (cls==nullPtr) (liftIO $ ioError $ userError $ printf "class %s not found" className)
f cls)
freeClass :: (WithJava m) => ClassName -> m ()
freeClass name=do
jc<-getJavaCache
let mptr=Map.lookup name (jc_classes jc)
case mptr of
Just ptr->do
liftIO $ f_freeClass ptr
putJavaCache (jc{jc_classes=Map.delete name $ jc_classes jc})
Nothing->return ()
findMethod :: (WithJava m) => Method -> m JMethodPtr
findMethod meth=do
jc<-getJavaCache
let mptr=Map.lookup meth (jc_methods jc)
case mptr of
Just ptr->return ptr
Nothing -> do
withClass (m_class meth) (\cls->do
ptr<- liftIO $ withCString (m_name meth)
(\m->withCString (m_signature meth)
(\s->f_findMethod cls m s
))
putJavaCache (jc{jc_methods=Map.insert meth ptr $ jc_methods jc})
return ptr)
findStaticMethod :: (WithJava m) => Method -> m JMethodPtr
findStaticMethod meth=do
jc<-getJavaCache
let mptr=Map.lookup meth (jc_methods jc)
case mptr of
Just ptr->return ptr
Nothing -> do
withClass (m_class meth) (\cls->do
ptr<- liftIO $ withCString (m_name meth)
(\m->withCString (m_signature meth)
(\s->f_findStaticMethod cls m s
))
putJavaCache (jc{jc_methods=Map.insert meth ptr $ jc_methods jc})
return ptr)
withMethod :: (WithJava m) => Method -> (JMethodPtr -> m a) -> m a
withMethod mp f=do
mid<-findMethod mp
when (mid==nullPtr) (liftIO $ ioError $ userError $ printf "method %s not found" $ show mp)
f mid
withStaticMethod :: (WithJava m) => Method -> (JMethodPtr -> m a) -> m a
withStaticMethod mp f=do
mid<-findStaticMethod mp
when (mid==nullPtr) (liftIO $ ioError $ userError $ printf "static method %s not found" $ show mp)
f mid
findField :: (WithJava m) => Field -> m JFieldPtr
findField field=do
jc<-getJavaCache
let mptr=Map.lookup field (jc_fields jc)
case mptr of
Just ptr->return ptr
Nothing -> do
withClass (f_class field) (\cls->do
ptr<- liftIO $ withCString (f_name field)
(\m->withCString (f_signature field)
(\s->f_findField cls m s
))
putJavaCache (jc{jc_fields=Map.insert field ptr $ jc_fields jc})
return ptr)
findStaticField :: (WithJava m) => Field -> m JFieldPtr
findStaticField field=do
jc<-getJavaCache
let mptr=Map.lookup field (jc_fields jc)
case mptr of
Just ptr->return ptr
Nothing -> do
withClass (f_class field) (\cls->do
ptr<- liftIO $ withCString (f_name field)
(\m->withCString (f_signature field)
(\s->f_findStaticField cls m s
))
putJavaCache (jc{jc_fields=Map.insert field ptr $ jc_fields jc})
return ptr)
withField :: (WithJava m) => Field -> (JFieldPtr -> m a) -> m a
withField mp f=do
fid<-findField mp
when (fid==nullPtr) (liftIO $ ioError $ userError $ printf "field %s not found" $ show mp)
f fid
withStaticField :: (WithJava m) => Field -> (JFieldPtr -> m a) -> m a
withStaticField mp f=do
fid<-findStaticField mp
when (fid==nullPtr) (liftIO $ ioError $ userError $ printf "static field %s not found" $ show mp)
f fid
handleException :: (CWString -> IO a) -> IO a
handleException f=allocaBytes 1000 (\errMsg ->do
ret<-f errMsg
s<-peekCWString errMsg
when (not $ null s) (ioError $ userError s)
return ret
)
withObject :: (WithJava m) => (m JObjectPtr) -> (JObjectPtr -> m a) -> m a
withObject f1 f2=do
obj <- f1
ret <- f2 obj
liftIO $ f_freeObject obj
return (ret)
newObject :: (WithJava m) => ClassName -> String -> [JValue] -> m (JObjectPtr)
newObject className signature args= withClass (className) (\cls->do
withMethod (Method className "<init>" signature) (\mid->
liftIO $ withArray args
(\arr-> handleException $ f_newObject cls mid arr)))
event :: JavaCache -> CallbackMapRef -> CallbackInternal
event jc mvar _ _ index eventObj=do
putStrLn "event"
putStrLn ("listenerEvt:"++(show index))
mh<-liftIO $ withMVar mvar (\m->do
return $ Map.lookup index m
)
case mh of
Nothing-> return ()
Just h->evalStateT (h eventObj) jc
--instance MethodProvider (JClassPtr,String,String) where
-- getMethodID (cls,method,signature)=do
-- withCString method
-- (\m->withCString signature
-- (\s->f_findMethod cls m s))
--
--instance MethodProvider (String,String,String) where
-- getMethodID (clsName,method,signature)=do
-- findClass clsName>>=(\cls->do
-- when (cls==nullPtr) (ioError $ userError $ printf "class %s not found" clsName)
-- withCString method
-- (\m->withCString signature
-- (\s->f_findMethod cls m s)))
--
voidMethod :: (WithJava m) => JObjectPtr -> Method -> [JValue] -> m ()
voidMethod obj m args=
withMethod m (\mid->liftIO $ withArray args (\arr->handleException $ f_callVoidMethod obj mid arr))
execMethod :: (HaskellJavaConversion h j,WithJava m) =>
(JObjectPtr -> JMethodPtr -> JValuePtr -> CWString-> IO j)
-> JObjectPtr -> Method -> [JValue] -> m h
execMethod f obj m args = javaToHaskell $ withMethod m (\mid->liftIO $ withArray args (\arr->handleException $ f obj mid arr))
booleanMethod :: (WithJava m) =>JObjectPtr -> Method -> [JValue] -> m (Bool)
booleanMethod obj m args= execMethod f_callBooleanMethod obj m args
intMethod :: (WithJava m) =>JObjectPtr -> Method -> [JValue] -> m (Integer)
intMethod obj m args= execMethod f_callIntMethod obj m args
charMethod :: (WithJava m) =>JObjectPtr -> Method -> [JValue] -> m (Char)
charMethod obj m args= execMethod f_callCharMethod obj m args
shortMethod :: (WithJava m) =>JObjectPtr -> Method -> [JValue] -> m (Int)
shortMethod obj m args= execMethod f_callShortMethod obj m args
byteMethod :: (WithJava m) =>JObjectPtr -> Method -> [JValue] -> m (Int)
byteMethod obj m args= execMethod f_callByteMethod obj m args
longMethod :: (WithJava m) =>JObjectPtr -> Method -> [JValue] -> m (Integer)
longMethod obj m args= execMethod f_callLongMethod obj m args
floatMethod :: (WithJava m) =>JObjectPtr -> Method -> [JValue] -> m (Float)
floatMethod obj m args= execMethod f_callFloatMethod obj m args
doubleMethod :: (WithJava m) =>JObjectPtr -> Method -> [JValue] -> m (Double)
doubleMethod obj m args= execMethod f_callDoubleMethod obj m args
objectMethod :: (WithJava m) =>JObjectPtr -> Method -> [JValue] -> m (JObjectPtr)
objectMethod obj m args= execMethod f_callObjectMethod obj m args
execStaticMethod :: (HaskellJavaConversion h j,WithJava m) =>
(JClassPtr -> JMethodPtr -> JValuePtr -> CWString-> IO j)
-> JClassPtr -> Method -> [JValue] -> m h
execStaticMethod f cls m args = javaToHaskell $ withStaticMethod m (\mid->liftIO $ withArray args (\arr->handleException $ f cls mid arr))
staticIntMethod :: (WithJava m) =>JClassPtr -> Method -> [JValue] -> m (Integer)
staticIntMethod cls m args= execStaticMethod f_callStaticIntMethod cls m args
staticBooleanMethod :: (WithJava m) =>JClassPtr -> Method -> [JValue] -> m (Bool)
staticBooleanMethod cls m args= execStaticMethod f_callStaticBooleanMethod cls m args
staticCharMethod :: (WithJava m) =>JClassPtr -> Method -> [JValue] -> m (Char)
staticCharMethod cls m args= execStaticMethod f_callStaticCharMethod cls m args
staticShortMethod :: (WithJava m) =>JClassPtr -> Method -> [JValue] -> m (Int)
staticShortMethod cls m args= execStaticMethod f_callStaticShortMethod cls m args
staticByteMethod :: (WithJava m) =>JClassPtr -> Method -> [JValue] -> m (Int)
staticByteMethod cls m args= execStaticMethod f_callStaticByteMethod cls m args
staticLongMethod :: (WithJava m) =>JClassPtr -> Method -> [JValue] -> m (Integer)
staticLongMethod cls m args= execStaticMethod f_callStaticLongMethod cls m args
staticFloatMethod :: (WithJava m) =>JClassPtr -> Method -> [JValue] -> m (Float)
staticFloatMethod cls m args= execStaticMethod f_callStaticFloatMethod cls m args
staticDoubleMethod :: (WithJava m) =>JClassPtr -> Method -> [JValue] -> m (Double)
staticDoubleMethod cls m args= execStaticMethod f_callStaticDoubleMethod cls m args
staticObjectMethod :: (WithJava m) =>JClassPtr -> Method -> [JValue] -> m (JObjectPtr)
staticObjectMethod cls m args= execStaticMethod f_callStaticObjectMethod cls m args
getStaticField :: (HaskellJavaConversion h j,WithJava m) =>
(JClassPtr -> JFieldPtr -> CWString-> IO j)
-> JClassPtr -> Field -> m h
getStaticField f cls fi = javaToHaskell $ withStaticField fi (\fid->liftIO $ handleException $ f cls fid)
getStaticIntField :: (WithJava m) =>JClassPtr -> Field -> m (Integer)
getStaticIntField = getStaticField f_getStaticIntField
getStaticBooleanField :: (WithJava m) =>JClassPtr -> Field -> m (Bool)
getStaticBooleanField = getStaticField f_getStaticBooleanField
getStaticCharField :: (WithJava m) =>JClassPtr -> Field -> m (Char)
getStaticCharField = getStaticField f_getStaticCharField
getStaticShortField :: (WithJava m) =>JClassPtr -> Field -> m (Int)
getStaticShortField = getStaticField f_getStaticShortField
getStaticByteField :: (WithJava m) =>JClassPtr -> Field -> m (Int)
getStaticByteField= getStaticField f_getStaticByteField
getStaticLongField :: (WithJava m) =>JClassPtr -> Field -> m (Integer)
getStaticLongField = getStaticField f_getStaticLongField
getStaticDoubleField :: (WithJava m) =>JClassPtr -> Field -> m (Double)
getStaticDoubleField= getStaticField f_getStaticDoubleField
getStaticFloatField :: (WithJava m) =>JClassPtr -> Field -> m (Float)
getStaticFloatField= getStaticField f_getStaticFloatField
getStaticObjectField :: (WithJava m) =>JClassPtr -> Field -> m (JObjectPtr)
getStaticObjectField= getStaticField f_getStaticObjectField
setStaticField :: (HaskellJavaConversion h j,WithJava m) =>
(JClassPtr -> JFieldPtr -> j -> CWString -> IO ())
-> JClassPtr -> Field -> h -> m ()
setStaticField f cls fi v= withStaticField fi (\fid->liftIO $ handleException $ f cls fid $ fromHaskell v)
setStaticIntField :: (WithJava m) =>JClassPtr -> Field -> Integer -> m ()
setStaticIntField = setStaticField f_setStaticIntField
setStaticBooleanField :: (WithJava m) =>JClassPtr -> Field -> Bool -> m ()
setStaticBooleanField = setStaticField f_setStaticBooleanField
setStaticCharField :: (WithJava m) =>JClassPtr -> Field -> Char -> m ()
setStaticCharField = setStaticField f_setStaticCharField
setStaticShortField :: (WithJava m) =>JClassPtr -> Field -> Int -> m ()
setStaticShortField = setStaticField f_setStaticShortField
setStaticByteField :: (WithJava m) =>JClassPtr -> Field -> Int -> m ()
setStaticByteField = setStaticField f_setStaticByteField
setStaticLongField :: (WithJava m) =>JClassPtr -> Field -> Integer -> m ()
setStaticLongField = setStaticField f_setStaticLongField
setStaticDoubleField :: (WithJava m) =>JClassPtr -> Field -> Double -> m ()
setStaticDoubleField = setStaticField f_setStaticDoubleField
setStaticFloatField :: (WithJava m) =>JClassPtr -> Field -> Float -> m ()
setStaticFloatField = setStaticField f_setStaticFloatField
setStaticObjectField :: (WithJava m) =>JClassPtr -> Field -> JObjectPtr -> m ()
setStaticObjectField = setStaticField f_setStaticObjectField
getField :: (HaskellJavaConversion h j,WithJava m) =>
(JObjectPtr -> JFieldPtr -> CWString-> IO j)
-> JObjectPtr -> Field -> m h
getField f cls fi = javaToHaskell $ withField fi (\fid->liftIO $ handleException $ f cls fid)
getIntField :: (WithJava m) =>JObjectPtr -> Field -> m (Integer)
getIntField = getField f_getIntField
getBooleanField :: (WithJava m) =>JObjectPtr -> Field -> m (Bool)
getBooleanField = getField f_getBooleanField
getCharField :: (WithJava m) =>JObjectPtr -> Field -> m (Char)
getCharField = getField f_getCharField
getShortField :: (WithJava m) =>JObjectPtr -> Field -> m (Int)
getShortField = getField f_getShortField
getByteField :: (WithJava m) =>JObjectPtr -> Field -> m (Int)
getByteField= getField f_getByteField
getLongField :: (WithJava m) =>JObjectPtr -> Field -> m (Integer)
getLongField = getField f_getLongField
getDoubleField :: (WithJava m) =>JObjectPtr -> Field -> m (Double)
getDoubleField= getField f_getDoubleField
getFloatField :: (WithJava m) =>JObjectPtr -> Field -> m (Float)
getFloatField= getField f_getFloatField
getObjectField :: (WithJava m) =>JObjectPtr -> Field -> m (JObjectPtr)
getObjectField= getField f_getObjectField
setField :: (HaskellJavaConversion h j,WithJava m) =>
(JObjectPtr -> JFieldPtr -> j -> CWString -> IO ())
-> JObjectPtr -> Field -> h -> m ()
setField f cls fi v= withField fi (\fid->liftIO $ handleException $ f cls fid $ fromHaskell v)
setIntField :: (WithJava m) =>JObjectPtr -> Field -> Integer -> m ()
setIntField = setField f_setIntField
setBooleanField :: (WithJava m) =>JObjectPtr -> Field -> Bool -> m ()
setBooleanField = setField f_setBooleanField
setCharField :: (WithJava m) =>JObjectPtr -> Field -> Char -> m ()
setCharField = setField f_setCharField
setShortField :: (WithJava m) =>JObjectPtr -> Field -> Int -> m ()
setShortField = setField f_setShortField
setByteField :: (WithJava m) =>JObjectPtr -> Field -> Int -> m ()
setByteField = setField f_setByteField
setLongField :: (WithJava m) =>JObjectPtr -> Field -> Integer -> m ()
setLongField = setField f_setLongField
setDoubleField :: (WithJava m) =>JObjectPtr -> Field -> Double -> m ()
setDoubleField = setField f_setDoubleField
setFloatField :: (WithJava m) =>JObjectPtr -> Field -> Float -> m ()
setFloatField = setField f_setFloatField
setObjectField :: (WithJava m) =>JObjectPtr -> Field -> JObjectPtr -> m ()
setObjectField = setField f_setObjectField
toJString :: (MonadIO m) => String -> m (JObjectPtr)
toJString s= liftIO $ withCWString s (\cs->handleException $ f_newString cs (fromIntegral $ length s))
|
JPMoresmau/HJVM
|
src/Language/Java/JVM/API.hs
|
bsd-3-clause
| 25,997 | 0 | 25 | 5,663 | 8,081 | 4,121 | 3,960 | 370 | 2 |
module Fibon.Analyse.Analysis (
Analysis(..)
, runAnalysis
, computeRows
, Normalize(..)
, NormMethod
)
where
import Data.List
import Data.Maybe
import qualified Data.Map as M
import Control.Monad.Error
import Fibon.Result
import Fibon.Analyse.AnalysisRoutines
import Fibon.Analyse.Parse
import Fibon.Analyse.Result
import Fibon.Analyse.Metrics
import Fibon.Analyse.Statistics
import Fibon.Analyse.Tables
import qualified Data.Vector.Unboxed as V
runAnalysis :: Analysis a -> FilePath -> IO (Maybe [ResultColumn a])
runAnalysis analysis file = do
fibonResults <- parse file
case fibonResults of
Nothing -> return Nothing
Just rs -> do x <- createResultColumns analysis rs
return (Just x)
where
parse f | ".SHOW" `isSuffixOf` f = parseShowFibonResults f
| otherwise = parseBinaryFibonResults f
createResultColumns :: Analysis a
-> M.Map ResultLabel [FibonResult]
-> IO [ResultColumn a]
createResultColumns analysis fibonResults =
mapM (analyseResults analysis) (M.toList fibonResults)
analyseResults :: Analysis a
-> (ResultLabel, [FibonResult])
-> IO (ResultColumn a)
analyseResults analysis (resultName, fibonResults) = do
ars <- mapM (analyseResult analysis) fibonResults
return $ ResultColumn resultName (resMap ars)
where
resMap ars = foldr create M.empty (zip ars fibonResults)
create (ar,fr) m = M.insert (benchNameOnly fr) ar m
benchNameOnly fr = takeWhile (/= '-') (benchName fr)
analyseResult ::
Analysis a
-> FibonResult
-> IO (AnalyseResult a) -- ^ final result
analyseResult analysis fibonR = do
fibonS <- (fibonAnalysis analysis) fibonR
extraS <- case mbExtras of
Nothing -> return Nothing
Just [] -> return Nothing
Just es -> return . Just =<< (extraAnalysis analysis) es
return (AnalyseResult fibonS extraS)
where
mbExtras = sequence $ map (extraP.runStats) (details.runData $ fibonR)
extraP = extraParser analysis
-- | Functions for normalizing and computing summaries of results
--
--
type RowData = (RowName, [PerfData])
type RowName = String
type TableError = String
type PerfMonad = Either TableError
type NormMethod a = ResultColumn a -> Normalize a
data Normalize a =
NormPercent (ResultColumn a)
| NormRatio (ResultColumn a)
| NormNone
computeRows :: [(Normalize a, ResultColumn a)]
-> [BenchName]
-> TableSpec a
-> Either TableError ([RowData], [RowData])
computeRows resultColumns benchs colSpecs = do
rows <- mapM (computeOneRow resultColumns colSpecs) benchs
let colData = transpose $ map snd rows
doSumm how = mapM (summarize how) colData
minRow <- doSumm Min
meanRow <- doSumm GeoMean
arithRow <- doSumm ArithMean
maxRow <- doSumm Max
let sumRows = [
("min", minRow)
, ("geomean", meanRow)
, ("arithmean", arithRow)
, ("max", maxRow)
]
return (rows, sumRows)
computeOneRow :: [(Normalize a, ResultColumn a)]
-> [ColSpec a]
-> BenchName
-> PerfMonad RowData
computeOneRow resultColumns colSpecs bench = do
row <- mapM (\spec ->
mapM (computeOneColumn bench spec) resultColumns
) colSpecs
return (bench, concat row)
computeOneColumn :: BenchName
-> ColSpec a
-> (Normalize a, ResultColumn a)
-> PerfMonad PerfData
computeOneColumn bench (ColSpec _ metric) (normType, resultColumn) =
maybe (return NoResult) doNormalize (getRawPerf resultColumn)
where
doNormalize peak =
case normType of
NormPercent base -> normToBase base normalizePercent
NormRatio base -> normToBase base normalizeRatio
NormNone -> return (mkRaw peak)
where
mkRaw = Basic . Raw
mkNorm = Basic . Norm
normToBase base normFun = maybe (return NoResult)
(\b -> mkNorm `liftM` normFun b peak)
(getRawPerf base)
getRawPerf rc = perf $ fmap metric ((M.lookup bench . results) rc)
type NormFun a =(a -> Double) -> a -> a -> NormPerf
normalizePercent :: RawPerf -> RawPerf -> PerfMonad NormPerf
normalizePercent = normalize normP
normalizeRatio :: RawPerf -> RawPerf -> PerfMonad NormPerf
normalizeRatio = normalize normR
normalize :: NormFun RawPerf
-> RawPerf
-> RawPerf
-> PerfMonad NormPerf
normalize n base@(RawTime _) peak@(RawTime _) =
return(n rawPerfToDouble base peak)
normalize n base@(RawSize _) peak@(RawSize _) =
return(n rawPerfToDouble base peak)
normalize _ _ _ = throwError "Can not normalize a size by time"
normP :: NormFun a
normP = norm Percent (\base peak -> (peak / base) * 100)
normR :: NormFun a
normR = norm Ratio (\base peak -> (base / peak))
-- TODO: use the intervals to compute the resulting interval
norm :: (Estimate Double -> NormPerf) -- ^ NormPerf constructor
-> (Double -> Double -> Double) -- ^ Normalizing function
-> (a -> Double) -- ^ Conversion to double
-> a -> a -- ^ Values to normalize
-> NormPerf
norm c f toDouble base peak =
c (mkPointEstimate mkStddev (f (toDouble base) (toDouble peak)))
where mkStddev = fromIntegral :: Int -> Double
summarize :: Summary -> [PerfData] -> PerfMonad PerfData
summarize how perfData =
case (normData, rawData) of
([], []) -> return NoResult
(nd, []) -> summarizeNorm how nd
([], rd) -> summarizeRaw how rd
_ -> throwError "Mixed raw and norm results in column"
where
normData = getData (\p -> case p of Basic (Norm n) -> Just n ; _ -> Nothing)
rawData = getData (\p -> case p of Basic (Raw r) -> Just r ; _ -> Nothing)
getData f = (catMaybes . map f) perfData
summarizeRaw :: Summary -> [RawPerf] -> PerfMonad PerfData
summarizeRaw how rawPerfs =
case (isTime rawPerfs, isSize rawPerfs) of
(True, _) -> summarizeRaw' how ExecTime RawTime rawPerfs
(_, True) -> summarizeRaw' how (MemSize . round) RawSize rawPerfs
_ -> throwError "Can only summarize column with time or size"
where
isTime = all (\r -> case r of RawTime _ -> True; RawSize _ -> False)
isSize = all (\r -> case r of RawSize _ -> True; RawTime _ -> False)
summarizeRaw' :: Summary -- ^ what kind of summary
-> (Double -> a) -- ^ rounding function
-> (Estimate a -> RawPerf) -- ^ RawPerf constructor
-> [RawPerf] -- ^ Performance numbers to summary
-> PerfMonad PerfData
summarizeRaw' how roundFun makeRaw rawPerfs =
return $ Summary how (Raw (makeRaw (fmap roundFun (computeSummary how vec))))
where
vec = V.fromList (map rawPerfToDouble rawPerfs)
summarizeNorm :: Summary -> [NormPerf] -> PerfMonad PerfData
summarizeNorm how normPerfs =
case (isPercent normPerfs, isRatio normPerfs) of
(True, _) -> summarizeNorm' how Percent normPerfs
(_, True) -> summarizeNorm' how Ratio normPerfs
_ -> throwError "Can only summarize column with percent or ratio"
where
isPercent = all (\r -> case r of Percent _ -> True; Ratio _ -> False)
isRatio = all (\r -> case r of Percent _ -> False; Ratio _ -> True)
summarizeNorm' :: Summary
-> (Estimate Double -> NormPerf)
-> [NormPerf]
-> PerfMonad PerfData
summarizeNorm' how makeNorm normPerfs =
return $ Summary how (Norm (makeNorm (computeSummary how vec)))
where
vec = V.fromList (map normPerfToDouble normPerfs)
|
dmpots/fibon
|
tools/fibon-analyse/Fibon/Analyse/Analysis.hs
|
bsd-3-clause
| 7,781 | 0 | 15 | 2,120 | 2,463 | 1,268 | 1,195 | 174 | 6 |
-- ------------------------------------------------------------
{- |
Module : Yuuko.Text.XML.HXT.Arrow.XmlIOStateArrow
Copyright : Copyright (C) 2005 Uwe Schmidt
License : MIT
Maintainer : Uwe Schmidt ([email protected])
Stability : experimental
Portability: portable
Version : $Id: XmlIOStateArrow.hs,v 1.39 2006/11/09 20:27:42 hxml Exp $
the basic state arrows for XML processing
A state is needed for global processing options,
like encoding options, document base URI, trace levels
and error message handling
The state is separated into a user defined state
and a system state. The system state contains variables
for error message handling, for tracing, for the document base
for accessing XML documents with relative references, e.g. DTDs,
and a global key value store. This assoc list has strings as keys
and lists of XmlTrees as values. It is used to store arbitrary
XML and text values, e.g. user defined global options.
The user defined part of the store is in the default case empty, defined as ().
It can be extended with an arbitray data type
-}
-- ------------------------------------------------------------
module Yuuko.Text.XML.HXT.Arrow.XmlIOStateArrow
( -- * Data Types
XIOState(..),
XIOSysState(..),
IOStateArrow,
IOSArrow,
-- * Running Arrows
initialState,
initialSysState,
runX,
-- * User State Manipulation
getUserState,
setUserState,
changeUserState,
withExtendedUserState,
withOtherUserState,
-- * Global System State Access
getSysParam,
changeSysParam,
setParamList,
setParam,
unsetParam,
getParam,
getAllParams,
getAllParamsString,
setParamString,
getParamString,
setParamInt,
getParamInt,
-- * Error Message Handling
clearErrStatus,
setErrStatus,
getErrStatus,
setErrMsgStatus,
setErrorMsgHandler,
errorMsgStderr,
errorMsgCollect,
errorMsgStderrAndCollect,
errorMsgIgnore,
getErrorMessages,
filterErrorMsg,
issueWarn,
issueErr,
issueFatal,
setDocumentStatus,
setDocumentStatusFromSystemState,
documentStatusOk,
-- * Document Base
setBaseURI,
getBaseURI,
changeBaseURI,
setDefaultBaseURI,
getDefaultBaseURI,
runInLocalURIContext,
-- * Tracing
setTraceLevel,
getTraceLevel,
withTraceLevel,
trace,
traceMsg,
traceValue,
traceString,
traceSource,
traceTree,
traceDoc,
traceState,
-- * URI Manipulation
expandURIString,
expandURI,
mkAbsURI,
getFragmentFromURI,
getPathFromURI,
getPortFromURI,
getQueryFromURI,
getRegNameFromURI,
getSchemeFromURI,
getUserInfoFromURI,
-- * Mime Type Handling
setMimeTypeTable,
setMimeTypeTableFromFile
)
where
import Control.Arrow -- arrow classes
import Yuuko.Control.Arrow.ArrowList
import Yuuko.Control.Arrow.ArrowIf
import Yuuko.Control.Arrow.ArrowTree
import Yuuko.Control.Arrow.ArrowIO
import Yuuko.Control.Arrow.IOStateListArrow
import Control.Monad ( mplus )
import Control.DeepSeq
import Yuuko.Text.XML.HXT.DOM.Interface
import Yuuko.Text.XML.HXT.Arrow.XmlArrow
import Yuuko.Text.XML.HXT.Arrow.Edit
( addHeadlineToXmlDoc
, treeRepOfXmlDoc
, indentDoc
)
import Data.Maybe
import Network.URI
( URI
, escapeURIChar
, isUnescapedInURI
, nonStrictRelativeTo
, parseURIReference
, uriAuthority
, uriFragment
, uriPath
, uriPort
, uriQuery
, uriRegName
, uriScheme
, uriUserInfo
)
import System.IO
( hPutStrLn
, hFlush
, stderr
)
import System.Directory
( getCurrentDirectory
)
-- ------------------------------------------------------------
{- $datatypes -}
-- |
-- predefined system state data type with all components for the
-- system functions, like trace, error handling, ...
data XIOSysState = XIOSys { xio_trace :: ! Int
, xio_errorStatus :: ! Int
, xio_errorModule :: ! String
, xio_errorMsgHandler :: String -> IO ()
, xio_errorMsgCollect :: ! Bool
, xio_errorMsgList :: ! XmlTrees
, xio_baseURI :: ! String
, xio_defaultBaseURI :: ! String
, xio_attrList :: ! (AssocList String XmlTrees)
, xio_mimeTypes :: MimeTypeTable
}
instance NFData XIOSysState where
rnf (XIOSys tr es em _emh emc eml bu du al _mt)
= rnf tr `seq` rnf es `seq` rnf em `seq` rnf emc `seq` rnf eml `seq` rnf bu `seq` rnf du `seq` rnf al
-- |
-- state datatype consists of a system state and a user state
-- the user state is not fixed
data XIOState us = XIOState { xio_sysState :: ! XIOSysState
, xio_userState :: ! us
}
instance (NFData us) => NFData (XIOState us) where
rnf (XIOState sys usr) = rnf sys `seq` rnf usr
-- |
-- The arrow type for stateful arrows
type IOStateArrow s b c = IOSLA (XIOState s) b c
-- |
-- The arrow for stateful arrows with no user defined state
type IOSArrow b c = IOStateArrow () b c
-- ------------------------------------------------------------
-- | the default global state, used as initial state when running an 'IOSArrow' with 'runIOSLA' or
-- 'runX'
initialState :: us -> XIOState us
initialState s = XIOState { xio_sysState = initialSysState
, xio_userState = s
}
initialSysState :: XIOSysState
initialSysState = XIOSys { xio_trace = 0
, xio_errorStatus = c_ok
, xio_errorModule = ""
, xio_errorMsgHandler = hPutStrLn stderr
, xio_errorMsgCollect = False
, xio_errorMsgList = []
, xio_baseURI = ""
, xio_defaultBaseURI = ""
, xio_attrList = []
, xio_mimeTypes = defaultMimeTypeTable
}
-- ------------------------------------------------------------
-- |
-- apply an 'IOSArrow' to an empty root node with 'initialState' () as initial state
--
-- the main entry point for running a state arrow with IO
--
-- when running @ runX f@ an empty XML root node is applied to @f@.
-- usually @f@ will start with a constant arrow (ignoring the input), e.g. a 'Yuuko.Text.XML.HXT.Arrow.ReadDocument.readDocument' arrow.
--
-- for usage see examples with 'Yuuko.Text.XML.HXT.Arrow.WriteDocument.writeDocument'
--
-- if input has to be feed into the arrow use 'Yuuko.Control.Arrow.IOStateListArrow.runIOSLA' like in @ runIOSLA f emptyX inputDoc @
runX :: IOSArrow XmlTree c -> IO [c]
runX = runXIOState (initialState ())
runXIOState :: XIOState s -> IOStateArrow s XmlTree c -> IO [c]
runXIOState s0 f
= do
(_finalState, res) <- runIOSLA (emptyRoot >>> f) s0 undefined
return res
where
emptyRoot = root [] []
-- ------------------------------------------------------------
{- user state -}
-- | read the user defined part of the state
getUserState :: IOStateArrow s b s
getUserState
= IOSLA $ \ s _ ->
return (s, [xio_userState s])
-- | change the user defined part of the state
changeUserState :: (b -> s -> s) -> IOStateArrow s b b
changeUserState cf
= IOSLA $ \ s v ->
let s' = s { xio_userState = cf v (xio_userState s) }
in return (s', [v])
-- | set the user defined part of the state
setUserState :: IOStateArrow s s s
setUserState
= changeUserState const
-- | extend user state
--
-- Run an arrow with an extended user state component, The old component
-- is stored together with a new one in a pair, the arrow is executed with this
-- extended state, and the augmented state component is removed form the state
-- when the arrow has finished its execution
withExtendedUserState :: s1 -> IOStateArrow (s1, s0) b c -> IOStateArrow s0 b c
withExtendedUserState initS1 f
= IOSLA $ \ s0 x ->
do
~(finalS, res) <- runIOSLA f ( XIOState { xio_sysState = xio_sysState s0
, xio_userState = (initS1, xio_userState s0)
}
) x
return ( XIOState { xio_sysState = xio_sysState finalS
, xio_userState = snd (xio_userState finalS)
}
, res
)
-- | change the type of user state
--
-- This conversion is useful, when running a state arrow with another
-- structure of the user state, e.g. with () when executing some IO arrows
withOtherUserState :: s1 -> IOStateArrow s1 b c -> IOStateArrow s0 b c
withOtherUserState s1 f
= IOSLA $ \ s x ->
do
(s', res) <- runIOSLA f ( XIOState { xio_sysState = xio_sysState s
, xio_userState = s1
}
) x
return ( XIOState { xio_sysState = xio_sysState s'
, xio_userState = xio_userState s
}
, res
)
-- ------------------------------------------------------------
{- $system state params -}
getSysParam :: (XIOSysState -> c) -> IOStateArrow s b c
getSysParam f
= IOSLA $ \ s _x ->
return (s, (:[]) . f . xio_sysState $ s)
changeSysParam :: (b -> XIOSysState -> XIOSysState) -> IOStateArrow s b b
changeSysParam cf
= ( IOSLA $ \ s v ->
let s' = changeSysState (cf v) s
in return (s', [v])
)
where
changeSysState css s = s { xio_sysState = css (xio_sysState s) }
-- | store a single XML tree in global state under a given attribute name
setParam :: String -> IOStateArrow s XmlTree XmlTree
setParam n
= (:[]) ^>> setParamList n
-- | store a list of XML trees in global system state under a given attribute name
setParamList :: String -> IOStateArrow s XmlTrees XmlTree
setParamList n
= changeSysParam addE
>>>
arrL id
where
addE x s = s { xio_attrList = addEntry n x (xio_attrList s) }
-- | remove an entry in global state, arrow input remains unchanged
unsetParam :: String -> IOStateArrow s b b
unsetParam n
= changeSysParam delE
where
delE _ s = s { xio_attrList = delEntry n (xio_attrList s) }
-- | read an attribute value from global state
getParam :: String -> IOStateArrow s b XmlTree
getParam n
= getAllParams
>>>
arrL (lookup1 n)
-- | read all attributes from global state
getAllParams :: IOStateArrow s b (AssocList String XmlTrees)
getAllParams
= getSysParam xio_attrList
-- | read all attributes from global state
-- and convert the values to strings
getAllParamsString :: IOStateArrow s b (AssocList String String)
getAllParamsString
= getAllParams
>>>
listA ( unlistA
>>>
second (xshow unlistA)
)
setParamString :: String -> String -> IOStateArrow s b b
setParamString n v
= perform ( txt v
>>>
setParam n
)
-- | read a string value from global state,
-- if parameter not set \"\" is returned
getParamString :: String -> IOStateArrow s b String
getParamString n
= xshow (getParam n)
-- | store an int value in global state
setParamInt :: String -> Int -> IOStateArrow s b b
setParamInt n v
= setParamString n (show v)
-- | read an int value from global state
--
-- > getParamInt 0 myIntAttr
getParamInt :: Int -> String -> IOStateArrow s b Int
getParamInt def n
= getParamString n
>>^
(\ x -> if null x then def else read x)
-- ------------------------------------------------------------
-- | reset global error variable
changeErrorStatus :: (Int -> Int -> Int) -> IOStateArrow s Int Int
changeErrorStatus f
= changeSysParam (\ l s -> s { xio_errorStatus = f l (xio_errorStatus s) })
clearErrStatus :: IOStateArrow s b b
clearErrStatus
= perform (constA 0 >>> changeErrorStatus min)
-- | set global error variable
setErrStatus :: IOStateArrow s Int Int
setErrStatus
= changeErrorStatus max
-- | read current global error status
getErrStatus :: IOStateArrow s XmlTree Int
getErrStatus
= getSysParam xio_errorStatus
-- | raise the global error status level to that of the input tree
setErrMsgStatus :: IOStateArrow s XmlTree XmlTree
setErrMsgStatus
= perform ( getErrorLevel
>>>
setErrStatus
)
-- | set the error message handler and the flag for collecting the errors
setErrorMsgHandler :: Bool -> (String -> IO ()) -> IOStateArrow s b b
setErrorMsgHandler c f
= changeSysParam cf
where
cf _ s = s { xio_errorMsgHandler = f
, xio_errorMsgCollect = c }
-- | error message handler for output to stderr
sysErrorMsg :: IOStateArrow s XmlTree XmlTree
sysErrorMsg
= perform ( getErrorLevel &&& getErrorMsg
>>>
arr formatErrorMsg
>>>
( IOSLA $ \ s e ->
do
(xio_errorMsgHandler . xio_sysState $ s) e
return (s, undefined)
)
)
where
formatErrorMsg (level, msg) = "\n" ++ errClass level ++ ": " ++ msg
errClass l
= fromMaybe "fatal error" . lookup l $ msgList
where
msgList = [ (c_ok, "no error")
, (c_warn, "warning")
, (c_err, "error")
, (c_fatal, "fatal error")
]
-- | the default error message handler: error output to stderr
errorMsgStderr :: IOStateArrow s b b
errorMsgStderr = setErrorMsgHandler False (hPutStrLn stderr)
-- | error message handler for collecting errors
errorMsgCollect :: IOStateArrow s b b
errorMsgCollect = setErrorMsgHandler True (const $ return ())
-- | error message handler for output to stderr and collecting
errorMsgStderrAndCollect :: IOStateArrow s b b
errorMsgStderrAndCollect = setErrorMsgHandler True (hPutStrLn stderr)
-- | error message handler for ignoring errors
errorMsgIgnore :: IOStateArrow s b b
errorMsgIgnore = setErrorMsgHandler False (const $ return ())
-- |
-- if error messages are collected by the error handler for
-- processing these messages by the calling application,
-- this arrow reads the stored messages and clears the error message store
getErrorMessages :: IOStateArrow s b XmlTree
getErrorMessages
= getSysParam (reverse . xio_errorMsgList) -- reverse the list of errors
>>>
clearErrorMsgList -- clear the error list in the system state
>>>
arrL id
clearErrorMsgList :: IOStateArrow s b b
clearErrorMsgList
= changeSysParam (\ _ s -> s { xio_errorMsgList = [] } )
addToErrorMsgList :: IOStateArrow s XmlTree XmlTree
addToErrorMsgList
= changeSysParam cf
where
cf t s = if xio_errorMsgCollect s
then s { xio_errorMsgList = t : xio_errorMsgList s }
else s
-- ------------------------------------------------------------
-- |
-- filter error messages from input trees and issue errors
filterErrorMsg :: IOStateArrow s XmlTree XmlTree
filterErrorMsg
= ( setErrMsgStatus
>>>
sysErrorMsg
>>>
addToErrorMsgList
>>>
none
)
`when`
isError
-- | generate a warnig message
issueWarn :: String -> IOStateArrow s b b
issueWarn msg = perform (warn msg >>> filterErrorMsg)
-- | generate an error message
issueErr :: String -> IOStateArrow s b b
issueErr msg = perform (err msg >>> filterErrorMsg)
-- | generate a fatal error message, e.g. document not found
issueFatal :: String -> IOStateArrow s b b
issueFatal msg = perform (fatal msg >>> filterErrorMsg)
-- |
-- add the error level and the module where the error occured
-- to the attributes of a document root node and remove the children when level is greater or equal to 'c_err'.
-- called by 'setDocumentStatusFromSystemState' when the system state indicates an error
setDocumentStatus :: Int -> String -> IOStateArrow s XmlTree XmlTree
setDocumentStatus level msg
= ( addAttrl ( sattr a_status (show level)
<+>
sattr a_module msg
)
>>>
( if level >= c_err
then setChildren []
else this
)
)
`when`
isRoot
-- |
-- check whether the error level attribute in the system state
-- is set to error, in this case the children of the document root are
-- removed and the module name where the error occured and the error level are added as attributes with 'setDocumentStatus'
-- else nothing is changed
setDocumentStatusFromSystemState :: String -> IOStateArrow s XmlTree XmlTree
setDocumentStatusFromSystemState msg
= setStatus $< getErrStatus
where
setStatus level
| level <= c_warn = this
| otherwise = setDocumentStatus level msg
-- |
-- check whether tree is a document root and the status attribute has a value less than 'c_err'
documentStatusOk :: ArrowXml a => a XmlTree XmlTree
documentStatusOk
= isRoot
>>>
( (getAttrValue a_status
>>>
isA (\ v -> null v || ((read v)::Int) <= c_warn)
)
`guards`
this
)
-- ------------------------------------------------------------
-- | set the base URI of a document, used e.g. for reading includes, e.g. external entities,
-- the input must be an absolute URI
setBaseURI :: IOStateArrow s String String
setBaseURI
= changeSysParam (\ b s -> s { xio_baseURI = b } )
>>>
traceValue 2 (("setBaseURI: new base URI is " ++) . show)
-- | read the base URI from the globale state
getBaseURI :: IOStateArrow s b String
getBaseURI
= getSysParam xio_baseURI
>>>
( ( getDefaultBaseURI
>>>
setBaseURI
>>>
getBaseURI
)
`when`
isA null -- set and get it, if not yet done
)
-- | change the base URI with a possibly relative URI, can be used for
-- evaluating the xml:base attribute. Returns the new absolute base URI.
-- Fails, if input is not parsable with parseURIReference
--
-- see also: 'setBaseURI', 'mkAbsURI'
changeBaseURI :: IOStateArrow s String String
changeBaseURI
= mkAbsURI
>>>
setBaseURI
-- | set the default base URI, if parameter is null, the system base (@ file:\/\/\/\<cwd\>\/ @) is used,
-- else the parameter, must be called before any document is read
setDefaultBaseURI :: String -> IOStateArrow s b String
setDefaultBaseURI base
= ( if null base
then arrIO getDir
else constA base
)
>>>
changeSysParam (\ b s -> s { xio_defaultBaseURI = b } )
>>>
traceValue 2 (("setDefaultBaseURI: new default base URI is " ++) . show)
where
getDir _ = do
cwd <- getCurrentDirectory
return ("file://" ++ normalize cwd ++ "/")
-- under Windows getCurrentDirectory returns something like: "c:\path\to\file"
-- backslaches are not allowed in URIs and paths must start with a /
-- so this is transformed into "/c:/path/to/file"
normalize wd'@(d : ':' : _)
| d `elem` ['A'..'Z'] || d `elem` ['a'..'z']
= '/' : concatMap win32ToUriChar wd'
normalize wd'
= concatMap escapeNonUriChar wd'
win32ToUriChar '\\' = "/"
win32ToUriChar c = escapeNonUriChar c
escapeNonUriChar c = escapeURIChar isUnescapedInURI c -- from Network.URI
-- | get the default base URI
getDefaultBaseURI :: IOStateArrow s b String
getDefaultBaseURI
= getSysParam xio_defaultBaseURI -- read default uri in system state
>>>
( setDefaultBaseURI "" -- set the default uri in system state
>>>
getDefaultBaseURI ) `when` isA null -- when uri not yet set
-- ------------------------------------------------------------
-- | remember base uri, run an arrow and restore the base URI, used with external entity substitution
runInLocalURIContext :: IOStateArrow s b c -> IOStateArrow s b c
runInLocalURIContext f
= ( getBaseURI &&& this )
>>>
( this *** listA f )
>>>
( setBaseURI *** this )
>>>
arrL snd
-- ------------------------------------------------------------
-- | set the global trace level
setTraceLevel :: Int -> IOStateArrow s b b
setTraceLevel l
= changeSysParam (\ _ s -> s { xio_trace = l } )
-- | read the global trace level
getTraceLevel :: IOStateArrow s b Int
getTraceLevel
= getSysParam xio_trace
-- | run an arrow with a given trace level, the old trace level is restored after the arrow execution
withTraceLevel :: Int -> IOStateArrow s b c -> IOStateArrow s b c
withTraceLevel level f
= ( getTraceLevel &&& this )
>>>
( setTraceLevel level *** listA f )
>>>
( restoreTraceLevel *** this )
>>>
arrL snd
where
restoreTraceLevel :: IOStateArrow s Int Int
restoreTraceLevel
= setTraceLevel $< this
-- | apply a trace arrow and issue message to stderr
trace :: Int -> IOStateArrow s b String -> IOStateArrow s b b
trace level trc
= perform ( trc
>>>
arrIO (\ s -> ( do
hPutStrLn stderr s
hFlush stderr
)
)
)
`when` ( getTraceLevel
>>>
isA (>= level)
)
-- | trace the current value transfered in a sequence of arrows.
--
-- The value is formated by a string conversion function. This is a substitute for
-- the old and less general traceString function
traceValue :: Int -> (b -> String) -> IOStateArrow s b b
traceValue level trc
= trace level (arr $ (('-' : "- (" ++ show level ++ ") ") ++) . trc)
-- | an old alias for 'traceValue'
traceString :: Int -> (b -> String) -> IOStateArrow s b b
traceString = traceValue
-- | issue a string message as trace
traceMsg :: Int -> String -> IOStateArrow s b b
traceMsg level msg
= traceValue level (const msg)
-- | issue the source representation of a document if trace level >= 3
--
-- for better readability the source is formated with indentDoc
traceSource :: IOStateArrow s XmlTree XmlTree
traceSource
= trace 3 $
xshow
( choiceA [ isRoot :-> ( indentDoc
>>>
getChildren
)
, isElem :-> ( root [] [this]
>>> indentDoc
>>> getChildren
>>> isElem
)
, this :-> this
]
)
-- | issue the tree representation of a document if trace level >= 4
traceTree :: IOStateArrow s XmlTree XmlTree
traceTree
= trace 4 $
xshow ( treeRepOfXmlDoc
>>>
addHeadlineToXmlDoc
>>>
getChildren
)
-- | trace a main computation step
-- issue a message when trace level >= 1, issue document source if level >= 3, issue tree when level is >= 4
traceDoc :: String -> IOStateArrow s XmlTree XmlTree
traceDoc msg
= traceMsg 1 msg
>>>
traceSource
>>>
traceTree
-- | trace the global state
traceState :: IOStateArrow s b b
traceState
= perform ( xshow ( (getAllParams >>. concat)
>>>
applyA (arr formatParam)
)
>>>
traceValue 2 ("global state:\n" ++)
)
where
-- formatParam :: (String, XmlTrees) -> IOStateArrow s b1 XmlTree
formatParam (n, v)
= mkelem "param" [sattr "name" n] [arrL (const v)] <+> txt "\n"
-- ----------------------------------------------------------
-- | parse a URI reference, in case of a failure try to escape special chars
-- and try parsing again
parseURIReference' :: String -> Maybe URI
parseURIReference' uri
= parseURIReference uri
`mplus`
parseURIReference uri'
where
uri' = concatMap ( escapeURIChar isUnescapedInURI) uri
-- | compute the absolut URI for a given URI and a base URI
expandURIString :: String -> String -> Maybe String
expandURIString uri base
= do
base' <- parseURIReference' base
uri' <- parseURIReference' uri
abs' <- nonStrictRelativeTo uri' base'
return $ show abs'
-- | arrow variant of 'expandURIString', fails if 'expandURIString' returns Nothing
expandURI :: ArrowXml a => a (String, String) String
expandURI
= arrL (maybeToList . uncurry expandURIString)
-- | arrow for expanding an input URI into an absolute URI using global base URI, fails if input is not a legal URI
mkAbsURI :: IOStateArrow s String String
mkAbsURI
= ( this &&& getBaseURI ) >>> expandURI
-- | arrow for selecting the scheme (protocol) of the URI, fails if input is not a legal URI.
--
-- See Network.URI for URI components
getSchemeFromURI :: ArrowList a => a String String
getSchemeFromURI = getPartFromURI scheme
where
scheme = init . uriScheme
-- | arrow for selecting the registered name (host) of the URI, fails if input is not a legal URI
getRegNameFromURI :: ArrowList a => a String String
getRegNameFromURI = getPartFromURI host
where
host = maybe "" uriRegName . uriAuthority
-- | arrow for selecting the port number of the URI without leading \':\', fails if input is not a legal URI
getPortFromURI :: ArrowList a => a String String
getPortFromURI = getPartFromURI port
where
port = dropWhile (==':') . maybe "" uriPort . uriAuthority
-- | arrow for selecting the user info of the URI without trailing \'\@\', fails if input is not a legal URI
getUserInfoFromURI :: ArrowList a => a String String
getUserInfoFromURI = getPartFromURI ui
where
ui = reverse . dropWhile (=='@') . reverse . maybe "" uriUserInfo . uriAuthority
-- | arrow for computing the path component of an URI, fails if input is not a legal URI
getPathFromURI :: ArrowList a => a String String
getPathFromURI = getPartFromURI uriPath
-- | arrow for computing the query component of an URI, fails if input is not a legal URI
getQueryFromURI :: ArrowList a => a String String
getQueryFromURI = getPartFromURI uriQuery
-- | arrow for computing the fragment component of an URI, fails if input is not a legal URI
getFragmentFromURI :: ArrowList a => a String String
getFragmentFromURI = getPartFromURI uriFragment
-- | arrow for computing the path component of an URI, fails if input is not a legal URI
getPartFromURI :: ArrowList a => (URI -> String) -> a String String
getPartFromURI sel
= arrL (maybeToList . getPart)
where
getPart s = do
uri <- parseURIReference' s
return (sel uri)
-- ------------------------------------------------------------
-- | set the table mapping of file extensions to mime types in the system state
--
-- Default table is defined in 'Yuuko.Text.XML.HXT.DOM.MimeTypeDefaults'.
-- This table is used when reading loacl files, (file: protocol) to determine the mime type
setMimeTypeTable :: MimeTypeTable -> IOStateArrow s b b
setMimeTypeTable mtt
= changeSysParam (\ _ s -> s {xio_mimeTypes = mtt})
-- | set the table mapping of file extensions to mime types by an external config file
--
-- The config file must follow the conventions of /etc/mime.types on a debian linux system,
-- that means all empty lines and all lines starting with a # are ignored. The other lines
-- must consist of a mime type followed by a possible empty list of extensions.
-- The list of extenstions and mime types overwrites the default list in the system state
-- of the IOStateArrow
setMimeTypeTableFromFile :: FilePath -> IOStateArrow s b b
setMimeTypeTableFromFile file
= setMimeTypeTable $< arrIO0 ( readMimeTypeTable file)
-- ------------------------------------------------------------
|
nfjinjing/yuuko
|
src/Yuuko/Text/XML/HXT/Arrow/XmlIOStateArrow.hs
|
bsd-3-clause
| 26,577 | 421 | 17 | 6,340 | 5,354 | 2,910 | 2,444 | 538 | 4 |
{-# LANGUAGE ExtendedDefaultRules, OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
module Main where
import Interpreter
import Language.Haskell.TH.Expand
import Control.Exception (throwIO)
import Control.Monad (filterM)
import Control.Monad.Trans (liftIO)
import Data.List (intercalate)
import Data.String (fromString)
import Data.Text (Text)
import qualified Data.Text as T
import GHC.Paths (libdir)
import Language.Haskell.Exts (ParseResult (..))
import Language.Haskell.Exts (parseFile, prettyPrint)
import Language.Haskell.Interpreter (OptionVal (..), infer)
import Language.Haskell.Interpreter (installedModulesInScope)
import Language.Haskell.Interpreter (interpret, runInterpreter)
import Language.Haskell.Interpreter (searchPath, set)
import qualified Language.Haskell.Interpreter as GHC
import Language.Haskell.Interpreter.Unsafe (unsafeSetGhcOption)
import Shelly (cmd, shelly, silently)
import Shelly (test_d)
import System.Environment (getArgs, setEnv)
import System.IO.Temp
default (Text)
main :: IO ()
main = do
fp : _ <- getArgs
ParseOk m <- parseFile fp
let modified = traceTHSplices m
dbs <- shelly $ silently $ do
snapPkgDb <- init . T.unpack <$> cmd "stack" "path" "--snapshot-pkg-db"
loclPkgDb <- init . T.unpack <$> cmd "stack" "path" "--local-pkg-db"
filterM (test_d . fromString) [snapPkgDb, loclPkgDb, libdir ++ "/package.conf.d"]
setEnv "GHC_PACKAGE_PATH" $ intercalate ":" dbs
ans <- runInterpreter $ withSystemTempDirectory "expandth" $ \dir -> do
ps <- GHC.get searchPath
set [searchPath := (dir : ps)]
mapM_ (unsafeSetGhcOption . ("-package-db " ++)) dbs
set [installedModulesInScope := True]
liftIO $ writeFile (fp ++ ".alt") $ prettyPrint modified
withHSEModule modified $ interpret "___table" infer
case ans of
Left (GHC.WontCompile errs) -> mapM_ (putStrLn . GHC.errMsg) errs
Left exc -> throwIO exc
Right dic -> putStrLn $ prettyPrint $ expandTH dic m
|
konn/expandth
|
app/Main.hs
|
bsd-3-clause
| 2,473 | 0 | 16 | 796 | 604 | 327 | 277 | 47 | 3 |
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module Text.Scalar ( module Text.Scalar.Types
, readScalarString
, readScalarFile
, parseScalar
, orderPages
) where
import Data.Maybe (mapMaybe)
import Data.RDF
import qualified Data.Map as Map
import qualified Data.Text as T
import Text.Scalar.RDF
import Text.Scalar.Types
import Control.Monad.Except
-- | Reads a Scalar RDF/XML string into in-memory RDF.
readScalarString :: String -> ScalarM ScalarRDF
readScalarString s = case parseString (XmlParser Nothing Nothing) (T.pack s) of
Left err -> throwError (RdfError err)
Right rdf -> return rdf
-- | Reads a Scalar RDF/XML file into in-memory RDF.
readScalarFile :: String -> IO ScalarRDF
readScalarFile = fmap fromEither . parseFile (XmlParser Nothing Nothing)
-- | Parses the RDF into a 'Scalar' (a list of 'Page's and (eventually) some contextual information).
parseScalar :: RDF rdf => rdf -> ScalarOptions -> ScalarM Scalar
parseScalar rdf opts = do
paths <- extractAllPaths rdf
pages <- extractAllPages rdf
return $ Scalar opts paths pages
-- | Collects the 'Page's into a list according to the 'PageOrderStrategy',
-- or returns an error
orderPages :: Scalar -> ScalarM [Page]
orderPages scalar@Scalar { scalarOptions, scalarPages } =
case orderPagesBy scalarOptions of
IndexPath -> getPath scalar (mkPathID "index")
Path s -> getPath scalar (mkPathID s)
None -> return $ Map.elems scalarPages
-- | Attempts to get the specified 'PathID' or returns an error.
getPath :: Scalar -> PathID -> ScalarM [Page]
getPath Scalar { scalarPaths, scalarPages } path =
maybe (throwError (ScalarError err)) return pathResult
where pathResult = do
path' <- Map.lookup path scalarPaths
return $ mapMaybe (`Map.lookup` scalarPages) path'
err = "Could not find path " ++ show (unPathID path) ++ ". Available paths are:\n" ++
concatMap ((\xs -> "- " ++ xs ++ "\n") . T.unpack . unPathID) (Map.keys scalarPaths)
|
corajr/scalar-convert
|
src/Text/Scalar.hs
|
bsd-3-clause
| 2,092 | 0 | 15 | 461 | 521 | 272 | 249 | 39 | 3 |
module Fifteen where
import Data.Foldable (maximumBy)
import Data.Ord (comparing)
import Text.Parsec hiding (State)
import Text.Parsec.String
data Properties = Properties { capacity :: Int
, durability :: Int
, flavor :: Int
, texture :: Int
, calories :: Int
}
data Ingredient = Ingredient { name :: String
, properties :: Properties
}
data Quantity = Quantity { teaspoons :: Int
, ingredient :: Ingredient
}
data Cookie = Cookie { quantities :: [Quantity] }
totalCalories :: Cookie -> Int
totalCalories = flip totalOf calories
totalScore :: Cookie -> Int
totalScore cookie = product totals
where
totals = map (totalOf cookie) [capacity, durability, flavor, texture]
totalOf :: Cookie -> (Properties -> Int) -> Int
totalOf (Cookie qs) f = max 0 (sum $ map (\q -> teaspoons q * (f . properties . ingredient) q) qs)
{-
butterscotch = Ingredient "Butterscotch" Properties { capacity = -1, durability = -2, flavor = 6, texture = 3, calories = 8 }
cinnamon = Ingredient "Cinnamon" Properties { capacity = 2, durability = 3, flavor = -2, texture = -1, calories = 3 }
exampleCookie = Cookie [ Quantity 44 butterscotch, Quantity 56 cinnamon ]
-}
bestCookie :: [Ingredient] -> Cookie
bestCookie = maximumBy (comparing totalScore) . possibleCookies 100
possibleCookies :: Int -> [Ingredient] -> [Cookie]
possibleCookies maxTeaspoons ingredients = map Cookie (combos maxTeaspoons ingredients)
where
combos _ [] = []
combos tsp [i] = [[Quantity tsp i]]
combos tsp (i:is) = concatMap (\n -> map ([Quantity n i] ++) (combos (tsp - n) is)) [0..tsp]
parseIngredient :: Parser Ingredient
parseIngredient = Ingredient <$> (many1 letter <* string ": ") <*> parseProperties
parseProperties :: Parser Properties
parseProperties = Properties <$> (string "capacity " *> number <* string ", ")
<*> (string "durability " *> number <* string ", ")
<*> (string "flavor " *> number <* string ", ")
<*> (string "texture " *> number <* string ", ")
<*> (string "calories " *> number)
number :: Parser Int
number = do
sign <- try (string "-") <|> return ""
digits <- many1 digit
return . read $ (sign ++ digits)
parseFile :: String -> IO (Either ParseError [Ingredient])
parseFile = parseFromFile (many1 (parseIngredient <* newline) <* eof)
fifteen :: IO (Int, Int)
fifteen = do
result <- parseFile "input/15.txt"
case result of
Right ingredients ->
let cookies = possibleCookies 100 ingredients
bestScore = totalScore . maximumBy (comparing totalScore)
in
return (bestScore cookies, bestScore (filter ((500 ==) . totalCalories) cookies))
Left err -> error (show err)
|
purcell/adventofcodeteam
|
app/Fifteen.hs
|
bsd-3-clause
| 3,089 | 0 | 19 | 964 | 862 | 454 | 408 | 53 | 3 |
module Sprite.Ship where
import Graphics.Rendering.OpenGL
import Sprite.Class
import Sprite.Colors
data Ship = Ship (Vector3 Float) Float
instance Sprite Ship where
pos (Ship p v) = p
draw (Ship p v) = do
preservingMatrix $ do
translate p
rotate (45 * v) (Vector3 0 1 0)
scale 0.1 0.1 (0.1::Float)
renderPrimitive Triangles $ do
materialAmbientAndDiffuse Front $= blue
materialSpecular Front $= Color4 0.8 0.8 0.8 1.0
materialShininess Front $= 128
vertex $ Vertex3 0 1 (0::Float)
vertex $ Vertex3 (-1) (-1) (0::Float)
vertex $ Vertex3 1 (-1) (0::Float)
update (Ship p v) = let Vector3 x y z = p
x' = x + 0.02 * v
p' = Vector3 x' y z
in Ship p' v
|
flazz/tooHS
|
src/Sprite/Ship.hs
|
bsd-3-clause
| 808 | 0 | 17 | 277 | 322 | 158 | 164 | 23 | 0 |
-- |
-- Module : Data.Array.Nikola.Backend.Flags
-- Copyright : (c) Geoffrey Mainland 2012
-- License : BSD-style
--
-- Maintainer : Geoffrey Mainland <[email protected]>
-- Stability : experimental
-- Portability : non-portable
module Data.Array.Nikola.Backend.Flags (
Dialect(..),
Flags(..),
defaultFlags,
ljust,
fromLJust
) where
import Data.Function (on)
import Data.Monoid (Monoid(..), Last(..))
import Text.PrettyPrint.Mainland
data Dialect = SequentialC
| OpenMP
| CUDA
| OpenCL
deriving (Eq, Ord, Enum, Show)
instance Pretty Dialect where
ppr = text . show
data Flags = Flags
{ fDialect :: Last Dialect -- ^ The language dialect to which we compile.
, fOptimize :: Last Int -- ^ Optimization level
, fVerbosity :: Last Int -- ^ Verbosity level
, fObsSharing :: Last Bool -- ^ Observer sharing
, fPprCols :: Last Int -- ^ Number of columns for pretty printing
, fFunction :: Last String -- ^ Name of function being compiled
, fOutput :: Last FilePath -- ^ Filename of output.
, fHelp :: Last Bool -- ^ Print help and exit.
} deriving (Eq, Show)
instance Monoid Flags where
mempty = emptyFlags
mappend = appendFlags
ljust :: a -> Last a
ljust = Last . Just
fromLJust :: (Flags -> Last a)
-> Flags
-> a
fromLJust fld f = case fld f of
Last Nothing -> fromLJust fld defaultFlags
Last (Just a) -> a
defaultFlags :: Flags
defaultFlags = Flags
{ fDialect = ljust CUDA
, fOptimize = ljust 0
, fVerbosity = ljust 0
, fObsSharing = ljust True
, fPprCols = ljust 80
, fFunction = mempty
, fOutput = mempty
, fHelp = ljust False
}
emptyFlags :: Flags
emptyFlags = Flags
{ fDialect = mempty
, fOptimize = mempty
, fVerbosity = mempty
, fObsSharing = mempty
, fPprCols = mempty
, fFunction = mempty
, fOutput = mempty
, fHelp = mempty
}
appendFlags :: Flags -> Flags -> Flags
appendFlags a b = Flags
{ fDialect = app fDialect a b
, fOptimize = app fOptimize a b
, fVerbosity = app fVerbosity a b
, fObsSharing = app fObsSharing a b
, fPprCols = app fPprCols a b
, fFunction = app fFunction a b
, fOutput = app fOutput a b
, fHelp = app fHelp a b
}
where
app f = mappend `on` f
|
mainland/nikola
|
src/Data/Array/Nikola/Backend/Flags.hs
|
bsd-3-clause
| 2,497 | 0 | 10 | 803 | 622 | 360 | 262 | 68 | 2 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Temperature.IT.Corpus
( corpus ) where
import Data.String
import Prelude
import Duckling.Locale
import Duckling.Resolve
import Duckling.Temperature.Types
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {locale = makeLocale IT Nothing}, testOptions, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (simple Celsius 37)
[ "37°C"
, "37 ° celsius"
, "37 ° centigradi"
, "37 gradi Celsius"
, "37 gradi Centigradi"
, "trentasette celsius"
, "trentasette gradi centigradi"
]
, examples (simple Celsius 1)
[ "1 grado centigrado"
]
, examples (simple Fahrenheit 70)
[ "70°F"
, "70 ° Fahrenheit"
, "70 gradi F"
, "70 gradi Fahreneit"
, "settanta Fahrenheit"
]
, examples (simple Degree 45)
[ "45°"
, "45 gradi"
]
, examples (simple Degree 1)
[ "1 grado"
]
]
|
facebookincubator/duckling
|
Duckling/Temperature/IT/Corpus.hs
|
bsd-3-clause
| 1,345 | 0 | 9 | 454 | 225 | 134 | 91 | 34 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ViewPatterns #-}
module Language.JQuery.Functions where
import Text.Blaze.Html
--import Language.JavaScript.AST
import Language.JQuery.Internal.Functions
import Language.JQuery.Internal.Types
jQuery :: (JQuerySelector sel, JQueryVariable a) => sel -> JQueryStmts a -> JQuery (Var a)
jQuery sel stmts = addJQuery sel stmts
-- | The typical jQuery chain operator:
--
-- > jQuery ".button" $ setCSS "display" "block"
-- > ~> setHTML (toHtml "Click me!")
-- > ~> addClass "visible"
(~>) :: JQueryStmts a -> JQueryStmts b -> JQueryStmts b
(~>) = JQSs_chain
--------------------------------------------------------------------------------
-- ** CSS
getCSS :: StringValue s => s -> JQueryStmts String
getCSS s = call "css" [valToExpr s]
setCSS :: (StringValue s1, StringValue s2) => s1 -> s2 -> JQueryStmts ()
setCSS s1 s2 = call "css" [valToExpr s1, valToExpr s2]
--------------------------------------------------------------------------------
-- ** Manipulation
--
-- *** Class Attribute
--
addClass :: StringValue s => s -> JQueryStmts ()
addClass s = call "addClass" [valToExpr s]
--
-- *** DOM Insertion, Inside
--
getHtml :: JQueryStmts Html
getHtml = call "html" []
setHtml :: HtmlValue html => html -> JQueryStmts ()
setHtml h = call "html" [valToExpr h]
|
mcmaniac/hs-jquery
|
src/Language/JQuery/Functions.hs
|
bsd-3-clause
| 1,505 | 0 | 10 | 249 | 334 | 182 | 152 | 25 | 1 |
{-# LANGUAGE DeriveDataTypeable, FlexibleContexts, OverloadedStrings #-}
module Main where
import Control.Applicative ((<$>), (<*>))
import Control.Failure (Failure)
import Control.Monad (liftM, when)
import Data.Aeson
import qualified Data.Aeson.Generic as AG
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as B
import Data.Conduit (MonadBaseControl, MonadResource)
import Data.Data (Data)
import Data.Function (on)
import Data.List (foldl', nub, sort, sortBy)
import qualified Data.Map as M
--import Data.Maybe (fromMaybe)
import qualified Data.Text as T
import Data.Time.Calendar (Day)
import Data.Time.LocalTime (ZonedTime, getZonedTime)
import Data.Time.Format (parseTime, formatTime)
import Data.Typeable (Typeable)
import Network (withSocketsDo)
import Network.HTTP.Conduit (withManager, Manager, HttpException)
import System.Console.GetOpt
import System.Directory (createDirectory, doesDirectoryExist)
import System.Environment (getArgs)
import System.FilePath (combine)
import System.Locale (defaultTimeLocale)
import Text.Blaze.Html.Renderer.Utf8
import Text.Blaze.Html5 hiding (map, head)
import qualified Text.Blaze.Html5 as H
import Text.Blaze.Html5.Attributes hiding (title, rows, accept, name, dir, start)
--import qualified Text.Blaze.Html5.Attributes as A
import qualified Scoring as S
import Strava
main :: IO ()
main = withSocketsDo $ do
argv <- getArgs
(opts, config) <- case getOpt Permute options argv of
(o, [cfname], []) -> do
cf <- B.readFile cfname
case decode' cf of
Just c -> return (foldl' (\opts f -> f opts) defaultOpts o, c)
Nothing -> fail "Could not parse config file"
(_, _, errs) ->
ioError $ userError $
concat errs ++ usageInfo "Usage: ba-winter-challenge [OPTION..] config-file" options
loadedScores <- if (clearCache opts)
then return M.empty
else loadScores config
(groups, rides) <- withManager $ \manager -> do
groups <- mapM (flip groupMembers manager) $ (challengeGroups config ++ challengeOthers config)
let members = nub $ sortBy (compare `on` snd) $ concatMap snd groups
rides <- mapM (\m@(_, uid) -> liftM (\x -> (m, filter (rideFilters config) x)) $ userRides uid (challengeStart config) (challengeEnd config) (1 + (maybe 0 S.currentRide $ M.lookup uid loadedScores)) manager) members
return (filter (flip elem (challengeGroups config) . snd . fst) groups, rides)
-- putStrLn "Collating..."
ensureDirectory (challengeDir config)
let scoreMap = foldl' addRides loadedScores rides
saveScores config scoreMap
let groupScores = sort $ map (S.scoreGroup scoreMap) groups
let userScores = sort $ map snd $ M.toList scoreMap
-- putStrLn "Group Scores:"
-- mapM_ (\g -> print (S.gname g, S.groupScore g)) groupScores
-- putStrLn "User Scores:"
-- mapM_ (\u -> print (S.name u, S.userScore u)) userScores
ztime <- getZonedTime
B.writeFile (combine (challengeDir config) "index.html") $ renderHtml $ render config ztime userScores groupScores
return ()
where
addRides :: M.Map Integer S.UserScore -> ((T.Text, Integer), [RideDetails]) -> M.Map Integer S.UserScore
addRides scoreMap ((name, uid), rides) = score `seq` M.insert uid score scoreMap
where
score = foldl' S.addScore (M.findWithDefault (S.emptyScore uid name) uid scoreMap) rides
ensureDirectory :: String -> IO ()
ensureDirectory dir = do
exists <- doesDirectoryExist dir
when (not exists) $ do
createDirectory dir
return ()
loadScores :: ChallengeConfig -> IO (M.Map Integer S.UserScore)
loadScores config = do
scoreFile <- BS.readFile (combine (challengeDir config) "scores.json")
return $ maybe M.empty toScoreMap $ AG.decode' $ B.pack $ BS.unpack $ scoreFile
saveScores config scoreMap = B.writeFile (combine (challengeDir config) "scores.json") $ AG.encode $ fromScoreMap scoreMap
rideFilters :: ChallengeConfig -> RideDetails -> Bool
rideFilters config = not . or . flip map (map T.toCaseFold $ challengeFilters config) . (\r -> flip T.isInfixOf (T.toCaseFold (rideName r)))
data Options = Options { clearCache :: Bool }
defaultOpts :: Options
defaultOpts = Options { clearCache = False }
options :: [OptDescr (Options -> Options)]
options =
[ Option ['c'] ["clear"]
(NoArg (\opts -> opts { clearCache = True }))
"Clear score cache"
]
data ScoreFile = ScoreFile [S.UserScore] deriving (Data, Typeable)
fromScoreMap :: M.Map Integer S.UserScore -> ScoreFile
fromScoreMap = ScoreFile . map snd . M.toList
toScoreMap :: ScoreFile -> M.Map Integer S.UserScore
toScoreMap (ScoreFile scores) = M.fromList $ map (\score -> (S.uid score, score)) scores
data ChallengeConfig = ChallengeConfig {
challengeTitle :: T.Text,
challengeDesc :: T.Text,
challengeDir :: String,
challengeFilters :: [T.Text],
challengeGroups :: [Integer],
challengeOthers :: [Integer],
challengeStart :: Day,
challengeEnd :: Day
} deriving Show
instance FromJSON ChallengeConfig where
parseJSON (Object v) = ChallengeConfig <$>
v .: "title" <*>
v .: "desc" <*>
v .: "directory" <*>
v .: "filters" <*>
v .: "groups" <*>
v .: "others" <*>
v .: "start" <*>
v .: "end"
parseJSON _ = fail "Expected object to parse challenge config data"
instance FromJSON Day where
parseJSON (String t) = case parseTime defaultTimeLocale "%F" (T.unpack t) of
Just d -> return d
_ -> fail "could not parse day"
parseJSON _ = fail "Expecting string when parsing a Day"
userRides :: (Failure HttpException m, MonadBaseControl IO m, MonadResource m) => Integer -> Day -> Day -> Integer -> Manager -> m [RideDetails]
userRides uid start end sid manager = do
urides <- rideSearch (rsDefault { userID = Just uid, startDay = Just start, endDay = Just end, startId = Just sid }) manager
liftM sort $ mapM (liftM snd . (flip rideDetails manager) . snd) urides
render :: ChallengeConfig -> ZonedTime -> [S.UserScore] -> [S.GroupScore] -> Html
render config ztime userScores groupScores = docTypeHtml $ do
H.head $ do
title (toHtml $ challengeTitle config)
link ! rel "stylesheet" ! href "style.css" ! type_ "text/css"
body $ do
h1 (toHtml $ challengeTitle config)
preEscapedToHtml $ challengeDesc config
h2 "Group Scores"
S.renderGroups groupScores
h2 "Individual Scores"
S.renderScores userScores
h2 "Total Stats"
ul $ do
li $ do
toHtml $ sum $ map S.rides userScores
" rides"
li $ do
toHtml $ (floor :: Double -> Int) $ sum $ map S.miles userScores
" miles"
li $ do
toHtml $ sum $ map S.userScore userScores
" total points earned"
p $ do
_ <- "Last update at "
toHtml $ formatTime defaultTimeLocale "%T on %D" ztime
p $ a ! href "https://github.com/ronwalf/ba-winter-challenge" $ "Get the BA-Winter Challenge Code!"
|
ronwalf/ba-winter-challenge
|
src/ba-winter-challenge.hs
|
bsd-3-clause
| 7,260 | 0 | 24 | 1,700 | 2,276 | 1,187 | 1,089 | 146 | 4 |
{-# LANGUAGE OverloadedStrings #-}
module HelloWorld where
import Network.Miku
import Network.HTTP.Pony.Serve (run)
import Network.HTTP.Pony.Serve.Wai (fromWAI)
import Network.HTTP.Pony.Transformer.HTTP (http)
import Network.HTTP.Pony.Transformer.CaseInsensitive (caseInsensitive)
import Network.HTTP.Pony.Transformer.StartLine (startLine)
import Pipes.Safe (runSafeT)
main :: IO ()
main =
runSafeT
. (run "localhost" "8080")
. http
. startLine
. caseInsensitive
. fromWAI
. miku $
get "/" (text "miku power")
|
nfjinjing/miku
|
test/HelloWorld.hs
|
bsd-3-clause
| 554 | 0 | 13 | 98 | 146 | 88 | 58 | 19 | 1 |
{-# LANGUAGE FlexibleContexts #-}
module Language.Gator.Ops.Output (
newOutput,
newOutputN,
) where
import Language.Gator.Logic
import Language.Gator.General
import Language.Gator.Gates
import Language.Gator.Gates.Output
import Language.Gator.Ops.General
import Control.Monad.State
nextOutput :: (MonadState Logic m) => m Name
nextOutput = do
idx <- nextIdxOf outputID
return $ "out" ++ (show idx)
newOutput :: (MonadState Logic m) => m Output
newOutput = nextOutput >>= newOutputN
newOutputN :: (MonadState Logic m) => Name -> m Output
newOutputN n = do
i <- nextGateID
let g = Output n i
g' = G_Output g
gateSets $ modify (g':)
return g
|
sw17ch/gator
|
src/Language/Gator/Ops/Output.hs
|
bsd-3-clause
| 687 | 0 | 10 | 138 | 215 | 117 | 98 | 23 | 1 |
module MessagesSpec where
import Test.Hspec
import Test.QuickCheck
import Data.List (intercalate)
import Data.Maybe
import qualified Data.UUID as UUID
import System.Random
import Messages
import Models
instance Arbitrary UUID.UUID where
arbitrary = (fst . random . mkStdGen) <$> arbitrary
spec :: Spec
spec = do
let uuid = fromJust $ UUID.fromString "dd7b8e07-10bf-4ea7-9564-0d1de00b363c"
describe "Encoding a message" $ do
describe "Message" $ do
it "prepends the message type and the server id" $ do
encode (Msg uuid "hi, what's up?") `shouldBe`
"message|dd7b8e07-10bf-4ea7-9564-0d1de00b363c|hi, what's up?"
describe "Handshake" $ do
it "prepends the handshake type and server id, with an empty message" $ do
encode (Handshake uuid) `shouldBe`
"handshake|dd7b8e07-10bf-4ea7-9564-0d1de00b363c|"
describe "Decoding a message" $ do
describe "Message" $ do
it "returns a Msg with the uuid and message" $ do
decode "message|dd7b8e07-10bf-4ea7-9564-0d1de00b363c|hi, what's up?" `shouldBe`
(Just (Msg uuid "hi, what's up?"))
it "returns nothing if the uuid cannot be parsed" $ do
decode "message|imnotauuid|hi, what's up?" `shouldBe` Nothing
describe "Handshake" $ do
it "returns a Handshake with the uuid" $ do
decode "handshake|dd7b8e07-10bf-4ea7-9564-0d1de00b363c|" `shouldBe`
(Just (Handshake uuid))
it "returns nothing if the uuid cannot be parsed" $ do
decode "handshake|imnotauuid|" `shouldBe` Nothing
describe "wrong message" $ do
it "returns nothing if the message prefix is not recognized" $ do
decode "finger|dd7b8e07-10bf-4ea7-9564-0d1de00b363c|hi, what's up?" `shouldBe` Nothing
describe "symmetry" $ do
it "decodes its own encoding of a message" $ property $
\u m -> (decode . encode) (Msg u m) == Just (Msg u m)
it "decodes its own encoding of a handshake" $ property $
\u -> (decode . encode) (Handshake u) == Just (Handshake u)
|
shterrett/peer-chat
|
test/MessagesSpec.hs
|
bsd-3-clause
| 2,105 | 0 | 20 | 525 | 482 | 232 | 250 | 44 | 1 |
module Yesod.Goodies.PNotify.Modules.Desktop
( Desktop(..)
, defaultDesktop
)where
import Data.Aeson
import Data.Text (Text)
import Yesod.Goodies.PNotify.Types
import Yesod.Goodies.PNotify.Types.Instances
data Desktop = Desktop { _desktop :: Maybe Bool
, _fallback :: Maybe Bool
, _icon :: Maybe (Prelude.Either Bool URL)
, _tag :: Maybe Text
}
deriving (Read, Show, Eq, Ord)
instance FromJSON Desktop where
parseJSON (Object v) = Desktop <$>
v .:? "desktop" <*>
v .:? "fallback" <*>
v .:? "icon" <*>
v .:? "tag"
instance ToJSON Desktop where
toJSON (Desktop { _desktop
, _fallback
, _icon
, _tag
})
= object $ maybe [] (\x -> ["desktop" .= x]) _desktop ++
maybe [] (\x -> ["fallback" .= x]) _fallback ++
maybe [] (\x -> ["icon" .= x]) _icon ++
maybe [] (\x -> ["tag" .= x]) _tag ++
[]
defaultDesktop :: Desktop
defaultDesktop = Desktop
{ _desktop = Nothing
, _fallback = Nothing
, _icon = Nothing
, _tag = Nothing
}
|
cutsea110/yesod-pnotify
|
Yesod/Goodies/PNotify/Modules/Desktop.hs
|
bsd-3-clause
| 1,411 | 0 | 15 | 645 | 367 | 207 | 160 | -1 | -1 |
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UnliftedFFITypes #-}
module MCL.Curves.Fp254BNb.G1
( G1
, mkG1
, mapToG1
, g1_zero
, g1_isZero
, g1_affineCoords
, g1_getYfromX
, g1_powFr
) where
import Control.DeepSeq
import Data.Binary
import Data.Bits
import Data.Group
import Foreign.C.Types
import GHC.Exts
import GHC.Integer.GMP.Internals
import MCL.Curves.Fp254BNb.Fp
import MCL.Curves.Fp254BNb.Fr
import MCL.Internal.Utils
import qualified MCL.Internal.Group as I
import qualified MCL.Internal.Prim as I
-- | Subgroup of @E(Fp)@ (i.e. curve points with coordinates in Fp) of order
-- @r@.
data G1 = G1 { unG1 :: I.CC G1 }
instance Binary G1 where
put = putCurvePoint g1_affineCoords putY
where
putY y = put . cintToBool . fromIntegral $ fromFp y .&. 1
get = getCurvePoint g1_zero $ \x y_lsb ->
mkG1 x =<< g1_getYfromX y_lsb x
instance NFData G1 where
rnf = (`seq` ())
instance Eq G1 where
(==) = I.eqG
instance Show G1 where
showsPrec = I.showsPrecG
-- | Point addition.
instance Monoid G1 where
mempty = I.zero
mappend = I.plusG
-- | Note: 'pow' uses const-time method, just as 'g1_powFr'.
instance Group G1 where
invert = I.invertG
pow = flip I.scalarMul
instance Abelian G1
-- | Construct non-zero element of G1 from two coordinates in Fp. If @(X,Y)@
-- does not lie on G1, no result is returned.
{-# INLINE mkG1 #-}
mkG1
:: Fp -- ^ X coordinate
-> Fp -- ^ Y coordinate
-> Maybe G1
mkG1 = I.mkG
-- | Map an element of Fp to a curve point. Note: @mapToG1 . hashToFp@ does NOT
-- yield generically secure hash function. For more details see page 3 of
-- "Indifferentiable Hashing to Barreto-Naehrig Curves"
-- (<https://www.di.ens.fr/~fouque/pub/latincrypt12.pdf>).
{-# INLINE mapToG1 #-}
mapToG1 :: Fp -> G1
mapToG1 = I.mapToG
-- | Neutral element of G1 (point at infinity).
{-# NOINLINE g1_zero #-}
g1_zero :: G1
g1_zero = I.zero
-- | Check if the element of G1 is point at infinity.
{-# INLINE g1_isZero #-}
g1_isZero :: G1 -> Bool
g1_isZero = I.isZero
-- | Return affine coordinates of the element @a ∈ G1@. No result is returned if
-- @a@ is the point at inifinity.
{-# INLINE g1_affineCoords #-}
g1_affineCoords :: G1 -> Maybe (Fp, Fp)
g1_affineCoords = I.affineCoords
-- | Attempt to recover Y coordinate from its least significant bit and X
-- coordinate.
{-# INLINE g1_getYfromX #-}
g1_getYfromX
:: Bool -- ^ Least significant bit of Y coordinate
-> Fp -- ^ X coordinate
-> Maybe Fp
g1_getYfromX = I.getYfromX (proxy# :: Proxy# G1)
-- | Multiply the element of G1 by a scalar @x ∈ Fr@. Note: it uses const-time
-- method, i.e. the time it takes to calculate the result depends only on the
-- bitlength of @x@.
{-# INLINE g1_powFr #-}
g1_powFr :: G1 -> Fr -> G1
g1_powFr = I.powFr
----------------------------------------
-- | Internal
instance I.Prim G1 where
prim_size _ = fromIntegral c_mcl_fp254bnb_g1_size
prim_wrap = G1
prim_unwrap = unG1
-- | Internal
instance I.CurveGroup Fp G1 where
c_zero _ = c_mcl_fp254bnb_g1_zero
c_construct _ = c_mcl_fp254bnb_g1_construct
c_map_to _ = c_mcl_fp254bnb_g1_map_to
c_add _ = c_mcl_fp254bnb_g1_add
c_invert _ = c_mcl_fp254bnb_g1_invert
c_scalar_mul_native _ = c_mcl_fp254bnb_g1_scalar_mul_native
c_scalar_mul_bignat _ = c_mcl_fp254bnb_g1_scalar_mul
c_scalar_mul_hsint _ = c_mcl_fp254bnb_g1_scalar_mul_small
c_eq _ = c_mcl_fp254bnb_g1_eq
c_is_zero _ = c_mcl_fp254bnb_g1_is_zero
c_affine_coords _ = c_mcl_fp254bnb_g1_affine_coords
c_y_from_x _ = c_mcl_fp254bnb_g1_y_from_x
foreign import ccall unsafe "hs_mcl_fp254bnb_g1_size"
c_mcl_fp254bnb_g1_size :: CInt
foreign import ccall unsafe "hs_mcl_fp254bnb_g1_zero"
c_mcl_fp254bnb_g1_zero :: I.MC G1 -> IO ()
foreign import ccall safe "hs_mcl_fp254bnb_g1_construct"
c_mcl_fp254bnb_g1_construct :: I.CC Fp -> I.CC Fp -> I.MC G1 -> IO CInt
foreign import ccall safe "hs_mcl_fp254bnb_g1_map_to"
c_mcl_fp254bnb_g1_map_to :: I.CC Fp -> I.MC G1 -> IO ()
foreign import ccall unsafe "hs_mcl_fp254bnb_g1_add"
c_mcl_fp254bnb_g1_add :: I.CC G1 -> I.CC G1 -> I.MC G1 -> IO ()
foreign import ccall unsafe "hs_mcl_fp254bnb_g1_invert"
c_mcl_fp254bnb_g1_invert :: I.CC G1 -> I.MC G1 -> IO ()
foreign import ccall safe "hs_mcl_fp254bnb_g1_scalar_mul_native"
c_mcl_fp254bnb_g1_scalar_mul_native :: CInt -> I.CC Fr -> I.CC G1 -> I.MC G1 -> IO ()
foreign import ccall safe "hs_mcl_fp254bnb_g1_scalar_mul"
c_mcl_fp254bnb_g1_scalar_mul :: CInt -> I.CC Integer -> GmpSize# -> CInt
-> I.CC G1 -> I.MC G1 -> IO ()
foreign import ccall safe "hs_mcl_fp254bnb_g1_scalar_mul_small"
c_mcl_fp254bnb_g1_scalar_mul_small :: CInt -> Int# -> I.CC G1 -> I.MC G1 -> IO ()
foreign import ccall unsafe "hs_mcl_fp254bnb_g1_eq"
c_mcl_fp254bnb_g1_eq :: I.CC G1 -> I.CC G1 -> IO CInt
foreign import ccall unsafe "hs_mcl_fp254bnb_g1_is_zero"
c_mcl_fp254bnb_g1_is_zero :: I.CC G1 -> IO CInt
foreign import ccall unsafe "hs_mcl_fp254bnb_g1_affine_coords"
c_mcl_fp254bnb_g1_affine_coords :: I.CC G1 -> I.MC Fp -> I.MC Fp -> IO ()
foreign import ccall unsafe "hs_mcl_fp254bnb_g1_y_from_x"
c_mcl_fp254bnb_g1_y_from_x :: CInt -> I.CC Fp -> I.MC Fp -> IO CInt
|
arybczak/haskell-mcl
|
src/MCL/Curves/Fp254BNb/G1.hs
|
bsd-3-clause
| 5,335 | 0 | 13 | 1,032 | 1,142 | 615 | 527 | 114 | 1 |
module Kagamin.Modules where
import Data.Text (Text)
import Web.Slack (Slack, ChannelId, Submitter)
-- | Result of executing a given hook: either the hook did nothing, modified
-- the message text for the next hook in the pipeline, or requested
-- processing to cease.
data HookResult = Next | Modify Text | Stop
-- | Hook for handling received messages.
type MsgHook = ChannelId -> Submitter -> Text -> Slack () HookResult
data KagaModule = KagaModule {
-- | Hook for messages directed at Kagamin.
kagaMsgHook :: MsgHook,
-- | Hook for messages *not* directed at Kagamin.
kagaOtherHook :: MsgHook,
-- | Hook for *all* messages. Processed after all other messages.
kagaAllHook :: MsgHook,
-- | Hook for saving the state of a module.
kagaSaveHook :: FilePath -> IO (),
-- | Hook for loading the state of a module.
kagaLoadHook :: FilePath -> IO ()
}
-- | Hook that does nothing.
nopHook :: MsgHook
nopHook _ _ _ = return Next
-- | Default KagaModule: does nothing, ever.
defaultModule :: KagaModule
defaultModule = KagaModule {
kagaMsgHook = nopHook,
kagaOtherHook = nopHook,
kagaAllHook = nopHook,
kagaSaveHook = const $ return (),
kagaLoadHook = const $ return ()
}
|
valderman/kagamin
|
Kagamin/Modules.hs
|
mit
| 1,256 | 0 | 11 | 286 | 220 | 131 | 89 | 20 | 1 |
module Data.Wright.RGB.Model.PALSECAMRGB (pALSECAMRGB) where
import Data.Wright.Types (Model(..), Primary(..), Gamma(..))
import Data.Wright.CIE.Illuminant.D65 (d65)
pALSECAMRGB :: Model
pALSECAMRGB = d65
{ gamma = Gamma 2.2
, red = Primary 0.6400 0.3300 0.222021
, green = Primary 0.2900 0.6000 0.706645
, blue = Primary 0.1500 0.0600 0.071334
}
|
fmap-archive/wright
|
src/Data/Wright/RGB/Model/PALSECAMRGB.hs
|
mit
| 361 | 0 | 7 | 59 | 116 | 72 | 44 | 9 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module PureScript.Ide.Pursuit where
import qualified Control.Exception as E
import Control.Lens hiding (noneOf)
import Control.Monad
import Data.Aeson
import Data.Aeson.Lens
import Data.ByteString.Lazy (ByteString)
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as T
import Network.HTTP.Client (HttpException (StatusCodeException))
import Network.Wreq
import PureScript.Ide.Types
import Text.Parsec
import Text.Parsec.Text
instance FromJSON PursuitResponse where
parseJSON (Object o) = do
package <- o .: "package"
info <- o .: "info"
(type' :: String) <- info .: "type"
case type' of
"module" -> do
name <- info .: "module"
return
ModuleResponse
{ moduleResponseName = name
, moduleResponsePackage = package
}
"declaration" -> do
moduleName <- info .: "module"
Right (ident, declType) <- typeParse <$> o .: "text"
return
DeclarationResponse
{ declarationResponseType = declType
, declarationResponseModule = moduleName
, declarationResponseIdent = ident
, declarationResponsePackage = package
}
_ -> mzero
parseJSON _ = mzero
queryUrl :: String
queryUrl = "http://pursuit.purescript.org/search"
jsonOpts :: Text -> Options
jsonOpts q =
defaults & header "Accept" .~ ["application/json"] & param "q" .~ [q]
-- We need to remove trailing dots because Pursuit will return a 400 otherwise
-- TODO: remove this when the issue is fixed at Pursuit
queryPursuit :: Text -> IO (Response ByteString)
queryPursuit q = getWith (jsonOpts (T.dropWhileEnd (== '.') q)) queryUrl
handler :: HttpException -> IO [a]
handler (StatusCodeException{}) = return []
handler _ = return []
searchPursuitForDeclarations :: Text -> IO [PursuitResponse]
searchPursuitForDeclarations query =
(do r <- queryPursuit query
let results = map fromJSON (r ^.. responseBody . values)
return (mapMaybe isDeclarationResponse results)) `E.catch`
handler
where
isDeclarationResponse (Success a@(DeclarationResponse{})) = Just a
isDeclarationResponse _ = Nothing
findPackagesForModuleIdent :: Text -> IO [PursuitResponse]
findPackagesForModuleIdent query =
(do r <- queryPursuit query
let results = map fromJSON (r ^.. responseBody . values)
return (mapMaybe isModuleResponse results)) `E.catch`
handler
where
isModuleResponse (Success a@(ModuleResponse{})) = Just a
isModuleResponse _ = Nothing
parseType :: Parser (String, String)
parseType = do
name <- identifier
_ <- string "::"
spaces
type' <- many1 anyChar
return (T.unpack name, type')
typeParse :: Text -> Either Text (Text, Text)
typeParse t = case parse parseType "" t of
Right (x,y) -> Right (T.pack x, T.pack y)
Left err -> Left (T.pack (show err))
identifier :: Parser Text
identifier = do
spaces
ident <-
-- necessary for being able to parse the following ((++), concat)
between (char '(') (char ')') (many1 (noneOf ", )")) <|>
many1 (noneOf ", )")
spaces
return (T.pack ident)
|
kRITZCREEK/psc-ide
|
src/PureScript/Ide/Pursuit.hs
|
mit
| 3,534 | 0 | 15 | 1,040 | 954 | 495 | 459 | -1 | -1 |
-- Model fitting to derive coefficients in
-- Math.NumberTheory.Primes.Sequence.chooseAlgorithm
module Main where
import Numeric.GSL.Fitting
-- | Benchmarks Sequence/filterIsPrime
-- ([start, length], ([time in microseconds], weight))
filterIsPrimeBenchData :: [([Double], ([Double], Double))]
filterIsPrimeBenchData =
[ ([100000, 1000], ([777], 0.1))
, ([100000, 10000], ([8523], 0.1))
, ([1000000, 1000], ([813], 0.1))
, ([1000000, 10000], ([8247], 0.1))
, ([1000000, 100000], ([78600], 0.1))
, ([10000000, 1000], ([765], 0.1))
, ([10000000, 10000], ([7685], 0.1))
, ([10000000, 100000], ([78900], 0.1))
, ([10000000, 1000000], ([785000], 0.1))
, ([100000000, 1000], ([792], 0.1))
, ([100000000, 10000], ([8094], 0.1))
, ([100000000, 100000], ([79280], 0.1))
, ([100000000, 1000000], ([771600], 0.1))
, ([100000000, 10000000], ([7670000], 0.1))
]
filterIsPrimeBenchModel :: [(Double, Double)]
filterIsPrimeBenchModel = sol
where
model [d] [from, len] = [len * d]
modelDer [d] [from, len] = [[len]]
(sol, _) = fitModelScaled 1E-10 1E-10 20 (model, modelDer) filterIsPrimeBenchData [1]
filterIsPrimeBenchApprox :: ([Double], ([Double], Double)) -> [Double]
filterIsPrimeBenchApprox ([from, len], ([exact], _)) = [from, len, exact, fromInteger (floor (appr / exact * 1000)) / 1000]
where
[(d, _)] = filterIsPrimeBenchModel
appr = len * d
-- | Benchmarks Sequence/eratosthenes
-- ([start, length], ([time in microseconds], weight))
eratosthenesData :: [([Double], ([Double], Double))]
eratosthenesData =
[ ([10000000000,1000000], ([21490], 0.1))
, ([10000000000,10000000], ([103200], 0.1))
, ([10000000000,100000000], ([956800], 0.1))
, ([10000000000,1000000000], ([9473000], 0.1))
, ([100000000000,10000000], ([107000], 0.1))
, ([1000000000000,10000000], ([129900], 0.1))
, ([10000000000000,10000000], ([202900], 0.1))
, ([100000000000000,10000000], ([420400], 0.1))
, ([1000000000000000,10000000], ([1048000], 0.1))
, ([10000000000000000,10000000], ([2940000], 0.1))
, ([100000000000000000,10000000], ([8763000], 0.1))
]
eratosthenesModel :: [(Double, Double)]
eratosthenesModel = sol
where
model [a, b, c] [from, len] = [a * len + b * sqrt from + c]
modelDer [a, b, c] [from, len] = [[len, sqrt from, 1]]
(sol, _) = fitModelScaled 1E-10 1E-10 20 (model, modelDer) eratosthenesData [1,0,0]
eratosthenesApprox :: ([Double], ([Double], Double)) -> [Double]
eratosthenesApprox ([from, len], ([exact], _)) = [from, len, exact, fromInteger (floor (appr / exact * 1000)) / 1000]
where
[(a, _), (b, _), (c, _)] = eratosthenesModel
appr = a * len + b * sqrt from + c
coeffs :: (Double, Double)
coeffs = (b / (d - a), c / (d - a))
where
[(a, _), (b, _), (c, _)] = eratosthenesModel
[(d, _)] = filterIsPrimeBenchModel
main :: IO ()
main = do
print filterIsPrimeBenchModel
mapM_ (print . filterIsPrimeBenchApprox) filterIsPrimeBenchData
print eratosthenesModel
mapM_ (print . eratosthenesApprox) eratosthenesData
print coeffs
|
Bodigrim/arithmoi
|
app/SequenceModel.hs
|
mit
| 3,047 | 0 | 12 | 511 | 1,364 | 849 | 515 | 60 | 1 |
-- Copyright 2017 Google Inc.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
module Language.Haskell.Indexer.Util.Path
( asTextPath
, stripTmpPrefix
) where
import Data.List (isPrefixOf)
import qualified Data.Text as T
import System.FilePath (splitPath, joinPath)
-- | Removes the workdir prefix from likely temporary paths.
-- Useful for 'aoFilePathTransform' in 'AnalysisOptions'.
stripTmpPrefix :: FilePath -> FilePath
stripTmpPrefix path = case partsAfterTmp path of
Just (rand:ps) | isValidRandomDir rand -> joinPath ps
_ -> path
where
-- | Finds the longest suffix of the path that begins with "tmp/".
partsAfterTmp :: FilePath -> Maybe [String]
partsAfterTmp = go . splitPath
where go [] = Nothing
go ("tmp/":rest) = Just rest
go (_:rest) = go rest
-- | True if the directory matches some known random-generation pattern.
isValidRandomDir :: String -> Bool
isValidRandomDir dir = all (`elem` '/':['0'..'9']) dir
|| "tempfile" `isPrefixOf` dir
-- | Wraps a FilePath operation as a Text operation.
asTextPath :: (FilePath -> FilePath) -> T.Text -> T.Text
asTextPath f = T.pack . f . T.unpack
|
google/haskell-indexer
|
haskell-indexer-pathutil/src/Language/Haskell/Indexer/Util/Path.hs
|
apache-2.0
| 1,696 | 0 | 12 | 340 | 289 | 165 | 124 | 20 | 4 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-missing-fields #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-----------------------------------------------------------------
-- Autogenerated by Thrift
-- --
-- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
-- @generated
-----------------------------------------------------------------
module TestService_Fuzzer (main) where
import qualified Module_Types
import qualified TestService_Client as Client
import Prelude ( Bool(..), Enum, Float, IO, Double, String, Maybe(..),
Eq, Show, Ord,
concat, error, fromIntegral, fromEnum, length, map,
maybe, not, null, otherwise, return, show, toEnum,
enumFromTo, Bounded, minBound, maxBound, seq,
(.), (&&), (||), (==), (++), ($), (-), (>>=), (>>))
import qualified Control.Applicative as Applicative (ZipList(..))
import Control.Applicative ( (<*>) )
import qualified Control.DeepSeq as DeepSeq
import qualified Control.Exception as Exception
import qualified Control.Monad as Monad ( liftM, ap, when )
import qualified Data.ByteString.Lazy as BS
import Data.Functor ( (<$>) )
import qualified Data.Hashable as Hashable
import qualified Data.Int as Int
import qualified Data.Maybe as Maybe (catMaybes)
import qualified Data.Text.Lazy.Encoding as Encoding ( decodeUtf8, encodeUtf8 )
import qualified Data.Text.Lazy as LT
import qualified Data.Typeable as Typeable ( Typeable )
import qualified Data.HashMap.Strict as Map
import qualified Data.HashSet as Set
import qualified Data.Vector as Vector
import qualified Test.QuickCheck.Arbitrary as Arbitrary ( Arbitrary(..) )
import qualified Test.QuickCheck as QuickCheck ( elements )
import qualified Thrift
import qualified Thrift.Types as Types
import qualified Thrift.Serializable as Serializable
import qualified Thrift.Arbitraries as Arbitraries
import Prelude ((>>), print)
import qualified Prelude as P
import Control.Monad (forM)
import qualified Data.List as L
import Data.Maybe (fromJust)
import qualified Data.Map as Map
import GHC.Int (Int64, Int32)
import Data.ByteString.Lazy (ByteString)
import System.Environment (getArgs)
import Test.QuickCheck (arbitrary)
import Test.QuickCheck.Gen (Gen(..))
import Thrift.FuzzerSupport
handleOptions :: ([Options -> Options], [String], [String]) -> Options
handleOptions (transformers, (serviceName:[]), []) | serviceName `P.elem` serviceNames
= (P.foldl (P.flip ($)) defaultOptions transformers) { opt_service = serviceName }
handleOptions (_, (serviceName:[]), []) | P.otherwise
= P.error $ usage ++ "\nUnknown serviceName " ++ serviceName ++ ", should be one of " ++ (P.show serviceNames)
handleOptions (_, [], _) = P.error $ usage ++ "\nMissing mandatory serviceName to fuzz."
handleOptions (_, _a, []) = P.error $ usage ++ "\nToo many serviceNames, pick one."
handleOptions (_, _, e) = P.error $ usage ++ (P.show e)
main :: IO ()
main = do
args <- getArgs
let config = handleOptions (getOptions args)
fuzz config
selectFuzzer :: Options -> (Options -> IO ())
selectFuzzer (Options _host _port service _timeout _framed _verbose)
= fromJust $ P.lookup service fuzzerFunctions
fuzz :: Options -> IO ()
fuzz config = (selectFuzzer config) config
-- Dynamic content
-- Configuration via command-line parsing
serviceNames :: [String]
serviceNames = ["init"]
fuzzerFunctions :: [(String, (Options -> IO ()))]
fuzzerFunctions = [("init", init_fuzzer)]
-- Random data generation
inf_Int_Int64 :: IO [Int.Int64]
inf_Int_Int64 = infexamples (Arbitrary.arbitrary :: Gen Int.Int64)
-- Fuzzers and exception handlers
init_fuzzer :: Options -> IO ()
init_fuzzer opts = do
a1 <- Applicative.ZipList <$> inf_Int_Int64
a2 <- Applicative.ZipList <$> inf_Int_Int64
a3 <- Applicative.ZipList <$> inf_Int_Int64
a4 <- Applicative.ZipList <$> inf_Int_Int64
a5 <- Applicative.ZipList <$> inf_Int_Int64
a6 <- Applicative.ZipList <$> inf_Int_Int64
a7 <- Applicative.ZipList <$> inf_Int_Int64
a8 <- Applicative.ZipList <$> inf_Int_Int64
a9 <- Applicative.ZipList <$> inf_Int_Int64
a10 <- Applicative.ZipList <$> inf_Int_Int64
a11 <- Applicative.ZipList <$> inf_Int_Int64
a12 <- Applicative.ZipList <$> inf_Int_Int64
a13 <- Applicative.ZipList <$> inf_Int_Int64
a14 <- Applicative.ZipList <$> inf_Int_Int64
a15 <- Applicative.ZipList <$> inf_Int_Int64
a16 <- Applicative.ZipList <$> inf_Int_Int64
_ <- P.sequence . Applicative.getZipList $ init_fuzzFunc <$> a1 <*> a2 <*> a3 <*> a4 <*> a5 <*> a6 <*> a7 <*> a8 <*> a9 <*> a10 <*> a11 <*> a12 <*> a13 <*> a14 <*> a15 <*> a16
return ()
where
init_fuzzFunc a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 a16 = let param = (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16) in
if opt_framed opts
then withThriftDo opts (withFramedTransport opts) (init_fuzzOnce param) (init_exceptionHandler param)
else withThriftDo opts (withHandle opts) (init_fuzzOnce param) (init_exceptionHandler param)
init_exceptionHandler :: (Show a1, Show a2, Show a3, Show a4, Show a5, Show a6, Show a7, Show a8, Show a9, Show a10, Show a11, Show a12, Show a13, Show a14, Show a15, Show a16) => (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16) -> IO ()
init_exceptionHandler (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16) = do
P.putStrLn $ "Got exception on data:"
P.putStrLn $ "(" ++ show a1 ++ show a2 ++ show a3 ++ show a4 ++ show a5 ++ show a6 ++ show a7 ++ show a8 ++ show a9 ++ show a10 ++ show a11 ++ show a12 ++ show a13 ++ show a14 ++ show a15 ++ show a16 ++ ")"
init_fuzzOnce (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16) client = Client.init client a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 a16 >> return ()
|
sinjar666/fbthrift
|
thrift/compiler/test/fixtures/service-fuzzer/gen-hs/TestService_Fuzzer.hs
|
apache-2.0
| 6,071 | 0 | 26 | 1,076 | 1,960 | 1,124 | 836 | 103 | 2 |
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances #-}
{-# LANGUAGE PatternGuards #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Layout.Stoppable
-- Copyright : (c) Anton Vorontsov <[email protected]> 2014
-- License : BSD-style (as xmonad)
--
-- Maintainer : Anton Vorontsov <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-- This module implements a special kind of layout modifier, which when
-- applied to a layout, causes xmonad to stop all non-visible processes.
-- In a way, this is a sledge-hammer for applications that drain power.
-- For example, given a web browser on a stoppable workspace, once the
-- workspace is hidden the web browser will be stopped.
--
-- Note that the stopped application won't be able to communicate with X11
-- clipboard. For this, the module actually stops applications after a
-- certain delay, giving a chance for a user to complete copy-paste
-- sequence. By default, the delay equals to 15 seconds, it is
-- configurable via 'Stoppable' constructor.
--
-- The stoppable modifier prepends a mark (by default equals to
-- \"Stoppable\") to the layout description (alternatively, you can choose
-- your own mark and use it with 'Stoppable' constructor). The stoppable
-- layout (identified by a mark) spans to multiple workspaces, letting you
-- to create groups of stoppable workspaces that only stop processes when
-- none of the workspaces are visible, and conversely, unfreezing all
-- processes even if one of the stoppable workspaces are visible.
--
-- To stop the process we use signals, which works for most cases. For
-- processes that tinker with signal handling (debuggers), another
-- (Linux-centric) approach may be used. See
-- <https://www.kernel.org/doc/Documentation/cgroups/freezer-subsystem.txt>
--
-- * Note
-- This module doesn't work on programs that do fancy things with processes
-- (such as Chromium) and programs that do not set _NET_WM_PID.
-----------------------------------------------------------------------------
module XMonad.Layout.Stoppable
( -- $usage
Stoppable(..)
, stoppable
) where
import XMonad
import XMonad.Actions.WithAll
import XMonad.Util.WindowProperties
import XMonad.Util.RemoteWindows
import XMonad.Util.Timer
import XMonad.StackSet hiding (filter)
import XMonad.Layout.LayoutModifier
import System.Posix.Signals
import Data.Maybe
import Control.Monad
-- $usage
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad
-- > import XMonad.Layout.Stoppable
-- >
-- > main = xmonad def
-- > { layoutHook = layoutHook def ||| stoppable (layoutHook def) }
--
-- Note that the module has to distinguish between local and remote
-- proccesses, which means that it needs to know the hostname, so it looks
-- for environment variables (e.g. HOST).
--
-- Environment variables will work for most cases, but won't work if the
-- hostname changes. To cover dynamic hostnames case, in addition to
-- layoutHook you have to provide manageHook from
-- "XMonad.Util.RemoteWindows" module.
--
-- For more detailed instructions on editing the layoutHook see:
--
-- "XMonad.Doc.Extending#Editing_the_layout_hook"
signalWindow :: Signal -> Window -> X ()
signalWindow s w = do
pid <- getProp32s "_NET_WM_PID" w
io $ (signalProcess s . fromIntegral) `mapM_` fromMaybe [] pid
signalLocalWindow :: Signal -> Window -> X ()
signalLocalWindow s w = isLocalWindow w >>= flip when (signalWindow s w)
withAllOn :: (a -> X ()) -> Workspace i l a -> X ()
withAllOn f wspc = f `mapM_` integrate' (stack wspc)
withAllFiltered :: (Workspace i l a -> Bool)
-> [Workspace i l a]
-> (a -> X ()) -> X ()
withAllFiltered p wspcs f = withAllOn f `mapM_` filter p wspcs
sigStoppableWorkspacesHook :: String -> X ()
sigStoppableWorkspacesHook k = do
ws <- gets windowset
withAllFiltered isStoppable (hidden ws) (signalLocalWindow sigSTOP)
where
isStoppable ws = k `elem` words (description $ layout ws)
-- | Data type for ModifiedLayout. The constructor lets you to specify a
-- custom mark/description modifier and a delay. You can also use
-- 'stoppable' helper function.
data Stoppable a = Stoppable
{ mark :: String
, delay :: Rational
, timer :: Maybe TimerId
} deriving (Show,Read)
instance LayoutModifier Stoppable Window where
modifierDescription = mark
hook _ = withAll $ signalLocalWindow sigCONT
handleMess (Stoppable m _ (Just tid)) msg
| Just ev <- fromMessage msg = handleTimer tid ev run
where run = sigStoppableWorkspacesHook m >> return Nothing
handleMess (Stoppable m d _) msg
| Just Hide <- fromMessage msg =
(Just . Stoppable m d . Just) `liftM` startTimer d
| otherwise = return Nothing
-- | Convert a layout to a stoppable layout using the default mark
-- (\"Stoppable\") and a delay of 15 seconds.
stoppable :: l a -> ModifiedLayout Stoppable l a
stoppable = ModifiedLayout (Stoppable "Stoppable" 15 Nothing)
|
f1u77y/xmonad-contrib
|
XMonad/Layout/Stoppable.hs
|
bsd-3-clause
| 5,105 | 0 | 11 | 938 | 742 | 412 | 330 | 50 | 1 |
yes = fromInteger 12
|
mpickering/hlint-refactor
|
tests/examples/Default61.hs
|
bsd-3-clause
| 20 | 0 | 5 | 3 | 9 | 4 | 5 | 1 | 1 |
module InOut where
import PointlessP.Functors
import PointlessP.Combinators
import PointlessP.Isomorphisms
import PointlessP.RecursionPatterns
{- imports will be added for the PointlessP librasies -}
-- the whole expression will be selected for translation.
tail' = app .
(((curry
(app .
((curry
((((inN (_L :: [a])) . (Left . bang)) \/ snd) .
distr)) /\
((ouT (_L :: [a])) . snd)))) .
bang) /\
id)
-- otherwise return the tail
|
kmate/HaRe
|
old/testing/pointwiseToPointfree/InOut_TokOut.hs
|
bsd-3-clause
| 658 | 0 | 27 | 296 | 141 | 83 | 58 | 14 | 1 |
module Test2 where
-- folding against simple function where the variable is on rhs of infix operator
f x = 1 + x
g = 1 + 2
|
kmate/HaRe
|
old/testing/refacFunDef/Test2.hs
|
bsd-3-clause
| 128 | 0 | 5 | 33 | 26 | 15 | 11 | 3 | 1 |
module Main (main ) where
import Debug.Trace
foo :: (a,b) -> a
foo (x,y) = x
{-# NOINLINE foo #-}
wwMe :: Int -> (Int,Int) -> (Int, Int)
wwMe 0 p =
let a = fst p
b = snd p
-- This ensure sharing of b, as seen by the demand analyzer
in foo p `seq`
-- This ensures that wwMe is strict in the tuple, but that the tuple
-- is preserved.
(b + a, a + b)
wwMe n p = wwMe (n-1) (0,0)
-- ^ Make it recursive, so that it is attractive to worker-wrapper
go :: Int -> IO ()
go seed = do
let shareMeThunk = trace "Evaluated (should only happen once)" (seed + 1)
{-# NOINLINE shareMeThunk #-}
-- ^ This is the thunk that is wrongly evaluated twice.
let (x,y) = wwMe 0 (seed,shareMeThunk)
(x + y) `seq` return ()
-- ^ Use both components
{-# NOINLINE go #-}
main :: IO ()
main = go 42
|
tjakway/ghcjvm
|
testsuite/tests/simplCore/should_run/T11731.hs
|
bsd-3-clause
| 860 | 0 | 12 | 255 | 269 | 148 | 121 | 21 | 1 |
module CompactTests where
import Test.QuickCheck
import Thrift.Protocol.Compact
import Util
main :: IO ()
main = aggregateResults
[ quickCheckResult $ propRoundTrip CompactProtocol
, quickCheckResult $ propRoundTripMessage CompactProtocol
]
|
chjp2046/fbthrift
|
thrift/lib/hs/tests/CompactTests.hs
|
apache-2.0
| 265 | 0 | 8 | 51 | 56 | 31 | 25 | 8 | 1 |
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow, 2011
--
-- Generate code to initialise cost centres
--
-- -----------------------------------------------------------------------------
module ProfInit (profilingInitCode) where
import CLabel
import CostCentre
import DynFlags
import Outputable
import FastString
import Module
-- -----------------------------------------------------------------------------
-- Initialising cost centres
-- We must produce declarations for the cost-centres defined in this
-- module;
profilingInitCode :: Module -> CollectedCCs -> SDoc
profilingInitCode this_mod (local_CCs, ___extern_CCs, singleton_CCSs)
= sdocWithDynFlags $ \dflags ->
if not (gopt Opt_SccProfilingOn dflags)
then empty
else vcat
[ text "static void prof_init_" <> ppr this_mod
<> text "(void) __attribute__((constructor));"
, text "static void prof_init_" <> ppr this_mod <> text "(void)"
, braces (vcat (
map emitRegisterCC local_CCs ++
map emitRegisterCCS singleton_CCSs
))
]
where
emitRegisterCC cc =
ptext (sLit "extern CostCentre ") <> cc_lbl <> ptext (sLit "[];") $$
ptext (sLit "REGISTER_CC(") <> cc_lbl <> char ')' <> semi
where cc_lbl = ppr (mkCCLabel cc)
emitRegisterCCS ccs =
ptext (sLit "extern CostCentreStack ") <> ccs_lbl <> ptext (sLit "[];") $$
ptext (sLit "REGISTER_CCS(") <> ccs_lbl <> char ')' <> semi
where ccs_lbl = ppr (mkCCSLabel ccs)
|
urbanslug/ghc
|
compiler/profiling/ProfInit.hs
|
bsd-3-clause
| 1,556 | 0 | 15 | 308 | 328 | 170 | 158 | 27 | 2 |
{-# LANGUAGE CPP #-}
module T9032 where
#ifdef ERR
import T9032
#endif
f x = x
|
urbanslug/ghc
|
testsuite/tests/rename/should_fail/T9032.hs
|
bsd-3-clause
| 85 | 0 | 5 | 22 | 18 | 12 | 6 | 3 | 1 |
{-# LANGUAGE FlexibleInstances #-}
module ShouldFail where
class Foo a where
op :: a -> a
instance {-# OVERLAPPABLE #-} Foo a => Foo [a]
instance {-# OVERLAPPING #-} Foo [Int]
foo :: Foo a => [a] -> [a]
foo x = op x
-- Correct instance depends on instantiation of 'a'
|
urbanslug/ghc
|
testsuite/tests/typecheck/should_fail/tcfail121.hs
|
bsd-3-clause
| 277 | 0 | 7 | 61 | 86 | 46 | 40 | 8 | 1 |
{-# OPTIONS_GHC -Wall #-}
module Foo where
-- We should complain that the first r shadows the second one, and give
-- the right locations for the two of them. (trac #2137)
z :: a
z = r
where
_a = 'a'
_f r = r
_b = 'b'
r = undefined
_c = 'c'
|
urbanslug/ghc
|
testsuite/tests/rename/should_compile/rn064.hs
|
bsd-3-clause
| 290 | 0 | 7 | 104 | 47 | 29 | 18 | 9 | 1 |
-- Squares sequence
-- http://www.codewars.com/kata/5546180ca783b6d2d5000062/
module Codewars.Exercise.Squares where
squares :: Integer -> Int -> [Integer]
squares x n = take n . iterate (^2) $ x
|
gafiatulin/codewars
|
src/Beta/Squares.hs
|
mit
| 198 | 0 | 8 | 28 | 53 | 30 | 23 | 3 | 1 |
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE OverloadedStrings #-}
module Web.Growler.Handler where
import Blaze.ByteString.Builder (Builder)
import Control.Applicative
import Control.Lens
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Trans.Either
import qualified Control.Monad.Trans.RWS.Strict as RWS
import qualified Control.Monad.Trans.State.Strict as ST
import Data.Aeson hiding ((.=))
import qualified Data.ByteString.Char8 as C
import qualified Data.ByteString.Lazy.Char8 as L
import Data.CaseInsensitive
import Data.Maybe
import Data.Monoid ((<>))
import qualified Data.HashMap.Strict as HM
import Data.Text as T
import Data.Text.Encoding as T
import Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import Network.HTTP.Types.Status
import Network.Wai
import Network.Wai.Parse hiding (Param)
import Network.HTTP.Types
import Web.Growler.Parsable
import Web.Growler.Types hiding (status, request, params)
import qualified Web.Growler.Types as L
import Pipes.Wai
import Pipes.Aeson
initialState :: ResponseState
initialState = ResponseState ok200 HM.empty (LBSSource "")
currentResponse :: Monad m => HandlerT m ResponseState
currentResponse = HandlerT RWS.get
-- | End the handler early with an arbitrary 'ResponseState'.
abort :: Monad m => ResponseState -> HandlerT m ()
abort rs = HandlerT $ lift $ left rs
-- | Set the response status code.
status :: Monad m => Status -> HandlerT m ()
status v = HandlerT $ L.status .= v
-- | Add a header to the response. Header names are case-insensitive.
addHeader :: Monad m => CI C.ByteString -> C.ByteString -> HandlerT m ()
addHeader k v = HandlerT (L.headers %= HM.insertWith (\_ v' -> v:v') k [v])
-- | Set a response header. Overrides duplicate headers of the same name.
setHeader :: Monad m => CI C.ByteString -> C.ByteString -> HandlerT m ()
setHeader k v = HandlerT (L.headers %= HM.insert k [v])
-- | Set an arbitrary body source for the response.
body :: Monad m => BodySource -> HandlerT m ()
body = HandlerT . (bodySource .=)
-- | Send a file as the response body.
file :: Monad m => FilePath -- ^ The file to send
-> Maybe FilePart -- ^ If 'Nothing', then send the whole file, otherwise, the part specified
-> HandlerT m ()
file fpath fpart = HandlerT (bodySource .= FileSource fpath fpart)
-- | Set the response body to a ByteString 'Builder'. Sets no headers.
builder :: Monad m => Builder
-> HandlerT m ()
builder b = HandlerT (bodySource .= BuilderSource b)
-- | Set the response body to a lazy 'ByteString'. Sets no headers.
bytestring :: Monad m => L.ByteString -> HandlerT m ()
bytestring bs = HandlerT (bodySource .= LBSSource bs)
-- | Send a streaming response body. Sets no headers.
stream :: Monad m => StreamingBody -> HandlerT m ()
stream s = HandlerT (bodySource .= StreamSource s)
-- | Send raw output as the response body. Useful for e.g. websockets. See WAI's @responseRaw@ for more details.
raw :: MonadIO m => (IO C.ByteString -> (C.ByteString -> IO ()) -> IO ())
-> Response -- ^ Backup response when the WAI provider doesn't support upgrading (e.g. CGI)
-> HandlerT m ()
raw f r = HandlerT (bodySource .= RawSource f r)
-- | Send a value as JSON as the response body. Also sets the content type to application/json.
json :: Monad m => ToJSON a => a -> HandlerT m ()
json x = do
body $ LBSSource $ encode x
addHeader "Content-Type" "application/json"
-- | Parse out the form parameters and the uploaded files. Consumes the request body.
formData :: MonadIO m => BackEnd y -> HandlerT m ([(C.ByteString, C.ByteString)], [File y])
formData b = do
r <- request
liftIO $ parseRequestBody b r
-- | Get all the request headers.
headers :: Monad m => HandlerT m RequestHeaders
headers = liftM requestHeaders request
-- | Consume the request body as a JSON value. Returns a 'JsonInputError' on failure.
jsonData :: (FromJSON a, MonadIO m) => HandlerT m (Either JsonInputError a)
jsonData = do
r <- request
ejs <- ST.evalStateT Pipes.Aeson.decode $ producerRequestBody r
return $! case ejs of
Nothing -> Left RequestBodyExhausted
Just res -> case res of
Left err -> Left $ JsonError err
Right r -> Right r
-- | Get all matched params.
params :: Monad m => HandlerT m [Param]
params = HandlerT (view L.params)
-- | Terminate the current handler and send a @302 Found@ redirect to the provided URL.
-- Other headers that have already been set will also be returned in the request.
redirect :: Monad m => T.Text -- ^ URL to redirect to.
-> HandlerT m ()
redirect url = do
status found302
setHeader "Location" $ T.encodeUtf8 url
currentResponse >>= abort
-- | Get the underlying WAI 'Request'
request :: Monad m => HandlerT m Request
request = HandlerT $ view $ L.request
-- | Return plain text as the response body. Sets the Content-Type header to \"text/plain; charset=utf-8\".
text :: Monad m => TL.Text -> HandlerT m ()
text t = do
setHeader hContentType "text/plain; charset=utf-8"
bytestring $ TL.encodeUtf8 t
-- | Return HTML as the response body. Sets the Content-Type header to \"text/html; charset=utf-8\".
-- If you're using something like blaze-html or lucid, you'll probably get better performance by rolling
-- your own function that sets the response body to a 'Builder'.
html :: Monad m => TL.Text -> HandlerT m ()
html t = do
setHeader hContentType "text/html; charset=utf-8"
bytestring $ TL.encodeUtf8 t
-- | Get the pattern that was matched in the router, e.g. @"/foo/:bar"@
routePattern :: Monad m => HandlerT m (Maybe T.Text)
routePattern = HandlerT $ view $ L.matchedPattern
lookupParam :: (Functor m, Monad m, Parsable a) => C.ByteString -> HandlerT m (Maybe a)
lookupParam k = do
mk <- lookup k <$> params
case mk of
Nothing -> return Nothing
Just v -> do
let ev = parseParam v
case ev of
Left err -> do
status badRequest400
text $ TL.fromStrict $ decodeUtf8 err
currentResponse >>= abort
return Nothing
Right r -> return $ Just r
param :: (Functor m, Monad m, Parsable a) => C.ByteString -> HandlerT m a
param k = do
p <- lookupParam k
case p of
Nothing -> do
status badRequest400
text $ "Missing required parameter " <> TL.fromStrict (decodeUtf8 k)
currentResponse >>= abort
param k
Just r -> return r
raise :: Monad m => C.ByteString -> HandlerT m ()
raise msg = do
status badRequest400
text $ TL.fromStrict $ decodeUtf8 msg
currentResponse >>= abort
runHandler :: Monad m => ResponseState -> Maybe T.Text -> Request -> [Param] -> HandlerT m a -> m (Either ResponseState (a, ResponseState))
runHandler rs pat rq ps m = runEitherT $ do
(dx, r, ()) <- RWS.runRWST (fromHandler m) (RequestState pat (qsParams ++ ps) rq) rs
return (dx, r)
where
qsParams = fmap (_2 %~ fromMaybe "") (queryString rq)
liftAround :: (Monad m) => (forall a. m a -> m a) -> HandlerT m a -> HandlerT m a
liftAround f m = HandlerT $ do
(RequestState pat ps req) <- RWS.ask
currentState <- RWS.get
r <- lift $ lift $ f $ runHandler currentState pat req ps m
case r of
Left err -> lift $ left err
Right (dx, state') -> do
RWS.put state'
return dx
|
iand675/growler
|
src/Web/Growler/Handler.hs
|
mit
| 7,709 | 0 | 19 | 1,920 | 2,125 | 1,081 | 1,044 | 143 | 3 |
module Tree where
data Tree a = Empty | Node (Tree a) a (Tree a)
insert :: (Ord a) => a -> Tree a -> Tree a
insert e Empty = Node Empty e Empty
insert e (Node t0 n t1) | e < n = Node (insert e t0) n t1
| e >= n = Node t0 n (insert e t1)
buildTree :: (Ord a) => [a] -> Tree a
buildTree = foldr insert Empty
foldTree :: (a -> b -> b) -> b -> Tree a -> b
foldTree _ seed Empty = seed
foldTree f seed (Node t0 n t1) = foldTree f (f n (foldTree f seed t1)) t0
flattenTree :: Tree a -> [a]
flattenTree = foldTree (:) []
|
slon1024/functional_programming
|
haskell/Tree.hs
|
mit
| 555 | 0 | 9 | 166 | 304 | 154 | 150 | 13 | 1 |
module Main (main, spec) where
import Test.Hspec
import Game.FizzBuzz
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "fizzbuzz" $ do
it "should return Fizz if int is dividable by 3" $
fizzbuzz 3 `shouldBe` "Fizz"
it "should return Buzz if int is dividable by 5" $
fizzbuzz 5 `shouldBe` "Buzz"
it "should return FizzBuzz if int dividable by 3 and 5" $
fizzbuzz 15 `shouldBe` "FizzBuzz"
it "should return the int as string if not dividable by 3 or 5" $
fizzbuzz 1 `shouldBe` "1"
|
to4iki/fizzbuzz-hs
|
test/Spec.hs
|
mit
| 584 | 0 | 12 | 182 | 136 | 69 | 67 | 16 | 1 |
module P028 (main, solveBasic) where
{-
Starting with the number 1 and moving to the right in a clockwise direction
a 5 by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
It can be verified that the sum of the numbers on the diagonals is 101.
What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral
formed in the same way?
-}
import qualified Common as C
input :: Int
input = 1001
main :: IO ()
main = -- do
C.time "P028(Basic): " $ solveBasic input
-- 前提として、nは奇数でなければならない。
--
-- サイズnの四角形の対角線の和をS(n)とし、サイズnの四角形の各頂点の数字の和を
-- T(n)とすると、
-- S(n) = 1 (n = 1)
-- = T(n) + S(n-2) (n >= 3)
-- である。
-- また、
-- T(n) = 1 (n = 1)
-- = n^2 + (n^2 - n + 1) + (n^2 - 2n + 2) + (n^2 - 3n + 3) (n >= 3)
-- = 4n^2 - 6n + 6
-- である。
--
-- n >= 3の場合
-- n >= 3 の場合
-- kを自然数とすれば、n = 2k+1 と書ける。その場合、T(n)をkで表すと
-- T(k) = 4n^2 - 6n + 6
-- = 4(2k+1)^2 - 6(2k+1) + 6
-- = 4(4k^2 + 4k + 1) - 6(2k+1) + 6
-- = 16k^2 + 16k + 4 - 12k - 6 + 6
-- = 16k^2 + 4k + 4
-- = 4(4k^2 + k + 1)
-- S(n) = 1 + Σ(k=1 -> (n-1)/2)T(k)
-- = 1 + 4{4((n-1)/2)(((n-1)/2)+1)(2((n-1)/2)+1)/6 + ((n-1)/2)(((n-1)/2)+1)/2 + ((n-1)/2)}
-- = 1 + 4{4*((n-1)/2)*((n+1)/2)*(n)/6 + ((n-1)/2)*((n+1)/2)/2 + (n-1)/2}
-- = 1 + 4(n-1)*(n+1)*(n)/6 + (n-1)*(n+1)/2 + 2(n-1)
-- = 6/6 + 4(n-1)*(n+1)*(n)/6 + 3(n-1)*(n+1)/6 + 12(n-1)/6
-- = {6 + 4(n-1)*(n+1)*(n) + 3(n-1)*(n+1) + 12(n-1)}/6
-- = {6 + 4n^3-4n + 3n^2-3 + 12n - 12}/6
-- = (4n^3 + 3n^2 + 8n - 9)/6
-- これはS(1)の場合も成立する。
solveBasic :: Int -> Int
solveBasic n = (4*n^(3::Int) + 3*n^(2::Int) + 8*n - 9) `div` 6
|
yyotti/euler_haskell
|
src/P028.hs
|
mit
| 1,926 | 0 | 14 | 482 | 158 | 104 | 54 | 9 | 1 |
-- 1. Given the type
type Gardener = String
-- What is the normal form of Garden?
data Garden =
Gardenia Gardener
| Daisy Gardener
| Rose Gardener
| Lilac Gardener
deriving Show
|
diminishedprime/.org
|
reading-list/haskell_programming_from_first_principles/11_10.hs
|
mit
| 191 | 0 | 6 | 46 | 36 | 22 | 14 | 7 | 0 |
module Lang where
import Debug.Trace
import Data.List
import Data.Function
data MOp = Neg | Not deriving (Eq,Ord)
data BOp = Plus
| Minus
| Times
| Div
| And
| Or
| Equal
| LessThan
| GreaterThan
deriving (Eq,Ord)
type Name = String
data Lit = LInt Int | LBool Bool deriving (Eq,Ord)
data Expr = Ident Name
| Lit Lit
| Susp Expr
| Force Expr
| Lam Name Expr
| App Expr Expr
| BinOp BOp Expr Expr
| MonOp MOp Expr
| Let Binding Expr
| If Expr Expr Expr deriving (Eq,Ord{-,Show-})
data Binding = Bind Name Expr deriving (Eq,Ord)
type Env = [Binding]
data State = State [Binding] Env deriving (Show)
bindingName :: Binding -> Name
bindingName (Bind n _) = n
addBinding :: Env -> Binding -> Env
addBinding env (Bind name expr) = (Bind name (evalExpr expr env)) : env
{-free(e) = FV(e)-}
free :: Expr -> [Name]
free (Lit _) = []
free (Lam x e) = delete x $ free e
free (Ident y) = [y]
free (Susp e) = free e
free (Force e) = free e
free (App e e') = union (free e) (free e')
free (BinOp _ e e') = union (free e) (free e')
free (MonOp _ e) = free e
free (Let b e) = delete (bindingName b) $ free e
free (If p e e') = union (union (free e) (free e')) (free p)
isFreeIn :: Name -> Expr -> Bool
isFreeIn x e' = x `elem` (free e')
alphaConvertLam :: Expr -> Expr
alphaConvertLam (Lam x e) = let x' = x ++ "0" in
(Lam x' $ subst x (Ident x') e)
{- e[x -> e0] -}
{- e[e0/x] -}
execSubst :: Name -> Expr -> Expr -> Expr
execSubst x e0 (Ident y) = if x == y then e0 else (Ident y)
execSubst x e0 (Lit n) = (Lit n)
execSubst x e0 (Susp e) = Susp (execSubst x e0 e)
execSubst x e0 (Force e) = Force (execSubst x e0 e)
{- If we're substituting INTO a lambda,
we need to make sure that the variable we are substituting
isn't the same as the lambda argument. If it is, we alphaconvert the
lambda, then substitute.
-}
execSubst x e0 (Lam u eu) = if x `isFreeIn` eu
then let lam' = alphaConvertLam (Lam u eu) in
execSubst x e0 lam'
else (Lam u $ execSubst x e0 eu)
execSubst x e0 (App e e') = App (execSubst x e0 e) (execSubst x e0 e')
execSubst x e0 (BinOp b e' e'') = BinOp b (execSubst x e0 e') (execSubst x e0 e'')
execSubst x e0 (MonOp m e) = MonOp m (execSubst x e0 e)
execSubst x e0 (If p t f) = If (execSubst x e0 p) (execSubst x e0 t) (execSubst x e0 f)
execSubst x e0 (Let (Bind y e1) e) = Let (Bind y e1') e'
where
e1' = execSubst x e0 e1
e' = execSubst x e0 e
substBinding :: Binding -> Expr -> Expr
substBinding (Bind n e) = execSubst n e
{-This is here since I think I might need to other stuff in here in the future-}
{- e[x -> e0] -}
subst :: Name -> Expr -> Expr -> Expr
subst x e0 e = execSubst x e0 e
isSusp :: Expr -> Bool
isSusp (Susp _) = True
isSusp _ = False
isVal :: Expr -> Bool
isVal (Lit _) = True
isVal (Susp _) = True
isVal (Lam _ _) = True
isVal _ = False
stepIntBinOp :: BOp -> Int -> Int -> Expr
stepIntBinOp Plus x y = Lit $ LInt $ x + y
stepIntBinOp Minus x y = Lit $ LInt $ x - y
stepIntBinOp Div x y = Lit $ LInt $ div x y
stepIntBinOp Times x y = Lit $ LInt $ x * y
stepIntBinOp Equal x y = Lit $ LBool $ x == y
stepIntBinOp LessThan x y = Lit $ LBool $ x < y
stepIntBinOp GreaterThan x y = Lit $ LBool $ x > y
stepBoolBinOp :: BOp -> Bool -> Bool -> Expr
stepBoolBinOp And x y = Lit $ LBool $ x && y
stepBoolBinOp Or x y = Lit $ LBool $ x || y
stepIntMonOp :: MOp -> Int -> Expr
stepIntMonOp Neg x = Lit $ LInt $ -x
stepBoolMonOp :: MOp -> Bool -> Expr
stepBoolMonOp Not x = Lit $ LBool $ not x
{- step rules for basics -}
step :: Expr -> Expr
step (Ident x) = Ident x
step (Lit x) = Lit x
step (Force (Susp e)) = e
step (Susp e) = if isVal e then e else (Susp e)
step (Force e) = e
step (Lam n e) = (Lam n e)
step (App (Lam x e) (Lit v)) = subst x (Lit v) e
step (App (Lam x e) e0) = App (Lam x e) $ step e0
{- Stall simplification until next substitution happens. -}
step (App (Ident x) (Lit v)) = (App (Ident x) (Lit v))
step (App (Ident x) e0) = App (Ident x) $ step e0
{- If not trying to apply to a lambda, try to simplify that expression to a lambda.-}
{- This allows for currying. -}
step (App lam arg) = App (step lam) arg
{- Step rules for binary operations-}
step (BinOp b (Lit (LInt x)) (Lit (LInt y))) = stepIntBinOp b x y
step (BinOp b (Lit (LBool x)) (Lit (LBool y))) = stepBoolBinOp b x y
step (BinOp b (Lit x) ey) = BinOp b (Lit x) $ step ey
step (BinOp b ex ey) = BinOp b (step ex) ey
{- step rules for unary operations -}
step (MonOp b (Lit (LInt x))) = stepIntMonOp b x
step (MonOp b (Lit (LBool x))) = stepBoolMonOp b x
step (MonOp b e) = MonOp b $ step e
{-step rules for let expressions -}
step (Let (Bind x e0) e) = if isVal e0
then subst x e0 e
else Let (Bind x $ step e0) e
{- Step rules for if statements -}
step (If (Lit (LBool True)) x y) = x
step (If (Lit (LBool False)) x y) = y
step (If p x y) = If (step p) x y
substEnv :: Expr -> Env -> Expr
substEnv e [] = e
substEnv e (b : bs) = substEnv (substBinding b e) bs
manyStep :: Expr -> Expr
manyStep e = let
e' = step e
in if e' == e
then e
else manyStep e'
evalExpr :: Expr -> Env -> Expr
evalExpr e env = let
e' = manyStep $ substEnv (manyStep e) env
in if isVal e' || isSusp e'
then e'
else evalExpr e' env
execDecl :: State -> State
execDecl (State [] env) = State [] env
execDecl (State (Bind vName expr : rest) env) = let
newBinding = Bind vName $ evalExpr expr env
in State rest $ addBinding env newBinding
run :: State -> State
run (State [] env) = State [] env
run s = run $ execDecl s
litShow :: Lit -> String
litShow (LBool b) = show b
litShow (LInt i) = show i
instance Show Lit where
show = litShow
mopShow :: MOp -> String
mopShow Neg = "-"
mopShow Not = "!"
bopShow :: BOp -> String
bopShow Plus = "+"
bopShow Minus = "-"
bopShow Times = "*"
bopShow Div = "/"
bopShow And = "&&"
bopShow Or = "||"
bopShow Equal = "=="
bopShow GreaterThan = ">"
bopShow LessThan = "<"
bindingShow :: Binding -> String
bindingShow (Bind n e) = n ++ " = " ++ exprShow e
exprShow :: Expr -> String
exprShow (Ident s) = s
exprShow (Lit l) = show l
exprShow (Lam n expr) = "(\\" ++ n ++ " -> " ++ (exprShow expr) ++ ")"
exprShow (App e0 e1) = "(" ++ exprShow e0 ++ " " ++ exprShow e1 ++ ")"
exprShow (BinOp b e0 e1) = "(" ++ exprShow e0 ++ " " ++ show b ++ " " ++ exprShow e1 ++ ")"
exprShow (MonOp m e) = mopShow m ++ exprShow e
exprShow (Let binding subexpr) = "let " ++ bindingShow binding ++ " in " ++ exprShow subexpr
exprShow (If p t f) = "if " ++ exprShow p ++ " then " ++ exprShow t ++ " else " ++ exprShow f
exprShow (Force e) = "force(" ++ exprShow e ++ ")"
exprShow (Susp e) = "susp(" ++ exprShow e ++ ")"
instance Show Binding where
show = bindingShow
instance Show Expr where
show = exprShow
instance Show MOp where
show = mopShow
instance Show BOp where
show = bopShow
litRead :: String -> Lit
litRead "True" = LBool True
litRead "False" = LBool False
litRead n = LInt $ read n
bopRead :: String -> BOp
bopRead "+" = Plus
bopRead "-" = Minus
bopRead "*" = Times
bopRead "/" = Div
bopRead "&&" = And
bopRead "||"= Or
bopRead "=="= Equal
bopRead "<" = LessThan
bopRead ">" = GreaterThan
mopRead :: String -> MOp
mopRead "-" = Neg
mopRead "!" = Not
|
jdublu10/toy_lang
|
src/Lang.hs
|
mit
| 7,631 | 0 | 12 | 2,123 | 3,451 | 1,736 | 1,715 | 197 | 3 |
import System.Random
-- Problem 25
-- Generate a random permutation of the elements of a list.
-- Remove the K'th element from a list.
removeAt :: Int -> [a] -> (a,[a])
removeAt i (x:xs) | i > 1 = (xz,x:yz)
| otherwise = (x,xs)
where (xz,yz) = removeAt (i-1) xs
rndPermutationG :: RandomGen g => [a] -> g -> [a]
rndPermutationG [] _ = []
rndPermutationG ls gen =
let (i,g) = randomR (0, length ls - 1) gen
(x,xs) = removeAt i ls
in x : rndPermutationG (reverse xs) g
rndPermutation :: [a] -> IO [a]
rndPermutation ls = do
gen <- getStdGen
return $ rndPermutationG ls gen
main :: IO()
main = do
xs <- rndPermutation "abcdefg"
print xs
|
baldore/haskell-99-exercises
|
25.hs
|
mit
| 684 | 0 | 12 | 171 | 306 | 158 | 148 | 19 | 1 |
module BetaBin where
-- The beta-binomial model in latent variable and urn model representations.
-- The two formulations should be exactly equivalent, but only urn works with Dist.
import Control.Monad.State.Lazy (get,put,evalStateT)
import Control.Monad.Bayes.Class
-- | Beta-binomial model as an i.i.d. sequence conditionally on weight.
latent :: MonadDist m => Int -> m [Bool]
latent n = do
weight <- uniform 0 1
let toss = bernoulli weight
sequence $ replicate n $ toss
-- | Beta-binomial as a random process.
urn :: MonadDist m => Int -> m [Bool]
urn n = flip evalStateT (1,1) $ do
let toss = do
(a,b) <- get
let weight = a / (a + b)
outcome <- bernoulli weight
let (a',b') = if outcome then (a+1,b) else (a,b+1)
put (a',b')
return outcome
sequence $ replicate n $ toss
-- | Post-processing by counting the number of True values.
count :: [Bool] -> Int
count = length . filter id
-- | A beta-binomial model where the first three states are True,True,False.
-- The resulting distribution is on the remaining outcomes.
cond :: MonadBayes m => m [Bool] -> m [Bool]
cond d = do
(first:second:third:rest) <- d
condition (first == True)
condition (second == True)
condition (third == False)
return rest
-- | The final conditional model, abstracting the representation.
model :: MonadBayes m => (Int -> m [Bool]) -> Int -> m Int
model repr n = fmap count $ cond $ repr (n+3)
|
ocramz/monad-bayes
|
models/BetaBin.hs
|
mit
| 1,517 | 0 | 18 | 385 | 472 | 241 | 231 | 29 | 2 |
module Joy.EnumSet (
EnumSet,
enumInSet,
emptyEnumSet,
fullEnumSet,
inverseEnumSet,
rangeEnumSet,
enumerationEnumSet,
negativeEnumerationEnumSet,
unionEnumSet,
differenceEnumSet,
relevantSubsetsForEnumSets,
anyEnumInSet,
toList,
fromList
)
where
import Data.List
import Data.Maybe
data (Ord content, Bounded content, Enum content) => EnumSet content
= EnumSet [(content, content)]
instance (Ord content, Bounded content, Enum content) => Show (EnumSet content) where
show (EnumSet ranges) = show $ map (\(start, end) -> (toEnum $ fromEnum start :: Char, toEnum $ fromEnum end :: Char)) ranges
instance (Ord content, Bounded content, Enum content) => Ord (EnumSet content) where
compare (EnumSet rangesA) (EnumSet rangesB) = compare rangesA rangesB
enumInSet
:: (Ord content, Bounded content, Enum content)
=> (EnumSet content)
-> content
-> Bool
enumInSet (EnumSet ranges) enum
= let enumInRange (start, end) =
(fromEnum start <= fromEnum enum) && (fromEnum enum <= fromEnum end)
in any enumInRange ranges
emptyEnumSet
:: (Ord content, Bounded content, Enum content)
=> EnumSet content
emptyEnumSet = EnumSet []
fullEnumSet
:: (Ord content, Bounded content, Enum content)
=> EnumSet content
fullEnumSet = EnumSet [(minBound, maxBound)]
inverseEnumSet
:: (Ord content, Bounded content, Enum content)
=> EnumSet content
-> EnumSet content
inverseEnumSet enumSet = differenceEnumSet fullEnumSet enumSet
rangeEnumSet
:: (Ord content, Bounded content, Enum content)
=> content
-> content
-> EnumSet content
rangeEnumSet start end = EnumSet [(start, end)]
enumerationEnumSet
:: (Ord content, Bounded content, Enum content)
=> [content]
-> EnumSet content
enumerationEnumSet enums
= foldl addEnumToSet emptyEnumSet enums
negativeEnumerationEnumSet
:: (Ord content, Bounded content, Enum content)
=> [content]
-> EnumSet content
negativeEnumerationEnumSet enums
= foldl removeEnumFromSet fullEnumSet enums
unionEnumSet
:: (Ord content, Bounded content, Enum content)
=> (EnumSet content)
-> (EnumSet content)
-> (EnumSet content)
unionEnumSet (EnumSet rangesA) (EnumSet rangesB)
= EnumSet $ unionRangeSets rangesA rangesB
differenceEnumSet
:: (Ord content, Bounded content, Enum content)
=> (EnumSet content)
-> (EnumSet content)
-> (EnumSet content)
differenceEnumSet (EnumSet rangesA) (EnumSet rangesB)
= EnumSet $ subtractRangeSets rangesA rangesB
addEnumToSet
:: (Ord content, Bounded content, Enum content)
=> (EnumSet content)
-> content
-> (EnumSet content)
addEnumToSet (EnumSet ranges) enum
= EnumSet $ unionRangeSets ranges [(enum, enum)]
removeEnumFromSet
:: (Ord content, Bounded content, Enum content)
=> (EnumSet content)
-> content
-> (EnumSet content)
removeEnumFromSet (EnumSet ranges) enum
= EnumSet $ subtractRangeSets ranges [(enum, enum)]
findLastStartingBefore
:: (Ord content, Bounded content, Enum content)
=> [(content, content)]
-> (content, content)
-> Bool
-> (Maybe Int, Bool)
findLastStartingBefore ranges newRange joinAdjacent
= let maybeIndex = case ranges of
[] -> Nothing
(firstRange:_) | fst newRange < fst firstRange -> Nothing
_ -> foldl (\lastResult (range, i)
-> if fst range <= fst newRange
then Just i
else lastResult)
Nothing
$ zip ranges [0..]
intersects = maybe False
(\index -> ((fromEnum $ fst newRange)
- (fromEnum $ snd $ head $ drop index ranges))
<= (if joinAdjacent then 1 else 0))
maybeIndex
in (maybeIndex, intersects)
findFirstEndingAfter
:: (Ord content, Bounded content, Enum content)
=> [(content, content)]
-> (content, content)
-> Bool
-> (Maybe Int, Bool)
findFirstEndingAfter ranges newRange joinAdjacent
= let maybeLengthMinusIndex
= case reverse ranges of
[] -> Nothing
(lastRange:_) | snd lastRange < snd newRange -> Nothing
reversedRanges -> foldl (\lastResult (range, i)
-> if snd newRange <= snd range
then Just i
else lastResult)
Nothing
$ zip reversedRanges [0..]
maybeIndex
= maybe Nothing
(\index -> Just $ length ranges - index - 1)
maybeLengthMinusIndex
intersects = maybe False
(\index -> ((fromEnum $ fst $ head $ drop index ranges)
- (fromEnum $ snd newRange))
<= (if joinAdjacent then 1 else 0))
maybeIndex
in (maybeIndex, intersects)
findStartAndEndInformation
:: (Ord content, Bounded content, Enum content)
=> [(content, content)]
-> (content, content)
-> Bool
-> (Maybe Int, Bool, Maybe Int, Bool)
findStartAndEndInformation ranges newRange joinAdjacent
= let (maybeStartIndex, startIntersects)
= findLastStartingBefore ranges newRange joinAdjacent
(maybeEndIndex, endIntersects)
= findFirstEndingAfter ranges newRange joinAdjacent
in (maybeStartIndex, startIntersects, maybeEndIndex, endIntersects)
addRangeToSet
:: (Ord content, Bounded content, Enum content)
=> [(content, content)]
-> (content, content)
-> [(content, content)]
addRangeToSet ranges newRange
= let (maybeStartIndex, startIntersects, maybeEndIndex, endIntersects)
= findStartAndEndInformation ranges newRange True
in if (isNothing maybeStartIndex) && (isNothing maybeEndIndex)
then [newRange]
else concat [maybe []
(\startIndex -> take (if startIntersects
then startIndex
else startIndex + 1)
ranges)
maybeStartIndex,
[(if startIntersects
then fst $ head $ drop (fromJust maybeStartIndex) ranges
else fst newRange,
if endIntersects
then snd $ head $ drop (fromJust maybeEndIndex) ranges
else snd newRange)],
maybe []
(\endIndex -> drop (if endIntersects
then endIndex + 1
else endIndex)
ranges)
maybeEndIndex]
subtractRangeFromSet
:: (Ord content, Bounded content, Enum content)
=> [(content, content)]
-> (content, content)
-> [(content, content)]
subtractRangeFromSet ranges newRange
= let (maybeStartIndex, startIntersects, maybeEndIndex, endIntersects)
= findStartAndEndInformation ranges newRange True
in if (isNothing maybeStartIndex) && (isNothing maybeEndIndex)
then []
else concat [maybe []
(\startIndex -> take (if startIntersects
then startIndex
else startIndex + 1)
ranges)
maybeStartIndex,
if startIntersects
&& (fst newRange
> (fst $ head $ drop (fromJust maybeStartIndex) ranges))
then [(fst $ head $ drop (fromJust maybeStartIndex) ranges,
toEnum $ (fromEnum $ fst newRange) - 1)]
else [],
if endIntersects
&& ((snd $ head $ drop (fromJust maybeEndIndex) ranges)
> snd newRange)
then [(toEnum $ (fromEnum $ snd newRange) + 1,
snd $ head $ drop (fromJust maybeEndIndex) ranges)]
else [],
maybe []
(\endIndex -> drop (if endIntersects
then endIndex + 1
else endIndex)
ranges)
maybeEndIndex]
overlappingRangeParts
:: (Ord content, Bounded content, Enum content)
=> [(content, content)]
-> (content, content)
-> [(content, content)]
overlappingRangeParts ranges newRange
= let (maybeStartIndex, startIntersects, maybeEndIndex, endIntersects)
= findStartAndEndInformation ranges newRange False
in case (maybeStartIndex, maybeEndIndex) of
(Nothing, Nothing) -> []
(Just a, Just b) | a == b -> [newRange]
_ -> concat [maybe []
(\startIndex
-> if startIntersects
then [(fst newRange,
snd $ head $ drop startIndex ranges)]
else [])
maybeStartIndex,
let rangeStart = maybe 0 (1+) maybeStartIndex
rangeEnd = maybe (length ranges) id maybeEndIndex
nToTake = rangeEnd - rangeStart
nToDrop = rangeStart
in take nToTake $ drop nToDrop ranges,
maybe []
(\endIndex
-> if endIntersects
then [(fst $ head $ drop endIndex ranges,
snd newRange)]
else [])
maybeEndIndex]
nonOverlappingRangeParts
:: (Ord content, Bounded content, Enum content)
=> [(content, content)]
-> (content, content)
-> [(content, content)]
nonOverlappingRangeParts ranges newRange
= foldl (\result overlappingPart -> subtractRangeFromSet result overlappingPart)
[newRange]
$ overlappingRangeParts ranges newRange
intersectRangeSets
:: (Ord content, Bounded content, Enum content)
=> [(content, content)]
-> [(content, content)]
-> [(content, content)]
intersectRangeSets a b
= foldl (\result range -> foldl (\result part -> addRangeToSet result part)
result
$ overlappingRangeParts a range)
[]
b
unionRangeSets
:: (Ord content, Bounded content, Enum content)
=> [(content, content)]
-> [(content, content)]
-> [(content, content)]
unionRangeSets a b
= foldl (\result range -> addRangeToSet result range)
a
b
subtractRangeSets
:: (Ord content, Bounded content, Enum content)
=> [(content, content)]
-> [(content, content)]
-> [(content, content)]
subtractRangeSets a b
= foldl (\result range -> subtractRangeFromSet result range)
a
b
exclusiveOrRangeSets
:: (Ord content, Bounded content, Enum content)
=> [(content, content)]
-> [(content, content)]
-> [(content, content)]
exclusiveOrRangeSets a b
= let result = foldl (\result range
-> foldl (\result part -> addRangeToSet result part)
result
$ nonOverlappingRangeParts b range)
[]
a
result' = foldl (\result range
-> foldl (\result part -> addRangeToSet result part)
result
$ nonOverlappingRangeParts a range)
result
b
in result'
{-
< |====|====| | | > (A B)
< | |====| |====| > (B D)
union to
< |====|====| |====| > (A B D) -- union
difference to
< |====| | | | > (A) -- difference
intersect to
< | |====| | | > (B) -- intersect
xor to
< |====| | |====| > (A D) -- xor
-}
relevantSubsetsForEnumSets
:: (Ord content, Bounded content, Enum content)
=> [EnumSet content]
-> [EnumSet content]
relevantSubsetsForEnumSets sets =
let computeBoundaries f
= sort $ nub $ concat $ map (\(EnumSet ranges) -> map f ranges)
sets
startBoundaries = computeBoundaries fst
endBoundaries = computeBoundaries snd
startBoundariesMinusOne
= mapMaybe (\i -> if i > minBound
then Just $ toEnum $ (-1+) $ fromEnum i
else Nothing)
startBoundaries
endBoundariesPlusOne = mapMaybe (\i -> if i < maxBound
then Just $ toEnum $ (1+) $ fromEnum i
else Nothing)
endBoundaries
allBoundaries
= sort $ concat [startBoundaries,
endBoundaries,
filter (\i -> not $ elem i endBoundaries)
startBoundariesMinusOne,
filter (\i -> not $ elem i startBoundaries)
endBoundariesPlusOne]
nToDropFromStart = if elem minBound startBoundaries
then 0
else 1
nToDropFromEnd = if elem maxBound endBoundaries
then 0
else 1
allBoundariesWithoutEndpoints
= drop nToDropFromStart
$ reverse
$ drop nToDropFromEnd
$ reverse allBoundaries
allBoundariesEvenIndices
= map fst $ filter (even . snd) $ zip allBoundariesWithoutEndpoints [0..]
allBoundariesOddIndices
= map fst $ filter (odd . snd) $ zip allBoundariesWithoutEndpoints [0..]
in map (\range -> EnumSet [range])
$ zip allBoundariesEvenIndices allBoundariesOddIndices
anyEnumInSet
:: (Ord content, Bounded content, Enum content)
=> EnumSet content
-> Maybe content
anyEnumInSet (EnumSet ((result, _):_)) = Just result
anyEnumInSet _ = Nothing
toList
:: (Ord content, Bounded content, Enum content)
=> EnumSet content
-> [(content, content)]
toList (EnumSet ranges) = ranges
fromList
:: (Ord content, Bounded content, Enum content)
=> [(content, content)]
-> EnumSet content
fromList ranges = EnumSet ranges
instance (Ord content, Bounded content, Enum content) => Eq (EnumSet content) where
(EnumSet aRanges) == (EnumSet bRanges)
= aRanges == bRanges
|
IreneKnapp/Joy
|
Joy/EnumSet.hs
|
mit
| 16,197 | 0 | 19 | 6,876 | 3,990 | 2,119 | 1,871 | 363 | 6 |
{-# LANGUAGE PackageImports #-}
{-# OPTIONS_GHC -fno-warn-dodgy-exports -fno-warn-unused-imports #-}
-- | Reexports "Foreign.ForeignPtr.Unsafe.Compat"
-- from a globally unique namespace.
module Foreign.ForeignPtr.Unsafe.Compat.Repl.Batteries (
module Foreign.ForeignPtr.Unsafe.Compat
) where
import "this" Foreign.ForeignPtr.Unsafe.Compat
|
haskell-compat/base-compat
|
base-compat-batteries/src/Foreign/ForeignPtr/Unsafe/Compat/Repl/Batteries.hs
|
mit
| 342 | 0 | 5 | 31 | 32 | 25 | 7 | 5 | 0 |
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Hadoop.Protos.RefreshAuthorizationPolicyProtocolProtos.RefreshServiceAclRequestProto (RefreshServiceAclRequestProto(..))
where
import Prelude ((+), (/))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data RefreshServiceAclRequestProto = RefreshServiceAclRequestProto{}
deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data)
instance P'.Mergeable RefreshServiceAclRequestProto where
mergeAppend RefreshServiceAclRequestProto RefreshServiceAclRequestProto = RefreshServiceAclRequestProto
instance P'.Default RefreshServiceAclRequestProto where
defaultValue = RefreshServiceAclRequestProto
instance P'.Wire RefreshServiceAclRequestProto where
wireSize ft' self'@(RefreshServiceAclRequestProto)
= case ft' of
10 -> calc'Size
11 -> P'.prependMessageSize calc'Size
_ -> P'.wireSizeErr ft' self'
where
calc'Size = 0
wirePut ft' self'@(RefreshServiceAclRequestProto)
= case ft' of
10 -> put'Fields
11 -> do
P'.putSize (P'.wireSize 10 self')
put'Fields
_ -> P'.wirePutErr ft' self'
where
put'Fields
= do
Prelude'.return ()
wireGet ft'
= case ft' of
10 -> P'.getBareMessageWith update'Self
11 -> P'.getMessageWith update'Self
_ -> P'.wireGetErr ft'
where
update'Self wire'Tag old'Self
= case wire'Tag of
_ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
instance P'.MessageAPI msg' (msg' -> RefreshServiceAclRequestProto) RefreshServiceAclRequestProto where
getVal m' f' = f' m'
instance P'.GPB RefreshServiceAclRequestProto
instance P'.ReflectDescriptor RefreshServiceAclRequestProto where
getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList [])
reflectDescriptorInfo _
= Prelude'.read
"DescriptorInfo {descName = ProtoName {protobufName = FIName \".hadoop.common.RefreshServiceAclRequestProto\", haskellPrefix = [MName \"Hadoop\",MName \"Protos\"], parentModule = [MName \"RefreshAuthorizationPolicyProtocolProtos\"], baseName = MName \"RefreshServiceAclRequestProto\"}, descFilePath = [\"Hadoop\",\"Protos\",\"RefreshAuthorizationPolicyProtocolProtos\",\"RefreshServiceAclRequestProto.hs\"], isGroup = False, fields = fromList [], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
instance P'.TextType RefreshServiceAclRequestProto where
tellT = P'.tellSubMessage
getT = P'.getSubMessage
instance P'.TextMsg RefreshServiceAclRequestProto where
textPut msg = Prelude'.return ()
textGet = Prelude'.return P'.defaultValue
|
alexbiehl/hoop
|
hadoop-protos/src/Hadoop/Protos/RefreshAuthorizationPolicyProtocolProtos/RefreshServiceAclRequestProto.hs
|
mit
| 3,090 | 1 | 16 | 546 | 554 | 291 | 263 | 53 | 0 |
{-# LANGUAGE PackageImports, BangPatterns, QuasiQuotes, PatternGuards,
MagicHash, ScopedTypeVariables, TypeFamilies #-}
{-# OPTIONS -Wall -fno-warn-missing-signatures -fno-warn-incomplete-patterns #-}
-- | Canny edge detector.
--
-- NOTE: for best performance this needs to be compiled with the following GHC options:
-- -fllvm -optlo-O3 -Odph -fno-liberate-case
-- -funfolding-use-threshold100 -funfolding-keeness-factor100
--
import Data.List
import Data.Word
import Data.Int
import Control.Monad
import System.Environment
import Data.Array.Repa as R
import Data.Array.Repa.Repr.Unboxed as U
import Data.Array.Repa.Repr.Cursored as C
import Data.Array.Repa.Stencil
import Data.Array.Repa.Stencil.Dim2
import Data.Array.Repa.Specialised.Dim2
import Data.Array.Repa.Algorithms.Pixel
import Data.Array.Repa.IO.BMP
import Data.Array.Repa.IO.Timing
import Debug.Trace
import GHC.Exts
import qualified Data.Vector.Unboxed.Mutable as VM
import qualified Data.Vector.Unboxed as V
import qualified Prelude as P
import Prelude hiding (compare)
type Image a = Array U DIM2 a
-- Constants ------------------------------------------------------------------
orientUndef = 0 :: Word8
orientPosDiag = 64 :: Word8
orientVert = 128 :: Word8
orientNegDiag = 192 :: Word8
orientHoriz = 255 :: Word8
data Edge = None | Weak | Strong
edge None = 0 :: Word8
edge Weak = 128 :: Word8
edge Strong = 255 :: Word8
-- Main routine ---------------------------------------------------------------
main
= do args <- getArgs
case args of
[fileIn, fileOut]
-> run 0 50 100 fileIn fileOut
[loops, threshLow, threshHigh, fileIn, fileOut]
-> run (read loops) (read threshLow) (read threshHigh) fileIn fileOut
_ -> putStrLn
$ concat [ "repa-canny [<loops::Int> <threshLow::Int> <threshHigh::Int>]"
, " <fileIn.bmp> <fileOut.bmp>" ]
run loops threshLow threshHigh fileIn fileOut
= do arrInput <- liftM (either (error . show) id)
$ readImageFromBMP fileIn
(arrResult, tTotal)
<- time $ process loops threshLow threshHigh arrInput
when (loops >= 1)
$ putStrLn $ "\nTOTAL\n"
putStr $ prettyTime tTotal
writeImageToBMP fileOut (U.zip3 arrResult arrResult arrResult)
process loops threshLow threshHigh arrInput
= do arrGrey <- timeStage loops "toGreyScale"
$ toGreyScale arrInput
arrBluredX <- timeStage loops "blurX"
$ blurSepX arrGrey
arrBlured <- timeStage loops "blurY"
$ blurSepY arrBluredX
arrDX <- timeStage loops "diffX"
$ gradientX arrBlured
arrDY <- timeStage loops "diffY"
$ gradientY arrBlured
arrMagOrient <- timeStage loops "magOrient"
$ gradientMagOrient threshLow arrDX arrDY
arrSuppress <- timeStage loops "suppress"
$ suppress threshLow threshHigh arrMagOrient
arrStrong <- timeStage loops "select"
$ selectStrong arrSuppress
arrEdges <- timeStage loops "wildfire"
$ wildfire arrSuppress arrStrong
return arrEdges
-- | Wrapper to time each stage of the algorithm.
timeStage
:: (Shape sh, Unbox a)
=> Int
-> String
-> IO (Array U sh a)
-> IO (Array U sh a)
timeStage loops name fn
= do
let burn !n
= do !arr <- fn
if n <= 1 then return arr
else burn (n - 1)
traceEventIO $ "**** Stage " P.++ name P.++ " begin."
(arrResult, t)
<- time $ do !arrResult' <- burn loops
return arrResult'
traceEventIO $ "**** Stage " P.++ name P.++ " end."
when (loops >= 1)
$ putStr $ name P.++ "\n"
P.++ unlines [ " " P.++ l | l <- lines $ prettyTime t ]
return arrResult
{-# NOINLINE timeStage #-}
-------------------------------------------------------------------------------
-- | RGB to greyscale conversion.
toGreyScale :: Image (Word8, Word8, Word8) -> IO (Image Float)
toGreyScale arr
= computeP
$ R.map (* 255)
$ R.map floatLuminanceOfRGB8 arr
{-# NOINLINE toGreyScale #-}
-- | Separable Gaussian blur in the X direction.
blurSepX :: Image Float -> IO (Image Float)
blurSepX arr
= computeP
$ forStencil2 BoundClamp arr
[stencil2| 1 4 6 4 1 |]
{-# NOINLINE blurSepX #-}
-- | Separable Gaussian blur in the Y direction.
blurSepY :: Image Float -> IO (Image Float)
blurSepY arr
= computeP
$ R.smap (/ 256)
$ forStencil2 BoundClamp arr
[stencil2| 1
4
6
4
1 |]
{-# NOINLINE blurSepY #-}
-- | Compute gradient in the X direction.
gradientX :: Image Float -> IO (Image Float)
gradientX img
= computeP
$ forStencil2 BoundClamp img
[stencil2| -1 0 1
-2 0 2
-1 0 1 |]
{-# NOINLINE gradientX #-}
-- | Compute gradient in the Y direction.
gradientY :: Image Float -> IO (Image Float)
gradientY img
= computeP
$ forStencil2 BoundClamp img
[stencil2| 1 2 1
0 0 0
-1 -2 -1 |]
{-# NOINLINE gradientY #-}
-- | Classify the magnitude and orientation of the vector gradient.
gradientMagOrient
:: Float -> Image Float -> Image Float -> IO (Image (Float, Word8))
gradientMagOrient !threshLow dX dY
= computeP
$ R.zipWith magOrient dX dY
where magOrient :: Float -> Float -> (Float, Word8)
magOrient !x !y
= (magnitude x y, orientation x y)
{-# INLINE magOrient #-}
magnitude :: Float -> Float -> Float
magnitude !x !y
= sqrt (x * x + y * y)
{-# INLINE magnitude #-}
{-# INLINE orientation #-}
orientation :: Float -> Float -> Word8
orientation !x !y
-- Don't bother computing orientation if vector is below threshold.
| x >= negate threshLow, x < threshLow
, y >= negate threshLow, y < threshLow
= orientUndef
| otherwise
= let -- Determine the angle of the vector and rotate it around a bit
-- to make the segments easier to classify.
!d = atan2 y x
!dRot = (d - (pi/8)) * (4/pi)
-- Normalise angle to beween 0..8
!dNorm = if dRot < 0 then dRot + 8 else dRot
-- Doing explicit tests seems to be faster than using the FP floor function.
in fromIntegral
$ I# (if dNorm >= 4
then if dNorm >= 6
then if dNorm >= 7
then 255# -- 7
else 192# -- 6
else if dNorm >= 5
then 128# -- 5
else 64# -- 4
else if dNorm >= 2
then if dNorm >= 3
then 255# -- 3
else 192# -- 2
else if dNorm >= 1
then 128# -- 1
else 64#) -- 0
{-# NOINLINE gradientMagOrient #-}
-- | Suppress pixels that are not local maxima, and use the magnitude to classify maxima
-- into strong and weak (potential) edges.
suppress :: Float -> Float -> Image (Float, Word8) -> IO (Image Word8)
suppress !threshLow !threshHigh !dMagOrient
= computeP
$ makeBordered2
(extent dMagOrient) 1
(makeCursored (extent dMagOrient) id addDim comparePts)
(fromFunction (extent dMagOrient) (const 0))
where {-# INLINE comparePts #-}
comparePts d@(sh :. i :. j)
| o == orientUndef = edge None
| o == orientHoriz = isMax (getMag (sh :. i :. j-1)) (getMag (sh :. i :. j+1))
| o == orientVert = isMax (getMag (sh :. i-1 :. j)) (getMag (sh :. i+1 :. j))
| o == orientNegDiag = isMax (getMag (sh :. i-1 :. j-1)) (getMag (sh :. i+1 :. j+1))
| o == orientPosDiag = isMax (getMag (sh :. i-1 :. j+1)) (getMag (sh :. i+1 :. j-1))
| otherwise = edge None
where
!o = getOrient d
!m = getMag (Z :. i :. j)
getMag = fst . (R.unsafeIndex dMagOrient)
getOrient = snd . (R.unsafeIndex dMagOrient)
{-# INLINE isMax #-}
isMax !intensity1 !intensity2
| m < threshLow = edge None
| m < intensity1 = edge None
| m < intensity2 = edge None
| m < threshHigh = edge Weak
| otherwise = edge Strong
{-# NOINLINE suppress #-}
-- | Select indices of strong edges.
-- TODO: If would better if we could medge this into the above stage, and
-- record the strong edge during non-maximum suppression, but Repa
-- doesn't provide a fused mapFilter primitive yet.
selectStrong :: Image Word8 -> IO (Array U DIM1 Int)
selectStrong img
= let vec = toUnboxed img
match ix = vec `V.unsafeIndex` ix == edge Strong
{-# INLINE match #-}
process' ix = ix
{-# INLINE process' #-}
in selectP match process' (size $ extent img)
{-# NOINLINE selectStrong #-}
-- | Trace out strong edges in the final image.
-- Also trace out weak edges that are connected to strong edges.
wildfire
:: Image Word8 -- ^ Image with strong and weak edges set.
-> Array U DIM1 Int -- ^ Array containing flat indices of strong edges.
-> IO (Image Word8)
wildfire img arrStrong
= do (sh, vec) <- wildfireIO
return $ sh `seq` vec `seq` fromUnboxed sh vec
where lenImg = R.size $ R.extent img
lenStrong = R.size $ R.extent arrStrong
vStrong = toUnboxed arrStrong
wildfireIO
= do -- Stack of image indices we still need to consider.
vStrong' <- V.thaw vStrong
vStack <- VM.grow vStrong' (lenImg - lenStrong)
-- Burn in new edges.
vImg <- VM.unsafeNew lenImg
VM.set vImg 0
burn vImg vStack lenStrong
vImg' <- V.unsafeFreeze vImg
return (extent img, vImg')
burn :: VM.IOVector Word8 -> VM.IOVector Int -> Int -> IO ()
burn !vImg !vStack !top
| top == 0
= return ()
| otherwise
= do let !top' = top - 1
n <- VM.unsafeRead vStack top'
let (Z :. y :. x) = fromIndex (R.extent img) n
let {-# INLINE push #-}
push t = pushWeak vImg vStack t
VM.write vImg n (edge Strong)
>> push (Z :. y - 1 :. x - 1) top'
>>= push (Z :. y - 1 :. x )
>>= push (Z :. y - 1 :. x + 1)
>>= push (Z :. y :. x - 1)
>>= push (Z :. y :. x + 1)
>>= push (Z :. y + 1 :. x - 1)
>>= push (Z :. y + 1 :. x )
>>= push (Z :. y + 1 :. x + 1)
>>= burn vImg vStack
-- If this ix is weak in the source then set it to strong in the
-- result and push the ix onto the stack.
{-# INLINE pushWeak #-}
pushWeak vImg vStack ix top
= do let n = toIndex (extent img) ix
xDst <- VM.unsafeRead vImg n
let xSrc = img `R.unsafeIndex` ix
if xDst == edge None
&& xSrc == edge Weak
then do
VM.unsafeWrite vStack top (toIndex (extent img) ix)
return (top + 1)
else return top
{-# NOINLINE wildfire #-}
|
eklinkhammer/robot-vision
|
src/canny_demo.hs
|
mit
| 12,693 | 0 | 24 | 5,056 | 3,038 | 1,545 | 1,493 | 253 | 9 |
module Graphics.TUIO.Types
( Vec2D
, Vec3D
, Rot2D
, Rot3D
, ClassId
, SessionId
)
where
type Vec2D = (Float, Float)
type Vec3D = (Float, Float, Float)
type Rot2D = Float
type Rot3D = (Float, Float, Float)
type ClassId = Integer
type SessionId = Integer
|
peacememories/tuio-haskell
|
src/Graphics/TUIO/Types.hs
|
mit
| 259 | 0 | 5 | 50 | 87 | 58 | 29 | 13 | 0 |
{-# LANGUAGE Arrows #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module OAuthLogin
(
-- * Queries
create
, findUserQuery
) where
import Control.Arrow (returnA)
import Control.Lens ((^.))
import Data.Profunctor.Product.TH (makeAdaptorAndInstance)
import Data.Text (Text)
import Database.PostgreSQL.Simple (Connection)
import Opaleye (Column, PGText, Query, Table(Table), (.===), (.==), pgInt4, pgStrictText, queryTable, required, restrict, runInsertMany)
import User (UserColumnRead, UserId, UserIdColumn, userId, userIdColumn, userQuery)
data OAuthLogin' a b c = OAuthLogin
{ oalUserId :: a
, oalProviderName :: b
, oalProviderUserId :: c
} deriving (Eq, Show)
type OAuthLoginColumn = OAuthLogin' UserIdColumn (Column PGText) (Column PGText)
$(makeAdaptorAndInstance "pOAuthLogin" ''OAuthLogin')
oAuthLoginsTable :: Table OAuthLoginColumn OAuthLoginColumn
oAuthLoginsTable = Table "oauth_logins"
(pOAuthLogin OAuthLogin { oalUserId = userIdColumn (required "user_id")
, oalProviderName = required "provider_name"
, oalProviderUserId = required "provider_user_id"
})
oAuthLoginQuery :: Query OAuthLoginColumn
oAuthLoginQuery = queryTable oAuthLoginsTable
create :: Connection -> UserId -> Text -> Text -> IO ()
create conn userId' providerName providerUserId = do
_ <- runInsertMany
conn
oAuthLoginsTable
[OAuthLogin (pgInt4 <$> userId') (pgStrictText providerName) (pgStrictText providerUserId)]
return ()
findUserQuery :: Text -> Text -> Query UserColumnRead
findUserQuery providerName providerUserId = proc () -> do
user <- userQuery -< ()
oAuthLogin <- oAuthLoginQuery -< ()
restrict -< oalUserId oAuthLogin .=== user^.userId
restrict -< oalProviderName oAuthLogin .== pgStrictText providerName
restrict -< oalProviderUserId oAuthLogin .== pgStrictText providerUserId
returnA -< user
|
robertjlooby/scotty-story-board
|
app/models/OAuthLogin.hs
|
mit
| 2,266 | 1 | 12 | 600 | 513 | 281 | 232 | 45 | 1 |
{- Copyright (c) 2007 John Goerzen <[email protected]>
Please see the COPYRIGHT file -}
import System.IO
import Control.Concurrent.MVar
import RsyncParser
import RsyncGUI
import System.Environment
import System.Process
import System.Posix.IO
import System.Posix.Signals
import System.Posix.Process
import System.Exit
main = do
args <- getArgs
rsyncbin <- catch (getEnv "RSYNC") (\_ -> return "rsync")
(readfd, writefd) <- createPipe
pid <- forkProcess (childFunc args rsyncbin readfd writefd)
closeFd writefd
hasExited <- newMVar False
readh <- fdToHandle readfd
hSetBuffering readh (BlockBuffering Nothing)
rsyncinput <- hGetContents readh
let rsyncstream = customlines rsyncinput
exitmv <- newMVar Nothing
gui <- initRsyncGUI (exitButton pid hasExited exitmv)
installHandler sigCHLD (Catch (chldHandler gui pid hasExited exitmv)) Nothing
-- Check to see if we died before installing the handler
ps <- getProcessStatus False False pid
case ps of
Nothing -> return ()
Just x -> chldPs gui x hasExited exitmv
runGUI gui rsyncstream exitmv
exitButton pid mv exitmv = withMVar mv $ \hasexited ->
if hasexited
then exitApp exitmv
else do -- Cancel signal handler since we don't want notification to
-- user of exit due to user's own action
installHandler sigCHLD Default Nothing
-- No need to update the MVar here since there won't be
-- anything else to read it. Besides, doing so would cause
-- deadlock anyway.
signalProcess sigKILL pid
exitApp exitmv
childFunc args rsyncbin readfd writefd =
do closeFd readfd
dupTo writefd stdOutput
dupTo writefd stdError
closeFd writefd
executeFile rsyncbin True args Nothing
chldHandler gui pid mv exitmv =
do ps <- getProcessStatus True False pid
case ps of
Just ps -> chldPs gui ps mv exitmv
Nothing -> return ()
chldPs gui ps mv exitmv =
do installHandler sigCHLD Default Nothing
swapMVar mv True
case ps of
Exited ExitSuccess -> return ()
Exited x -> do oobError gui ("rsync exited with unexpected error: " ++ show x)
swapMVar exitmv (Just x) >> return ()
x -> do oobError gui ("rsync exited with unexpected condition: " ++ show x)
swapMVar exitmv (Just (ExitFailure 255)) >> return ()
|
jgoerzen/gtkrsync
|
gtkrsync.hs
|
gpl-2.0
| 2,509 | 0 | 17 | 704 | 647 | 300 | 347 | 56 | 3 |
{-# LANGUAGE ViewPatterns, TemplateHaskell, TypeFamilies, FlexibleInstances, TypeSynonymInstances, MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS -Wall -fno-warn-orphans #-}
-- | The tetrahedron
module AbsTet where
import TIndex
import Tetrahedron.Vertex
import HomogenousTuples
import Tetrahedron.Edge
import Tetrahedron.Triangle
import Data.Tuple.OneTuple
import Simplicial.DeltaSet3
import TupleTH
import Control.Exception
import EitherC
instance HasTIndex TIndex AbsTet where
viewI = flip I AbsTet
(./) = const
data AbsTet = AbsTet
deriving(Eq,Ord,Show)
absTet :: AbsTet
absTet = AbsTet
instance Vertices AbsTet where
type Verts AbsTet = Quadruple Vertex
vertices = const allVertices'
instance Edges AbsTet where
type Eds AbsTet = Sextuple Edge
edges = const allEdges'
instance Triangles AbsTet where
type Tris AbsTet = Quadruple Triangle
triangles = const allTriangles'
instance SatisfiesSimplicialIdentities3 AbsTet
instance Tetrahedra AbsTet where
type Tets AbsTet = OneTuple AbsTet
tetrahedra = OneTuple
instance Link Vertex (ZeroSkeleton AbsTet) (Triple Vertex) where
link v _ = fromList3 (filter4 (/= v) allVertices')
instance Link IVertex (ZeroSkeleton AbsTet) (Triple IVertex) where
link v p = traverseI map3 (flip link p) v
-- | Edges containing a given vertex
instance Star Vertex (OneSkeleton AbsTet) (Triple Edge) where
star = const . edgesContainingVertex
-- | Edges containing a given vertex
instance Star IVertex (OneSkeleton AbsTet) (Triple IEdge) where
star v p = traverseI map3 (flip star p) v
-- | Triangles containing a given edge
instance Star Edge (TwoSkeleton AbsTet) (Pair Triangle) where
star = const . trianglesContainingEdge
instance Star Vertex (TwoSkeleton AbsTet) (Triple Triangle) where
star = const . trianglesContainingVertex
-- | Triangles containing a given vertex
instance Star IVertex (TwoSkeleton AbsTet) (Triple ITriangle) where
star v p = traverseI map3 (flip star p) v
-- | Triangles containing a given edge
instance Star IEdge (TwoSkeleton AbsTet) (Pair ITriangle) where
star e p = traverseI map2 (flip star p) e
-- = 'triangleDualVertex'
instance Link Triangle AbsTet Vertex where
link t _ = triangleDualVertex t
-- = 'itriangleDualVertex'
instance Link ITriangle AbsTet IVertex where
link t _ = iTriangleDualVertex t
-- = 'triangleByDualVertex'
instance Link Vertex AbsTet Triangle where
link v _ = triangleByDualVertex v
-- = 'itriangleByDualVertex'
instance Link IVertex AbsTet ITriangle where
link v _ = iTriangleByDualVertex v
-- | Morphism that embeds the abstract tetrahedron into an arbitrary tetrahedron-like thing
data MapAbsTet tet = MapAbsTet tet
instance (t ~ Tri tet, SatisfiesSimplicialIdentities3 tet) =>
DeltaSetMorphism2 Triangle t (MapAbsTet tet) where
mapVert (MapAbsTet tet) = tetrahedronGetVertexAt tet . toEnum . fromEnum
mapEd (MapAbsTet tet) = tetrahedronGetEdgeAt tet . toEnum . fromEnum
mapTri (MapAbsTet tet) = tetrahedronGetTriangleAt tet . toEnum . fromEnum
instance (SatisfiesSimplicialIdentities3 tet) =>
DeltaSetMorphism3 AbsTet tet (MapAbsTet tet) where
mapTet (MapAbsTet tet) _ = tet
instance SimplicialTet AbsTet where
sTetAscTotal = const . return $ AbsTet
sTetVerts = $unEitherC "AbsTet/sTetVerts" . asc4total . vertices -- could skip check
instance SimplicialTet TIndex where
sTetAscTotal (unAsc4 -> xs) =
let x = $(proj 4 1) xs
in
assert (all3 ((== (getTIndex x)) . getTIndex) ($(dropTuple 4 1) xs)) $
return (getTIndex x)
sTetVerts = $unEitherC "TIndex/sTetVerts" . asc4total . vertices -- could skip check
|
DanielSchuessler/hstri
|
AbsTet.hs
|
gpl-3.0
| 3,756 | 0 | 16 | 728 | 1,005 | 517 | 488 | 76 | 1 |
module Repl() where
import Parser
import TypeInference
import Control.Monad.Trans.Class
import Control.Monad.IO.Class
import Text.PrettyPrint.ANSI.Leijen
readInput env input = do
func <-lift $ parseFunction input
inferFunction env func
repl :: MonadIO m => TypeEnvironment -> [Named TypedExpr] -> InferenceMonad m ()
repl env xs = do
input <- liftIO $ getLine
(env', x) <- readInput env input
liftIO $ print $ pretty x
repl env' (x:xs)
|
bruno-cadorette/Baeta-Compiler
|
src/Repl.hs
|
gpl-3.0
| 461 | 0 | 9 | 89 | 167 | 86 | 81 | 15 | 1 |
module Sound.SC3.Server.Utils
( withSynthOutput
, quickSynth
, module Sound.SC3.Server.State.Monad
, module Sound.SC3.Server.State.Monad.Command
) where
import Sound.SC3.Server.State.Monad
import Sound.SC3.Server.State.Monad.Command
import Sound.SC3.Server.State.Monad.Process ( withSynth )
import Sound.SC3.Server.Process
( OutputHandler (..)
, defaultServerOptions
, defaultRTOptions
)
import System.IO
withSynthOutput :: Maybe FilePath -> Server a -> IO a
withSynthOutput outfile m = case outfile of
Nothing -> defaultSynth noHandler m
Just fp -> withFile fp WriteMode $ \h ->
defaultSynth (fileHandler h) m
where
defaultSynth :: OutputHandler -> Server a -> IO a
defaultSynth = withSynth defaultServerOptions defaultRTOptions
noHandler = OutputHandler (\_ -> return ()) (\_ -> return ())
fileHandler h = OutputHandler p p
where
p s = hPutStrLn h s >> hFlush h
-- | Start the default scsynth server, sending output to "scsynth.out"
quickSynth :: Server a -> IO a
quickSynth = withSynthOutput $ Just "scsynth.out"
|
cdxr/hsc3-server-utils
|
Sound/SC3/Server/Utils.hs
|
gpl-3.0
| 1,089 | 0 | 12 | 209 | 304 | 169 | 135 | 25 | 2 |
module Global where
{ import System.IO.Unsafe;
import Network.BSD;
import Control.Concurrent;
local_hostent :: MVar HostEntry;
local_hostent = unsafePerformIO newEmptyMVar}
|
ckaestne/CIDE
|
CIDE_Language_Haskell/test/WSP/Webserver/Global.hs
|
gpl-3.0
| 185 | 0 | 5 | 30 | 42 | 27 | 15 | 6 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable #-}
{- |
Module : Postmaster.FSM.SessionState
Copyright : (c) 2004-2008 by Peter Simons
License : GPL2
Maintainer : [email protected]
Stability : provisional
Portability : Haskell 2-pre
-}
module Postmaster.FSM.SessionState where
import Postmaster.Base
import Text.ParserCombinators.Parsec.Rfc2821
import Data.Typeable
newtype SmtpSessionState = SSST SessionState
deriving (Typeable)
-- |Local Variable: @SESSIONSTATE :: 'SessionState'@
sessionState :: SmtpdVariable
sessionState = defineLocal "sessionstate"
setSessionState :: SessionState -> Smtpd ()
setSessionState sst = sessionState (`setVar` (SSST sst))
getSessionState :: Smtpd SessionState
getSessionState = sessionState (`getVarDef` (SSST Unknown)) >>= \(SSST sst) -> return sst
|
richardfontana/postmaster
|
Postmaster/FSM/SessionState.hs
|
gpl-3.0
| 869 | 0 | 9 | 163 | 138 | 80 | 58 | 13 | 1 |
--
-- Dummy stub
--
import System.Environment
import System.Exit
-- Business logic
{-!app-name!-}::[FilePath] -> IO ()
{-!app-name!-} args = putStrLn "{-!app-synopsis!-}" >> exitFailure
-- Entry Point
main :: IO ()
main = do
args <- getArgs
{-!app-name!-} args
|
whitebonobo/gensp
|
templates/sublime-haskell/{-!app-name!-}/{-!App-name!-}.hs
|
gpl-3.0
| 279 | 2 | 9 | 56 | 66 | 38 | 28 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, Rank2Types#-}
module Main(main) where
import Control.Applicative ((<$>), (<*))
import Control.Concurrent (threadDelay, forkIO, ThreadId)
import Control.Concurrent.MVar
import Control.Lens.Operators
import Control.Monad (unless, forever)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.State (StateT, runStateT, mapStateT)
import Data.Cache (Cache)
import Data.IORef
import Data.MRUMemo(memoIO)
import Data.Monoid(Monoid(..))
import Data.Store.Db (Db)
import Data.Store.Guid (Guid)
import Data.Store.Transaction (Transaction)
import Data.Vector.Vector2 (Vector2(..))
import Graphics.UI.Bottle.MainLoop(mainLoopWidget)
import Graphics.UI.Bottle.Widget(Widget)
import Lamdu.Config (Config)
import Lamdu.GUI.CodeEdit.Settings (Settings(..))
import Lamdu.GUI.WidgetEnvT (runWidgetEnvT)
import Paths_lamdu (getDataFileName)
import System.Environment (getArgs)
import System.FilePath ((</>))
import qualified Control.Exception as E
import qualified Data.Aeson as Aeson
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Cache as Cache
import qualified Data.Monoid as Monoid
import qualified Data.Store.Db as Db
import qualified Data.Store.Guid as Guid
import qualified Data.Store.IRef as IRef
import qualified Data.Store.Transaction as Transaction
import qualified Graphics.DrawingCombinators as Draw
import qualified Graphics.UI.Bottle.EventMap as EventMap
import qualified Graphics.UI.Bottle.Widget as Widget
import qualified Graphics.UI.Bottle.Widgets.EventMapDoc as EventMapDoc
import qualified Graphics.UI.Bottle.Widgets.FlyNav as FlyNav
import qualified Graphics.UI.Bottle.Widgets.TextEdit as TextEdit
import qualified Graphics.UI.Bottle.Widgets.TextView as TextView
import qualified Graphics.UI.GLFW as GLFW
import qualified Graphics.UI.GLFW.Utils as GLFWUtils
import qualified Lamdu.Config as Config
import qualified Lamdu.Data.DbLayout as DbLayout
import qualified Lamdu.Data.ExampleDB as ExampleDB
import qualified Lamdu.GUI.CodeEdit as CodeEdit
import qualified Lamdu.GUI.CodeEdit.Settings as Settings
import qualified Lamdu.GUI.VersionControl as VersionControlGUI
import qualified Lamdu.GUI.WidgetEnvT as WE
import qualified Lamdu.GUI.WidgetIds as WidgetIds
import qualified Lamdu.VersionControl as VersionControl
import qualified System.Directory as Directory
data ParsedOpts = ParsedOpts
{ poShouldDeleteDB :: Bool
, poMFontPath :: Maybe FilePath
}
parseArgs :: [String] -> Either String ParsedOpts
parseArgs =
go (ParsedOpts False Nothing)
where
go args [] = return args
go (ParsedOpts _ mPath) ("-deletedb" : args) =
go (ParsedOpts True mPath) args
go _ ("-font" : []) = failUsage "-font must be followed by a font name"
go (ParsedOpts delDB mPath) ("-font" : fn : args) =
case mPath of
Nothing -> go (ParsedOpts delDB (Just fn)) args
Just _ -> failUsage "Duplicate -font arguments"
go _ (arg : _) = failUsage $ "Unexpected arg: " ++ show arg
failUsage msg = fail $ unlines [ msg, usage ]
usage = "Usage: lamdu [-deletedb] [-font <filename>]"
main :: IO ()
main = do
args <- getArgs
home <- Directory.getHomeDirectory
let lamduDir = home </> ".lamdu"
opts <- either fail return $ parseArgs args
if poShouldDeleteDB opts
then do
putStrLn "Deleting DB..."
Directory.removeDirectoryRecursive lamduDir
else runEditor lamduDir $ poMFontPath opts
loadConfig :: FilePath -> IO Config
loadConfig configPath = do
eConfig <- Aeson.eitherDecode' <$> LBS.readFile configPath
either (fail . (msg ++)) return eConfig
where
msg = "Failed to parse config file contents at " ++ show configPath ++ ": "
accessDataFile :: FilePath -> (FilePath -> IO a) -> FilePath -> IO a
accessDataFile startDir accessor fileName =
(accessor =<< getDataFileName fileName)
`E.catch` \(E.SomeException _) ->
accessor $ startDir </> fileName
type Version = Int
sampler :: Eq a => IO a -> IO (ThreadId, IO (Version, a))
sampler sample = do
ref <- newMVar . (,) 0 =<< E.evaluate =<< sample
let
updateMVar new =
modifyMVar_ ref $ \(ver, old) -> return $
if old == new
then (ver, old)
else (ver+1, new)
tid <-
forkIO . forever $ do
threadDelay 200000
(updateMVar =<< sample) `E.catch` \E.SomeException {} -> return ()
return (tid, readMVar ref)
runEditor :: FilePath -> Maybe FilePath -> IO ()
runEditor lamduDir mFontPath = do
Directory.createDirectoryIfMissing False lamduDir
-- GLFW changes the directory from start directory, at least on macs.
startDir <- Directory.getCurrentDirectory
-- Load config as early as possible, before we open any windows/etc
(_, getConfig) <- sampler $ accessDataFile startDir loadConfig "config.json"
GLFWUtils.withGLFW $ do
Vector2 displayWidth displayHeight <- GLFWUtils.getVideoModeSize
win <- GLFWUtils.createWindow displayWidth displayHeight "Lamdu"
-- Fonts must be loaded after the GL context is created..
let
getFont path = do
exists <- Directory.doesFileExist path
unless exists . ioError . userError $ path ++ " does not exist!"
Draw.openFont path
font <-
case mFontPath of
Nothing -> accessDataFile startDir getFont "fonts/DejaVuSans.ttf"
Just path -> getFont path
Db.withDb (lamduDir </> "codeedit.db") $ runDb win getConfig font
mainLoopDebugMode ::
GLFW.Window ->
IO (Version, Config) ->
( Config -> Widget.Size ->
( IO (Widget IO)
, Widget IO -> IO (Widget IO)
)
) -> IO a
mainLoopDebugMode win getConfig iteration = do
debugModeRef <- newIORef False
lastVersionNumRef <- newIORef 0
let
getAnimHalfLife = do
isDebugMode <- readIORef debugModeRef
return $ if isDebugMode then 1.0 else 0.05
addDebugMode config widget = do
isDebugMode <- readIORef debugModeRef
let
doc = EventMap.Doc $ "Debug Mode" : if isDebugMode then ["Disable"] else ["Enable"]
set = writeIORef debugModeRef (not isDebugMode)
return $
-- whenApply isDebugMode (Widget.wFrame %~ addAnnotations font) $
Widget.strongerEvents
(Widget.keysEventMap (Config.debugModeKeys config) doc set)
widget
makeDebugModeWidget size = do
(_, config) <- getConfig
let (makeWidget, addHelp) = iteration config size
addHelp =<< addDebugMode config =<< makeWidget
tickHandler = do
(curVersionNum, _) <- getConfig
atomicModifyIORef lastVersionNumRef $ \lastVersionNum ->
(curVersionNum, lastVersionNum /= curVersionNum)
mainLoopWidget win tickHandler makeDebugModeWidget getAnimHalfLife
cacheMakeWidget :: Eq a => (a -> IO (Widget IO)) -> IO (a -> IO (Widget IO))
cacheMakeWidget mkWidget = do
widgetCacheRef <- newIORef =<< memoIO mkWidget
let invalidateCache = writeIORef widgetCacheRef =<< memoIO mkWidget
return $ \x -> do
mkWidgetCached <- readIORef widgetCacheRef
Widget.atEvents (<* invalidateCache) <$>
mkWidgetCached x
makeFlyNav :: IO (Widget IO -> IO (Widget IO))
makeFlyNav = do
flyNavState <- newIORef FlyNav.initState
return $ \widget -> do
fnState <- readIORef flyNavState
return $ FlyNav.make WidgetIds.flyNav fnState (writeIORef flyNavState) widget
makeScaleFactor :: IO (IORef (Vector2 Widget.R), Config -> Widget.EventHandlers IO)
makeScaleFactor = do
factor <- newIORef 1
let
eventMap config = mconcat
[ Widget.keysEventMap (Config.enlargeBaseFontKeys config)
(EventMap.Doc ["View", "Zoom", "Enlarge"]) $
modifyIORef factor (* realToFrac (Config.enlargeFactor config))
, Widget.keysEventMap (Config.shrinkBaseFontKeys config)
(EventMap.Doc ["View", "Zoom", "Shrink"]) $
modifyIORef factor (/ realToFrac (Config.shrinkFactor config))
]
return (factor, eventMap)
helpConfig :: Draw.Font -> Config -> EventMapDoc.Config
helpConfig font config =
EventMapDoc.Config
{ EventMapDoc.configStyle =
TextView.Style
{ TextView._styleColor = Config.helpTextColor config
, TextView._styleFont = font
, TextView._styleFontSize = Config.helpTextSize config
}
, EventMapDoc.configInputDocColor = Config.helpInputDocColor config
, EventMapDoc.configBGColor = Config.helpBGColor config
, EventMapDoc.configOverlayDocKeys = Config.overlayDocKeys config
}
baseStyle :: Config -> Draw.Font -> TextEdit.Style
baseStyle config font = TextEdit.Style
{ TextEdit._sTextViewStyle =
TextView.Style
{ TextView._styleColor = Config.baseColor config
, TextView._styleFont = font
, TextView._styleFontSize = Config.baseTextSize config
}
, TextEdit._sCursorColor = TextEdit.defaultCursorColor
, TextEdit._sCursorWidth = TextEdit.defaultCursorWidth
, TextEdit._sTextCursorId = WidgetIds.textCursorId
, TextEdit._sBackgroundCursorId = WidgetIds.backgroundCursorId
, TextEdit._sBackgroundColor = Config.cursorBGColor config
, TextEdit._sEmptyUnfocusedString = ""
, TextEdit._sEmptyFocusedString = ""
}
runDb :: GLFW.Window -> IO (Version, Config) -> Draw.Font -> Db -> IO a
runDb win getConfig font db = do
ExampleDB.initDB (Guid.augment "ExampleDB") db
(sizeFactorRef, sizeFactorEvents) <- makeScaleFactor
addHelpWithStyle <- EventMapDoc.makeToggledHelpAdder EventMapDoc.HelpNotShown
settingsRef <- newIORef Settings
{ _sInfoMode = Settings.defaultInfoMode
}
cacheRef <- newIORef $ Cache.new 0x10000000
wrapFlyNav <- makeFlyNav
let
makeWidget (config, size) = do
cursor <- dbToIO . Transaction.getP $ DbLayout.cursor DbLayout.revisionProps
sizeFactor <- readIORef sizeFactorRef
globalEventMap <- mkGlobalEventMap config settingsRef
let eventMap = globalEventMap `mappend` sizeFactorEvents config
prevCache <- readIORef cacheRef
(widget, newCache) <-
(`runStateT` prevCache) $
mkWidgetWithFallback config settingsRef (baseStyle config font) dbToIO
(size / sizeFactor, cursor)
writeIORef cacheRef newCache
return . Widget.scale sizeFactor $ Widget.weakerEvents eventMap widget
makeWidgetCached <- cacheMakeWidget makeWidget
mainLoopDebugMode win getConfig $ \config size ->
( wrapFlyNav =<< makeWidgetCached (config, size)
, addHelpWithStyle (helpConfig font config) size
)
where
dbToIO = DbLayout.runDbTransaction db
nextInfoMode :: Settings.InfoMode -> Settings.InfoMode
nextInfoMode Settings.None = Settings.Types
nextInfoMode Settings.Types = Settings.None -- Settings.Examples
nextInfoMode Settings.Examples = Settings.None
mkGlobalEventMap :: Config -> IORef Settings -> IO (Widget.EventHandlers IO)
mkGlobalEventMap config settingsRef = do
settings <- readIORef settingsRef
let
curInfoMode = settings ^. Settings.sInfoMode
next = nextInfoMode curInfoMode
nextDoc = EventMap.Doc ["View", "Subtext", "Show " ++ show next]
return .
Widget.keysEventMap (Config.nextInfoModeKeys config) nextDoc .
modifyIORef settingsRef $ Settings.sInfoMode .~ next
mkWidgetWithFallback ::
Config -> IORef Settings ->
TextEdit.Style ->
(forall a. Transaction DbLayout.DbM a -> IO a) ->
(Widget.Size, Widget.Id) ->
StateT Cache IO (Widget IO)
mkWidgetWithFallback config settingsRef style dbToIO (size, cursor) = do
settings <- lift $ readIORef settingsRef
(isValid, widget) <-
mapStateT dbToIO $ do
candidateWidget <- fromCursor settings cursor
(isValid, widget) <-
if candidateWidget ^. Widget.wIsFocused
then return (True, candidateWidget)
else do
finalWidget <- fromCursor settings rootCursor
lift $ Transaction.setP (DbLayout.cursor DbLayout.revisionProps) rootCursor
return (False, finalWidget)
unless (widget ^. Widget.wIsFocused) $
fail "Root cursor did not match"
return (isValid, widget)
if isValid
then return widget
else do
lift . putStrLn $ "Invalid cursor: " ++ show cursor
widget
& Widget.backgroundColor (Config.layerMax (Config.layers config))
["invalid cursor bg"] (Config.invalidCursorBGColor config)
& return
where
fromCursor settings = makeRootWidget config settings style dbToIO size
rootCursor = WidgetIds.fromGuid rootGuid
rootGuid :: Guid
rootGuid = IRef.guid $ DbLayout.panes DbLayout.codeIRefs
makeRootWidget ::
Config -> Settings -> TextEdit.Style ->
(forall a. Transaction DbLayout.DbM a -> IO a) ->
Widget.Size -> Widget.Id ->
StateT Cache (Transaction DbLayout.DbM) (Widget IO)
makeRootWidget config settings style dbToIO size cursor = do
actions <- lift VersionControl.makeActions
mapStateT (runWidgetEnvT cursor style config) $ do
codeEdit <-
(fmap . Widget.atEvents) (VersionControl.runEvent cursor) .
(mapStateT . WE.mapWidgetEnvT) VersionControl.runAction $
CodeEdit.make env rootGuid
branchGui <- lift $ VersionControlGUI.make id size actions codeEdit
let
quitEventMap =
Widget.keysEventMap (Config.quitKeys config) (EventMap.Doc ["Quit"]) (error "Quit")
return .
Widget.atEvents (dbToIO . (attachCursor =<<)) $
Widget.strongerEvents quitEventMap branchGui
where
env = CodeEdit.Env
{ CodeEdit.codeProps = DbLayout.codeProps
, CodeEdit.totalSize = size
, CodeEdit.settings = settings
}
attachCursor eventResult = do
maybe (return ()) (Transaction.setP (DbLayout.cursor DbLayout.revisionProps)) .
Monoid.getLast $ eventResult ^. Widget.eCursor
return eventResult
|
MatiasNAmendola/lamdu
|
Lamdu/Main.hs
|
gpl-3.0
| 13,520 | 0 | 19 | 2,559 | 3,878 | 2,034 | 1,844 | 308 | 6 |
-- Written by Siddharth Trehan
module Main where
import Round
import System.IO
main = do
contents <- getContents
let round = getround "Rohan Deshpande" contents
print round
getround authors contents = Round qs
where
qs = dropMaybe . questionup (hasbonus . lines $ contents) . map (toquestion (Tag authors) . parsequestion) . questions . lines $ contents
dropMaybe = map isJust . filter (/= Nothing)
where
isJust (Just x) = x
isJust Nothing = error "Cannot take isJust of Nothing"
|
trehansiddharth/mlsciencebowl
|
git/hs/compile.hs
|
gpl-3.0
| 521 | 18 | 18 | 121 | 170 | 89 | 81 | 12 | 2 |
-- UUAGC 0.9.42.1 (Diff.ag)
-- List --------------------------------------------------------
data List = Nil
| Cons (Float) (List)
deriving ( Show)
-- cata
sem_List (Nil) =
(sem_List_Nil)
sem_List (Cons _head _tail) =
(sem_List_Cons _head (sem_List _tail))
sem_List_Nil =
(\ _lhsIavg ->
(let _lhsOlength =
0.0
_lhsOsum =
0
_lhsOres =
Nil
in ( _lhsOlength,_lhsOres,_lhsOsum)))
sem_List_Cons head_ tail_ =
(\ _lhsIavg ->
(let _lhsOlength =
1.0 + _tailIlength
_lhsOsum =
head_ + _tailIsum
_tailOavg =
_lhsIavg
_lhsOres =
Cons (head_ - _lhsIavg) _tailIres
( _tailIlength,_tailIres,_tailIsum) =
tail_ _tailOavg
in ( _lhsOlength,_lhsOres,_lhsOsum)))
-- Root --------------------------------------------------------
data Root = Root (List)
-- cata
sem_Root (Root _list) =
(sem_Root_Root (sem_List _list))
sem_Root_Root list_ =
(let _listOavg =
_listIsum / _listIlength
_lhsOres =
_listIres
( _listIlength,_listIres,_listIsum) =
list_ _listOavg
in ( _lhsOres))
|
haraldsteinlechner/lambdaWolf
|
report/Diff.hs
|
gpl-3.0
| 1,330 | 0 | 14 | 499 | 307 | 171 | 136 | 40 | 1 |
-- import AfterExp
import Occasionally
-- import SuperSampling
main :: IO ()
main = testOccasionallySuperSampling
|
thalerjonathan/phd
|
coding/papers/FrABS/Haskell/prototyping/SamplingTests/Main.hs
|
gpl-3.0
| 116 | 0 | 6 | 17 | 21 | 12 | 9 | 3 | 1 |
{- ============================================================================
| Copyright 2011 Matthew D. Steele <[email protected]> |
| |
| This file is part of Fallback. |
| |
| Fallback 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. |
| |
| Fallback 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 Fallback. If not, see <http://www.gnu.org/licenses/>. |
============================================================================ -}
module Fallback.Scenario.Triggers.IronMine
(compileIronMine)
where
import Control.Applicative ((<$>))
import Control.Monad (when)
import Data.List (intersperse)
import Data.Maybe (listToMaybe)
import qualified Fallback.Data.Grid as Grid
import Fallback.Data.Point
import Fallback.Draw.Base (blitTopleft)
import Fallback.Scenario.Compile
import Fallback.Scenario.Script
import Fallback.Scenario.Triggers.Globals
import Fallback.Scenario.Triggers.Script
import Fallback.State.Area
import Fallback.State.Creature (MonsterTownAI(..))
import Fallback.State.Doodad (Doodad(..), DoodadHeight(LowDood))
import Fallback.State.Resources
import Fallback.State.Simple (FaceDir(..), Ingredient(AquaVitae))
import Fallback.State.Tags
import Fallback.State.Terrain (positionCenter, positionTopleft)
import Fallback.State.Tileset (TileTag(..))
import Fallback.Utility (maybeM)
-------------------------------------------------------------------------------
compileIronMine :: Globals -> CompileScenario ()
compileIronMine globals = compileArea IronMine Nothing $ do
makeExit Marata ["ToMarata"] "FromMarata"
onStartDaily 244106 $ do
addUnlockedDoors globals
uniqueDevice 335736 "Signpost" signRadius $ \_ _ -> do
narrate "Someone has helpfully posted a sign here:\n\n\
\ {b}MINE CLOSED{_}\n\
\ {i}DANGER: UNDEAD!{_}"
uniqueDevice 895064 "SwitchingSign" signRadius $ \_ _ -> do
narrate "The sign tacked to the wall reads:\n\n\
\ {i}SWITCHING STATION{_}"
-- South-southwest chamber:
simpleEnemy_ 984023 "BatA1" CaveBat MindlessAI
simpleEnemy_ 439814 "BatA2" CaveBat MindlessAI
simpleEnemy_ 545801 "BatA3" CaveBat MindlessAI
-- South-southeast chamber:
simpleEnemy_ 892397 "BatB1" CaveBat MindlessAI
simpleEnemy_ 448921 "BatB2" CaveBat MindlessAI
simpleEnemy_ 598787 "BatB3" CaveBat MindlessAI
-- Southeast chamber:
simpleEnemy_ 978497 "GhastC1" Ghast MindlessAI
simpleEnemy_ 579913 "GhastC2" Ghast MindlessAI
simpleEnemy_ 442116 "WightC" Wight MindlessAI
once 807555 (walkIn "Latrine") $ do
narrate "Ulgghh. It appears that the miners used this narrow tunnel as a\
\ latrine, to save themselves the trouble of walking all the way back\
\ outside the mine. The smell of urine and garbage back here is awful."
-- Records office:
uniqueDevice 208934 "RecordsSign" signRadius $ \_ _ -> do
narrate "The sign tacked to the wall reads:\n\n\
\ {i}RECORDS OFFICE{_}"
treasureChest_ 750928 "NorthChest" [PotionItemTag HealingPotion]
[(AquaVitae, 10)] 240
-- Snow chamber:
(iceLizard1Key, iceLizard1Dead) <-
scriptedMonster 987298 "IceLizard1" IceLizard False ImmobileAI
(iceLizard2Key, iceLizard2Dead) <-
scriptedMonster 098458 "IceLizard2" IceLizard False ImmobileAI
once 799563 (walkIn "NearSnow" `andP`
(varFalse iceLizard1Dead `orP` varFalse iceLizard2Dead)) $ do
narrate "Looking upwards, you see that the miners cut a ventilation shaft\
\ in the ceiling of the cave here leading up to the surface above. Snow\
\ has drifted down the shaft from the outside, eventually building up\
\ over a small patch of this chamber.\n\n\
\The air is remarkably fresh and crisp in here. Between the snow and\
\ the cold air, you imagine that this chamber makes a lovely nest for\
\ the two wild ice lizards that have somehow gotten in here. They look\
\ up at you from their nap, evidentally deciding that you will make a\
\ nice meal."
setMonsterTownAI (GuardAI 7 "IceLizard1" FaceRight) =<<
readVar iceLizard1Key
setMonsterTownAI (GuardAI 7 "IceLizard2" FaceLeft) =<<
readVar iceLizard2Key
-- Mine tracks/cart state:
tracksSetToTurn <- newPersistentVar 231202 False
-- The mineCartLocation should always be between 0 and 5 inclusive:
-- 0 means the cart is in its starting position
-- 1 means the cart is at the wall
-- 2 means the cart is near the switching station
-- 3 means the cart is near the mine entrance
-- 4 means the cart is in the rocks room
-- 5 means the cart has asploded the wall and is gone
mineCartLocation <- newPersistentVar 626625 (0 :: Int)
mineCartFilledWithRocks <- newPersistentVar 699149 False
-- Switching station lever:
let setLeverTile turn = do
setTerrain (if turn then LeverRightTile else LeverLeftTile) =<<
lookupTerrainMark "Lever"
uniqueDevice 646620 "Lever" signRadius $ \_ _ -> do
let labelStr turn = if turn then "TURN" else "STRAIGHT"
current <- readVar tracksSetToTurn
change <- forcedChoice
("There is a large iron lever mounted in the floor here. On either\
\ end of the metal base is engraved a label: \"STRAIGHT\" and\
\ \"TURN.\" The lever is currently in the \"" ++ labelStr current ++
"\" position.")
[("Move the lever to the \"" ++ labelStr (not current) ++
"\" position", True), ("Leave it alone.", False)]
when change $ do
playSound SndLever
writeVar tracksSetToTurn (not current)
setLeverTile (not current)
narrate "You hear several loud, metallic {i}clank{_} sounds echo through\
\ the mine, and then silence."
onStartDaily 789534 $ do
setLeverTile =<< readVar tracksSetToTurn
let addCartAtLocation cartDevice cartLoc = do
let mbPos = listToMaybe $ snd $ cartPath False False cartLoc
maybeM mbPos $ \position -> do
cartFull <- readVar mineCartFilledWithRocks
let tile = if cartLoc == 1
then (if cartFull then MineCartFullVertTile
else MineCartEmptyVertTile)
else (if cartFull then MineCartFullHorzTile
else MineCartEmptyHorzTile)
setTerrain tile [position]
addDevice_ cartDevice position
mineCart <- newDevice 293845 1 $ \ge charNum -> conversation $ do
cartLoc <- readVar mineCartLocation
cartFull <- readVar mineCartFilledWithRocks
let fillCart = do
writeVar mineCartFilledWithRocks True
removeDevice (Grid.geKey ge)
addCartAtLocation (Grid.geValue ge) cartLoc
narrate "Oof, these rocks are heavy. It takes several of you\
\ working together to lift them up over the edge of the cart. \
\ But it was well worth all that sweat and effort--{i}now{_} you\
\ have a cart full of rocks! It is very heavy. Fortunately, it\
\ is still relatively easy to push."
let pushCart = do
turn <- readVar tracksSetToTurn
let (newLoc, path) = cartPath cartFull turn cartLoc
removeDevice (Grid.geKey ge)
resetTerrain [rectTopleft $ Grid.geRect ge]
doMineCartChain cartFull path
writeVar mineCartLocation newLoc
addCartAtLocation (Grid.geValue ge) newLoc
if (newLoc /= 5) then playSound SndMineCartStop else do
shakeCamera 20 20
playSound SndBoomBig
center <- demandOneTerrainMark "WallCenter"
forkScript $ doExplosionDoodad FireBoom $
positionCenter center `pSub` Point 0 18
wait 5
resetTerrain =<< lookupTerrainMark "Wall"
convText "You examine the cart. "
convText $ if cartFull then "It is currently full of very heavy boulders."
else "It is currently empty."
convText " Despite its weight, it rolls easily along the tracks; the\
\ axles seem to still be well-oiled. If you were to give it a shove, it\
\ would probably follow the tracks all the way toward wherever they\
\ lead."
convChoice (return ()) "Leave it alone."
do blocked <- isOnTerrainMark "Blocking" =<<
areaGet (arsCharacterPosition charNum)
if blocked then convText " At least, it would if you weren't standing\
\ right in the way."
else convChoice pushCart "Give the cart a shove."
when (cartLoc == 4 && not cartFull) $ do
convText "\n\n\
\You also notice that this chamber is scattered with loose boulders. \
\ They're far too heavy for you to carry very far, but with some\
\ effort you could probably heave some of into the cart, if you wanted\
\ to."
convChoice fillCart "Fill the cart with boulders."
convNode $ return ()
onStartDaily 450713 $ do
cartLoc <- readVar mineCartLocation
addCartAtLocation mineCart cartLoc
when (cartLoc /= 5) $ do
setTerrain AdobeCrackedWallTile =<< lookupTerrainMark "Wall"
foundMineCart <- newPersistentVar 729428 False
once 542400 (walkIn "CartChamber" `andP` varEq mineCartLocation 0) $ do
writeVar foundMineCart True
narrate "Ah ha! There's a mine cart sitting at the end of the tracks in\
\ this chamber. From here, it looks to still be in good condition. \
\ Perhaps it can be of some use to you?"
once 782580 (walkIn "NearWall" `andP` varEq mineCartLocation 1) $ do
narrate "It looks like pushing the cart from where you first found it\
\ brought it here. Unlike some of the other track ends you've seen in\
\ here, there's not a proper buffer stop to stop the cart; instead, the\
\ cart was just stopped by smacking into the wall here.\n\n\
\The wall appears to be in somewhat rough shape (presumably this cart\
\ has run into this wall many times over the years), but the empty cart\
\ isn't really heavy enough to do much serious damage to the wall. \
\ Maybe there's something you could do about that."
once 469883 (walkIn "RockChamber") $ conversation $ convNode $ do
cartIsHere <- (4 ==) <$> readVar mineCartLocation
convText "This chamber must have been the end of an active drift around\
\ the time that the mine was abandoned--there are loose boulders\
\ scattered everywhere, still waiting to be carted off and\
\ processed.\n\n\
\Most of the boulders are too heavy for you to carry very far, but "
if cartIsHere then do
convText "you could probably lift some of them into the cart here."
else do
seenCart <- readVar foundMineCart
if seenCart then convText "if you could get that mine cart you found"
else convText "if you could find a mine cart somewhere and get it"
convText " into this chamber, you could probably load it up with rocks."
-- Central building:
once 629513 (walkIn "PastWall") $ do
narrate "You step inside the central building through the new entrance you\
\ just created. It is dimly lit inside, and the floor is covered in a\
\ thick layer of dust and debris, as if no one has been in here in a\
\ long time...\n\n\
\...no, wait, that's just the dust and debris that came from the section\
\ of wall that you just smashed into tiny bits by ramming a cart full of\
\ boulders into it. So you're not really sure if anyone has been in\
\ here lately or not. But now that you listen, you think you can hear\
\ something coming from the the hallway to the southwest."
uniqueDevice 172051 "OreSign" signRadius $ \_ _ -> do
narrate "The sign tacked to the wall reads:\n\n\
\ {i}ORE PROCESSING{_}\n\
\ {b}<--------{_}\n\n\
\The arrow points down the hallway to the south."
-- Boss chamber:
(strigoiKey, strigoiDead) <-
scriptedMonster 874101 "Strigoi" Strigoi True ImmobileAI
once 791390 (walkIn "BossRoom") $ do
-- TODO conversation and so forth
setMonsterIsAlly False =<< readVar strigoiKey
setTerrain AdobeGateClosedTile =<< lookupTerrainMark "BossGate"
startBossFight "BossRoom"
trigger 620397 (varTrue strigoiDead) $ do
setAreaCleared IronMine True
setTerrain AdobeGateOpenTile =<< lookupTerrainMark "BossGate"
setTerrain AdobeGateOpenTile =<< lookupTerrainMark "ChestGate"
-------------------------------------------------------------------------------
cartPath :: Bool {-^full-} -> Bool {-^turn-} -> Int {-^loc-}
-> (Int, [Position])
cartPath _ _ 0 = (1, [Point 48 4, Point 51 4, Point 51 21, Point 26 21,
Point 26 25])
cartPath _ False 1 = (2, path1to2)
cartPath _ True 1 = (3, [Point 26 25, Point 26 21, Point 45 21, Point 45 23,
Point 49 23, Point 49 36, Point 39 36, Point 39 44,
Point 42 44, Point 42 51, Point 43 51])
cartPath full False 2 = (if full then 5 else 1, reverse path1to2)
cartPath _ True 2 = (3, path2to3)
cartPath _ False 3 = (4, path3to4)
cartPath _ True 3 = (2, reverse path2to3)
cartPath _ False 4 = (3, reverse path3to4)
cartPath _ True 4 = (2, [Point 15 26, Point 7 26, Point 7 30, Point 2 30,
Point 2 20, Point 6 20, Point 6 14, Point 10 14,
Point 10 8, Point 27 8, Point 27 3, Point 34 3,
Point 34 13, Point 35 13, Point 35 24, Point 31 24])
cartPath _ _ loc = (loc, [])
path1to2, path2to3, path3to4 :: [Position]
path1to2 = [Point 26 25, Point 26 13, Point 35 13, Point 35 24, Point 31 24]
path2to3 = [Point 31 24, Point 35 24, Point 35 14, Point 47 14, Point 47 23,
Point 49 23, Point 49 36, Point 39 36, Point 39 44, Point 42 44,
Point 42 51, Point 43 51]
path3to4 = [Point 43 51, Point 42 51, Point 42 44, Point 13 44, Point 13 35,
Point 7 35, Point 7 26, Point 15 26]
-------------------------------------------------------------------------------
doMineCartDoodad :: (FromAreaEffect f) => Bool -> Position -> Position
-> Script f ()
doMineCartDoodad cartFull startPos endPos = do
resources <- areaGet arsResources
let sprite = rsrcSprite resources $
if pointX startPos == pointX endPos
then (if cartFull then MineCartFullVertSprite
else MineCartEmptyVertSprite)
else (if cartFull then MineCartFullHorzSprite
else MineCartEmptyHorzSprite)
let startPt = positionTopleft startPos
endPt = positionTopleft endPos
let limit = 2 * (abs (pointX startPos - pointX endPos) +
abs (pointY startPos - pointY endPos))
let paint count cameraTopleft = do
let Point dx dy = startPt `pSub` endPt
let topleft = endPt `pSub` cameraTopleft `pAdd`
Point (dx * count `div` limit) (dy * count `div` limit)
blitTopleft sprite topleft
addDoodad $ Doodad { doodadCountdown = limit, doodadHeight = LowDood,
doodadPaint = paint }
wait limit
doMineCartChain :: (FromAreaEffect f) => Bool -> [Position] -> Script f ()
doMineCartChain cartFull positions = do
sequence_ $ intersperse (playSound SndMineCartTurn) $
map (uncurry $ doMineCartDoodad cartFull) $ byPairs positions
byPairs :: [a] -> [(a, a)]
byPairs (x1 : x2 : xs) = (x1, x2) : byPairs (x2 : xs)
byPairs _ = []
-------------------------------------------------------------------------------
|
mdsteele/fallback
|
src/Fallback/Scenario/Triggers/IronMine.hs
|
gpl-3.0
| 16,463 | 0 | 25 | 4,427 | 3,101 | 1,530 | 1,571 | -1 | -1 |
module Language.Mulang.Edl (
parseQuery,
parseExpectation,
parseExpectations,
parseExpectations',
Expectation(..)) where
import Codec.Binary.UTF8.String (encode)
import Language.Mulang.Edl.Lexer (evalP)
import qualified Language.Mulang.Edl.Parser as P
import Language.Mulang.Edl.Expectation (Query, Expectation(..))
parseQuery :: String -> Query
parseQuery = wrap P.parseQuery
parseExpectations :: String -> [Expectation]
parseExpectations = zipWith overrideName [0..] . wrap P.parseExpectations
where
overrideName :: Int -> Expectation -> Expectation
overrideName number e@Expectation { name = ""} = e { name = "E" ++ show number }
overrideName _ e = e
parseExpectations' :: String -> Either String [Expectation]
parseExpectations' = evalP P.parseExpectations . encode
parseExpectation :: String -> Expectation
parseExpectation = head . parseExpectations
wrap f = either error id . evalP f . encode
|
mumuki/mulang
|
src/Language/Mulang/Edl.hs
|
gpl-3.0
| 985 | 0 | 11 | 195 | 269 | 154 | 115 | 22 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.EC2.DescribeSpotInstanceRequests
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Describes the Spot Instance requests that belong to your account. Spot
-- Instances are instances that Amazon EC2 launches when the bid price that you
-- specify exceeds the current Spot Price. Amazon EC2 periodically sets the Spot
-- Price based on available Spot Instance capacity and current Spot Instance
-- requests. For more information, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-requests.html Spot Instance Requests> in the /AmazonElastic Compute Cloud User Guide/.
--
-- You can use 'DescribeSpotInstanceRequests' to find a running Spot Instance by
-- examining the response. If the status of the Spot Instance is 'fulfilled', the
-- instance ID appears in the response and contains the identifier of the
-- instance. Alternatively, you can use 'DescribeInstances' with a filter to look
-- for instances where the instance lifecycle is 'spot'.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSpotInstanceRequests.html>
module Network.AWS.EC2.DescribeSpotInstanceRequests
(
-- * Request
DescribeSpotInstanceRequests
-- ** Request constructor
, describeSpotInstanceRequests
-- ** Request lenses
, dsirDryRun
, dsirFilters
, dsirSpotInstanceRequestIds
-- * Response
, DescribeSpotInstanceRequestsResponse
-- ** Response constructor
, describeSpotInstanceRequestsResponse
-- ** Response lenses
, dsirrSpotInstanceRequests
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.EC2.Types
import qualified GHC.Exts
data DescribeSpotInstanceRequests = DescribeSpotInstanceRequests
{ _dsirDryRun :: Maybe Bool
, _dsirFilters :: List "Filter" Filter
, _dsirSpotInstanceRequestIds :: List "SpotInstanceRequestId" Text
} deriving (Eq, Read, Show)
-- | 'DescribeSpotInstanceRequests' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dsirDryRun' @::@ 'Maybe' 'Bool'
--
-- * 'dsirFilters' @::@ ['Filter']
--
-- * 'dsirSpotInstanceRequestIds' @::@ ['Text']
--
describeSpotInstanceRequests :: DescribeSpotInstanceRequests
describeSpotInstanceRequests = DescribeSpotInstanceRequests
{ _dsirDryRun = Nothing
, _dsirSpotInstanceRequestIds = mempty
, _dsirFilters = mempty
}
-- | Checks whether you have the required permissions for the action, without
-- actually making the request, and provides an error response. If you have the
-- required permissions, the error response is 'DryRunOperation'. Otherwise, it is 'UnauthorizedOperation'.
dsirDryRun :: Lens' DescribeSpotInstanceRequests (Maybe Bool)
dsirDryRun = lens _dsirDryRun (\s a -> s { _dsirDryRun = a })
-- | One or more filters.
--
-- 'availability-zone-group' - The Availability Zone group.
--
-- 'create-time' - The time stamp when the Spot Instance request was created.
--
-- 'fault-code' - The fault code related to the request.
--
-- 'fault-message' - The fault message related to the request.
--
-- 'instance-id' - The ID of the instance that fulfilled the request.
--
-- 'launch-group' - The Spot Instance launch group.
--
-- 'launch.block-device-mapping.delete-on-termination' - Indicates whether the
-- Amazon EBS volume is deleted on instance termination.
--
-- 'launch.block-device-mapping.device-name' - The device name for the Amazon
-- EBS volume (for example, '/dev/sdh').
--
-- 'launch.block-device-mapping.snapshot-id' - The ID of the snapshot used for
-- the Amazon EBS volume.
--
-- 'launch.block-device-mapping.volume-size' - The size of the Amazon EBS
-- volume, in GiB.
--
-- 'launch.block-device-mapping.volume-type' - The type of the Amazon EBS
-- volume ('gp2' | 'standard' | 'io1').
--
-- 'launch.group-id' - The security group for the instance.
--
-- 'launch.image-id' - The ID of the AMI.
--
-- 'launch.instance-type' - The type of instance (for example, 'm1.small').
--
-- 'launch.kernel-id' - The kernel ID.
--
-- 'launch.key-name' - The name of the key pair the instance launched with.
--
-- 'launch.monitoring-enabled' - Whether monitoring is enabled for the Spot
-- Instance.
--
-- 'launch.ramdisk-id' - The RAM disk ID.
--
-- 'network-interface.network-interface-id' - The ID of the network interface.
--
-- 'network-interface.device-index' - The index of the device for the network
-- interface attachment on the instance.
--
-- 'network-interface.subnet-id' - The ID of the subnet for the instance.
--
-- 'network-interface.description' - A description of the network interface.
--
-- 'network-interface.private-ip-address' - The primary private IP address of
-- the network interface.
--
-- 'network-interface.delete-on-termination' - Indicates whether the network
-- interface is deleted when the instance is terminated.
--
-- 'network-interface.group-id' - The ID of the security group associated with
-- the network interface.
--
-- 'network-interface.group-name' - The name of the security group associated
-- with the network interface.
--
-- 'network-interface.addresses.primary' - Indicates whether the IP address is
-- the primary private IP address.
--
-- 'product-description' - The product description associated with the instance
-- ('Linux/UNIX' | 'Windows').
--
-- 'spot-instance-request-id' - The Spot Instance request ID.
--
-- 'spot-price' - The maximum hourly price for any Spot Instance launched to
-- fulfill the request.
--
-- 'state' - The state of the Spot Instance request ('open' | 'active' | 'closed' | 'cancelled' | 'failed'). Spot bid status information can help you track your Amazon EC2
-- Spot Instance requests. For more information, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html Spot Bid Status> in the
-- Amazon Elastic Compute Cloud User Guide.
--
-- 'status-code' - The short code describing the most recent evaluation of your
-- Spot Instance request.
--
-- 'status-message' - The message explaining the status of the Spot Instance
-- request.
--
-- 'tag':/key/=/value/ - The key/value combination of a tag assigned to the
-- resource.
--
-- 'tag-key' - The key of a tag assigned to the resource. This filter is
-- independent of the 'tag-value' filter. For example, if you use both the filter
-- "tag-key=Purpose" and the filter "tag-value=X", you get any resources
-- assigned both the tag key Purpose (regardless of what the tag's value is),
-- and the tag value X (regardless of what the tag's key is). If you want to
-- list only resources where Purpose is X, see the 'tag':/key/=/value/ filter.
--
-- 'tag-value' - The value of a tag assigned to the resource. This filter is
-- independent of the 'tag-key' filter.
--
-- 'type' - The type of Spot Instance request ('one-time' | 'persistent').
--
-- 'launched-availability-zone' - The Availability Zone in which the bid is
-- launched.
--
-- 'valid-from' - The start date of the request.
--
-- 'valid-until' - The end date of the request.
--
--
dsirFilters :: Lens' DescribeSpotInstanceRequests [Filter]
dsirFilters = lens _dsirFilters (\s a -> s { _dsirFilters = a }) . _List
-- | One or more Spot Instance request IDs.
dsirSpotInstanceRequestIds :: Lens' DescribeSpotInstanceRequests [Text]
dsirSpotInstanceRequestIds =
lens _dsirSpotInstanceRequestIds
(\s a -> s { _dsirSpotInstanceRequestIds = a })
. _List
newtype DescribeSpotInstanceRequestsResponse = DescribeSpotInstanceRequestsResponse
{ _dsirrSpotInstanceRequests :: List "item" SpotInstanceRequest
} deriving (Eq, Read, Show, Monoid, Semigroup)
-- | 'DescribeSpotInstanceRequestsResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dsirrSpotInstanceRequests' @::@ ['SpotInstanceRequest']
--
describeSpotInstanceRequestsResponse :: DescribeSpotInstanceRequestsResponse
describeSpotInstanceRequestsResponse = DescribeSpotInstanceRequestsResponse
{ _dsirrSpotInstanceRequests = mempty
}
-- | One or more Spot Instance requests.
dsirrSpotInstanceRequests :: Lens' DescribeSpotInstanceRequestsResponse [SpotInstanceRequest]
dsirrSpotInstanceRequests =
lens _dsirrSpotInstanceRequests
(\s a -> s { _dsirrSpotInstanceRequests = a })
. _List
instance ToPath DescribeSpotInstanceRequests where
toPath = const "/"
instance ToQuery DescribeSpotInstanceRequests where
toQuery DescribeSpotInstanceRequests{..} = mconcat
[ "DryRun" =? _dsirDryRun
, "Filter" `toQueryList` _dsirFilters
, "SpotInstanceRequestId" `toQueryList` _dsirSpotInstanceRequestIds
]
instance ToHeaders DescribeSpotInstanceRequests
instance AWSRequest DescribeSpotInstanceRequests where
type Sv DescribeSpotInstanceRequests = EC2
type Rs DescribeSpotInstanceRequests = DescribeSpotInstanceRequestsResponse
request = post "DescribeSpotInstanceRequests"
response = xmlResponse
instance FromXML DescribeSpotInstanceRequestsResponse where
parseXML x = DescribeSpotInstanceRequestsResponse
<$> x .@? "spotInstanceRequestSet" .!@ mempty
|
romanb/amazonka
|
amazonka-ec2/gen/Network/AWS/EC2/DescribeSpotInstanceRequests.hs
|
mpl-2.0
| 10,115 | 0 | 10 | 1,785 | 693 | 467 | 226 | 70 | 1 |
-- | Query and update documents
{-# LANGUAGE OverloadedStrings, RecordWildCards, NamedFieldPuns, TupleSections, FlexibleContexts, FlexibleInstances, UndecidableInstances, MultiParamTypeClasses, GeneralizedNewtypeDeriving, StandaloneDeriving, TypeSynonymInstances, TypeFamilies, CPP, DeriveDataTypeable, ScopedTypeVariables, BangPatterns #-}
module Database.MongoDB.Query (
-- * Monad
Action, access, Failure(..), ErrorCode,
AccessMode(..), GetLastError, master, slaveOk, accessMode,
liftDB,
MongoContext(..), HasMongoContext(..),
-- * Database
Database, allDatabases, useDb, thisDatabase,
-- ** Authentication
Username, Password, auth, authMongoCR, authSCRAMSHA1,
-- * Collection
Collection, allCollections,
-- ** Selection
Selection(..), Selector, whereJS,
Select(select),
-- * Write
-- ** Insert
insert, insert_, insertMany, insertMany_, insertAll, insertAll_,
-- ** Update
save, replace, repsert, upsert, Modifier, modify, updateMany, updateAll,
WriteResult(..), UpdateOption(..), Upserted(..),
-- ** Delete
delete, deleteOne, deleteMany, deleteAll, DeleteOption(..),
-- * Read
-- ** Query
Query(..), QueryOption(NoCursorTimeout, TailableCursor, AwaitData, Partial),
Projector, Limit, Order, BatchSize,
explain, find, findOne, fetch,
findAndModify, findAndModifyOpts, FindAndModifyOpts(..), defFamUpdateOpts,
count, distinct,
-- *** Cursor
Cursor, nextBatch, next, nextN, rest, closeCursor, isCursorClosed,
-- ** Aggregate
Pipeline, AggregateConfig(..), aggregate, aggregateCursor,
-- ** Group
Group(..), GroupKey(..), group,
-- ** MapReduce
MapReduce(..), MapFun, ReduceFun, FinalizeFun, MROut(..), MRMerge(..),
MRResult, mapReduce, runMR, runMR',
-- * Command
Command, runCommand, runCommand1,
eval, retrieveServerData, ServerData(..)
) where
import Prelude hiding (lookup)
import Control.Exception (Exception, throwIO)
import Control.Monad (unless, replicateM, liftM, liftM2)
import Control.Monad.Fail(MonadFail)
import Data.Default.Class (Default(..))
import Data.Int (Int32, Int64)
import Data.Either (lefts, rights)
import Data.List (foldl1')
import Data.Maybe (listToMaybe, catMaybes, isNothing)
import Data.Word (Word32)
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid (mappend)
#endif
import Data.Typeable (Typeable)
import System.Mem.Weak (Weak)
import qualified Control.Concurrent.MVar as MV
#if MIN_VERSION_base(4,6,0)
import Control.Concurrent.MVar.Lifted (MVar,
readMVar)
#else
import Control.Concurrent.MVar.Lifted (MVar, addMVarFinalizer,
readMVar)
#endif
import Control.Applicative ((<$>))
import Control.Exception (catch)
import Control.Monad (when, void)
import Control.Monad.Reader (MonadReader, ReaderT, runReaderT, ask, asks, local)
import Control.Monad.Trans (MonadIO, liftIO)
import Data.Binary.Put (runPut)
import Data.Bson (Document, Field(..), Label, Val, Value(String, Doc, Bool),
Javascript, at, valueAt, lookup, look, genObjectId, (=:),
(=?), (!?), Val(..), ObjectId, Value(..))
import Data.Bson.Binary (putDocument)
import Data.Text (Text)
import qualified Data.Text as T
import Database.MongoDB.Internal.Protocol (Reply(..), QueryOption(..),
ResponseFlag(..), InsertOption(..),
UpdateOption(..), DeleteOption(..),
CursorId, FullCollection, Username,
Password, Pipe, Notice(..),
Request(GetMore, qOptions, qSkip,
qFullCollection, qBatchSize,
qSelector, qProjector),
pwKey, ServerData(..))
import Database.MongoDB.Internal.Util (loop, liftIOE, true1, (<.>))
import qualified Database.MongoDB.Internal.Protocol as P
import qualified Crypto.Nonce as Nonce
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Base64 as B64
import qualified Data.ByteString.Char8 as B
import qualified Data.Either as E
import qualified Crypto.Hash.MD5 as MD5
import qualified Crypto.Hash.SHA1 as SHA1
import qualified Crypto.MAC.HMAC as HMAC
import Data.Bits (xor)
import qualified Data.Map as Map
import Text.Read (readMaybe)
import Data.Maybe (fromMaybe)
-- * Monad
type Action = ReaderT MongoContext
-- ^ A monad on top of m (which must be a MonadIO) that may access the database and may fail with a DB 'Failure'
access :: (MonadIO m) => Pipe -> AccessMode -> Database -> Action m a -> m a
-- ^ Run action against database on server at other end of pipe. Use access mode for any reads and writes.
-- Throw 'Failure' in case of any error.
access mongoPipe mongoAccessMode mongoDatabase action = runReaderT action MongoContext{..}
-- | A connection failure, or a read or write exception like cursor expired or inserting a duplicate key.
-- Note, unexpected data from the server is not a Failure, rather it is a programming error (you should call 'error' in this case) because the client and server are incompatible and requires a programming change.
data Failure =
ConnectionFailure IOError -- ^ TCP connection ('Pipeline') failed. May work if you try again on the same Mongo 'Connection' which will create a new Pipe.
| CursorNotFoundFailure CursorId -- ^ Cursor expired because it wasn't accessed for over 10 minutes, or this cursor came from a different server that the one you are currently connected to (perhaps a fail over happen between servers in a replica set)
| QueryFailure ErrorCode String -- ^ Query failed for some reason as described in the string
| WriteFailure Int ErrorCode String -- ^ Error observed by getLastError after a write, error description is in string, index of failed document is the first argument
| WriteConcernFailure Int String -- ^ Write concern error. It's reported only by insert, update, delete commands. Not by wire protocol.
| DocNotFound Selection -- ^ 'fetch' found no document matching selection
| AggregateFailure String -- ^ 'aggregate' returned an error
| CompoundFailure [Failure] -- ^ When we need to aggregate several failures and report them.
| ProtocolFailure Int String -- ^ The structure of the returned documents doesn't match what we expected
deriving (Show, Eq, Typeable)
instance Exception Failure
type ErrorCode = Int
-- ^ Error code from getLastError or query failure
-- | Type of reads and writes to perform
data AccessMode =
ReadStaleOk -- ^ Read-only action, reading stale data from a slave is OK.
| UnconfirmedWrites -- ^ Read-write action, slave not OK, every write is fire & forget.
| ConfirmWrites GetLastError -- ^ Read-write action, slave not OK, every write is confirmed with getLastError.
deriving Show
type GetLastError = Document
-- ^ Parameters for getLastError command. For example @[\"w\" =: 2]@ tells the server to wait for the write to reach at least two servers in replica set before acknowledging. See <http://www.mongodb.org/display/DOCS/Last+Error+Commands> for more options.
class Result a where
isFailed :: a -> Bool
data WriteResult = WriteResult
{ failed :: Bool
, nMatched :: Int
, nModified :: Maybe Int
, nRemoved :: Int
-- ^ Mongodb server before 2.6 doesn't allow to calculate this value.
-- This field is meaningless if we can't calculate the number of modified documents.
, upserted :: [Upserted]
, writeErrors :: [Failure]
, writeConcernErrors :: [Failure]
} deriving Show
instance Result WriteResult where
isFailed = failed
instance Result (Either a b) where
isFailed (Left _) = True
isFailed _ = False
data Upserted = Upserted
{ upsertedIndex :: Int
, upsertedId :: ObjectId
} deriving Show
master :: AccessMode
-- ^ Same as 'ConfirmWrites' []
master = ConfirmWrites []
slaveOk :: AccessMode
-- ^ Same as 'ReadStaleOk'
slaveOk = ReadStaleOk
accessMode :: (Monad m) => AccessMode -> Action m a -> Action m a
-- ^ Run action with given 'AccessMode'
accessMode mode act = local (\ctx -> ctx {mongoAccessMode = mode}) act
readMode :: AccessMode -> ReadMode
readMode ReadStaleOk = StaleOk
readMode _ = Fresh
writeMode :: AccessMode -> WriteMode
writeMode ReadStaleOk = Confirm []
writeMode UnconfirmedWrites = NoConfirm
writeMode (ConfirmWrites z) = Confirm z
-- | Values needed when executing a db operation
data MongoContext = MongoContext {
mongoPipe :: Pipe, -- ^ operations read/write to this pipelined TCP connection to a MongoDB server
mongoAccessMode :: AccessMode, -- ^ read/write operation will use this access mode
mongoDatabase :: Database } -- ^ operations query/update this database
mongoReadMode :: MongoContext -> ReadMode
mongoReadMode = readMode . mongoAccessMode
mongoWriteMode :: MongoContext -> WriteMode
mongoWriteMode = writeMode . mongoAccessMode
class HasMongoContext env where
mongoContext :: env -> MongoContext
instance HasMongoContext MongoContext where
mongoContext = id
liftDB :: (MonadReader env m, HasMongoContext env, MonadIO m)
=> Action IO a
-> m a
liftDB m = do
env <- ask
liftIO $ runReaderT m (mongoContext env)
-- * Database
type Database = Text
allDatabases :: (MonadIO m) => Action m [Database]
-- ^ List all databases residing on server
allDatabases = (map (at "name") . at "databases") `liftM` useDb "admin" (runCommand1 "listDatabases")
thisDatabase :: (Monad m) => Action m Database
-- ^ Current database in use
thisDatabase = asks mongoDatabase
useDb :: (Monad m) => Database -> Action m a -> Action m a
-- ^ Run action against given database
useDb db act = local (\ctx -> ctx {mongoDatabase = db}) act
-- * Authentication
auth :: MonadIO m => Username -> Password -> Action m Bool
-- ^ Authenticate with the current database (if server is running in secure mode). Return whether authentication was successful or not. Reauthentication is required for every new pipe. SCRAM-SHA-1 will be used for server versions 3.0+, MONGO-CR for lower versions.
auth un pw = do
let serverVersion = liftM (at "version") $ useDb "admin" $ runCommand ["buildinfo" =: (1 :: Int)]
mmv <- liftM (readMaybe . T.unpack . head . T.splitOn ".") $ serverVersion
maybe (return False) performAuth mmv
where
performAuth majorVersion =
case (majorVersion >= (3 :: Int)) of
True -> authSCRAMSHA1 un pw
False -> authMongoCR un pw
authMongoCR :: (MonadIO m) => Username -> Password -> Action m Bool
-- ^ Authenticate with the current database, using the MongoDB-CR authentication mechanism (default in MongoDB server < 3.0)
authMongoCR usr pss = do
n <- at "nonce" `liftM` runCommand ["getnonce" =: (1 :: Int)]
true1 "ok" `liftM` runCommand ["authenticate" =: (1 :: Int), "user" =: usr, "nonce" =: n, "key" =: pwKey n usr pss]
authSCRAMSHA1 :: MonadIO m => Username -> Password -> Action m Bool
-- ^ Authenticate with the current database, using the SCRAM-SHA-1 authentication mechanism (default in MongoDB server >= 3.0)
authSCRAMSHA1 un pw = do
let hmac = HMAC.hmac SHA1.hash 64
nonce <- liftIO (Nonce.withGenerator Nonce.nonce128 >>= return . B64.encode)
let firstBare = B.concat [B.pack $ "n=" ++ (T.unpack un) ++ ",r=", nonce]
let client1 = ["saslStart" =: (1 :: Int), "mechanism" =: ("SCRAM-SHA-1" :: String), "payload" =: (B.unpack . B64.encode $ B.concat [B.pack "n,,", firstBare]), "autoAuthorize" =: (1 :: Int)]
server1 <- runCommand client1
shortcircuit (true1 "ok" server1) $ do
let serverPayload1 = B64.decodeLenient . B.pack . at "payload" $ server1
let serverData1 = parseSCRAM serverPayload1
let iterations = read . B.unpack $ Map.findWithDefault "1" "i" serverData1
let salt = B64.decodeLenient $ Map.findWithDefault "" "s" serverData1
let snonce = Map.findWithDefault "" "r" serverData1
shortcircuit (B.isInfixOf nonce snonce) $ do
let withoutProof = B.concat [B.pack "c=biws,r=", snonce]
let digestS = B.pack $ T.unpack un ++ ":mongo:" ++ T.unpack pw
let digest = B16.encode $ MD5.hash digestS
let saltedPass = scramHI digest salt iterations
let clientKey = hmac saltedPass (B.pack "Client Key")
let storedKey = SHA1.hash clientKey
let authMsg = B.concat [firstBare, B.pack ",", serverPayload1, B.pack ",", withoutProof]
let clientSig = hmac storedKey authMsg
let pval = B64.encode . BS.pack $ BS.zipWith xor clientKey clientSig
let clientFinal = B.concat [withoutProof, B.pack ",p=", pval]
let serverKey = hmac saltedPass (B.pack "Server Key")
let serverSig = B64.encode $ hmac serverKey authMsg
let client2 = ["saslContinue" =: (1 :: Int), "conversationId" =: (at "conversationId" server1 :: Int), "payload" =: (B.unpack $ B64.encode clientFinal)]
server2 <- runCommand client2
shortcircuit (true1 "ok" server2) $ do
let serverPayload2 = B64.decodeLenient . B.pack $ at "payload" server2
let serverData2 = parseSCRAM serverPayload2
let serverSigComp = Map.findWithDefault "" "v" serverData2
shortcircuit (serverSig == serverSigComp) $ do
let done = true1 "done" server2
if done
then return True
else do
let client2Step2 = [ "saslContinue" =: (1 :: Int)
, "conversationId" =: (at "conversationId" server1 :: Int)
, "payload" =: String ""]
server3 <- runCommand client2Step2
shortcircuit (true1 "ok" server3) $ do
return True
where
shortcircuit True f = f
shortcircuit False _ = return False
scramHI :: B.ByteString -> B.ByteString -> Int -> B.ByteString
scramHI digest salt iters = snd $ foldl com (u1, u1) [1..(iters-1)]
where
hmacd = HMAC.hmac SHA1.hash 64 digest
u1 = hmacd (B.concat [salt, BS.pack [0, 0, 0, 1]])
com (u,uc) _ = let u' = hmacd u in (u', BS.pack $ BS.zipWith xor uc u')
parseSCRAM :: B.ByteString -> Map.Map B.ByteString B.ByteString
parseSCRAM = Map.fromList . fmap cleanup . (fmap $ T.breakOn "=") . T.splitOn "," . T.pack . B.unpack
where cleanup (t1, t2) = (B.pack $ T.unpack t1, B.pack . T.unpack $ T.drop 1 t2)
retrieveServerData :: (MonadIO m) => Action m ServerData
retrieveServerData = do
d <- runCommand1 "isMaster"
let newSd = ServerData
{ isMaster = (fromMaybe False $ lookup "ismaster" d)
, minWireVersion = (fromMaybe 0 $ lookup "minWireVersion" d)
, maxWireVersion = (fromMaybe 0 $ lookup "maxWireVersion" d)
, maxMessageSizeBytes = (fromMaybe 48000000 $ lookup "maxMessageSizeBytes" d)
, maxBsonObjectSize = (fromMaybe (16 * 1024 * 1024) $ lookup "maxBsonObjectSize" d)
, maxWriteBatchSize = (fromMaybe 1000 $ lookup "maxWriteBatchSize" d)
}
return newSd
-- * Collection
type Collection = Text
-- ^ Collection name (not prefixed with database)
allCollections :: MonadIO m => Action m [Collection]
-- ^ List all collections in this database
allCollections = do
p <- asks mongoPipe
let sd = P.serverData p
if (maxWireVersion sd <= 2)
then do
db <- thisDatabase
docs <- rest =<< find (query [] "system.namespaces") {sort = ["name" =: (1 :: Int)]}
return . filter (not . isSpecial db) . map dropDbPrefix $ map (at "name") docs
else do
r <- runCommand1 "listCollections"
let curData = do
(Doc curDoc) <- r !? "cursor"
(curId :: Int64) <- curDoc !? "id"
(curNs :: Text) <- curDoc !? "ns"
(firstBatch :: [Value]) <- curDoc !? "firstBatch"
return $ (curId, curNs, ((catMaybes (map cast' firstBatch)) :: [Document]))
case curData of
Nothing -> return []
Just (curId, curNs, firstBatch) -> do
db <- thisDatabase
nc <- newCursor db curNs 0 $ return $ Batch Nothing curId firstBatch
docs <- rest nc
return $ catMaybes $ map (\d -> (d !? "name")) docs
where
dropDbPrefix = T.tail . T.dropWhile (/= '.')
isSpecial db col = T.any (== '$') col && db <.> col /= "local.oplog.$main"
-- * Selection
data Selection = Select {selector :: Selector, coll :: Collection} deriving (Show, Eq)
-- ^ Selects documents in collection that match selector
type Selector = Document
-- ^ Filter for a query, analogous to the where clause in SQL. @[]@ matches all documents in collection. @[\"x\" =: a, \"y\" =: b]@ is analogous to @where x = a and y = b@ in SQL. See <http://www.mongodb.org/display/DOCS/Querying> for full selector syntax.
whereJS :: Selector -> Javascript -> Selector
-- ^ Add Javascript predicate to selector, in which case a document must match both selector and predicate
whereJS sel js = ("$where" =: js) : sel
class Select aQueryOrSelection where
select :: Selector -> Collection -> aQueryOrSelection
-- ^ 'Query' or 'Selection' that selects documents in collection that match selector. The choice of type depends on use, for example, in @'find' (select sel col)@ it is a Query, and in @'delete' (select sel col)@ it is a Selection.
instance Select Selection where
select = Select
instance Select Query where
select = query
-- * Write
data WriteMode =
NoConfirm -- ^ Submit writes without receiving acknowledgments. Fast. Assumes writes succeed even though they may not.
| Confirm GetLastError -- ^ Receive an acknowledgment after every write, and raise exception if one says the write failed. This is acomplished by sending the getLastError command, with given 'GetLastError' parameters, after every write.
deriving (Show, Eq)
write :: Notice -> Action IO (Maybe Document)
-- ^ Send write to server, and if write-mode is 'Safe' then include getLastError request and raise 'WriteFailure' if it reports an error.
write notice = asks mongoWriteMode >>= \mode -> case mode of
NoConfirm -> do
pipe <- asks mongoPipe
liftIOE ConnectionFailure $ P.send pipe [notice]
return Nothing
Confirm params -> do
let q = query (("getlasterror" =: (1 :: Int)) : params) "$cmd"
pipe <- asks mongoPipe
Batch _ _ [doc] <- do
r <- queryRequest False q {limit = 1}
rr <- liftIO $ request pipe [notice] r
fulfill rr
return $ Just doc
-- ** Insert
insert :: (MonadIO m) => Collection -> Document -> Action m Value
-- ^ Insert document into collection and return its \"_id\" value, which is created automatically if not supplied
insert col doc = do
doc' <- liftIO $ assignId doc
res <- insertBlock [] col (0, [doc'])
case res of
Left failure -> liftIO $ throwIO failure
Right r -> return $ head r
insert_ :: (MonadIO m) => Collection -> Document -> Action m ()
-- ^ Same as 'insert' except don't return _id
insert_ col doc = insert col doc >> return ()
insertMany :: (MonadIO m) => Collection -> [Document] -> Action m [Value]
-- ^ Insert documents into collection and return their \"_id\" values,
-- which are created automatically if not supplied.
-- If a document fails to be inserted (eg. due to duplicate key)
-- then remaining docs are aborted, and LastError is set.
-- An exception will be throw if any error occurs.
insertMany = insert' []
insertMany_ :: (MonadIO m) => Collection -> [Document] -> Action m ()
-- ^ Same as 'insertMany' except don't return _ids
insertMany_ col docs = insertMany col docs >> return ()
insertAll :: (MonadIO m) => Collection -> [Document] -> Action m [Value]
-- ^ Insert documents into collection and return their \"_id\" values,
-- which are created automatically if not supplied. If a document fails
-- to be inserted (eg. due to duplicate key) then remaining docs
-- are still inserted.
insertAll = insert' [KeepGoing]
insertAll_ :: (MonadIO m) => Collection -> [Document] -> Action m ()
-- ^ Same as 'insertAll' except don't return _ids
insertAll_ col docs = insertAll col docs >> return ()
insertCommandDocument :: [InsertOption] -> Collection -> [Document] -> Document -> Document
insertCommandDocument opts col docs writeConcern =
[ "insert" =: col
, "ordered" =: (KeepGoing `notElem` opts)
, "documents" =: docs
, "writeConcern" =: writeConcern
]
takeRightsUpToLeft :: [Either a b] -> [b]
takeRightsUpToLeft l = E.rights $ takeWhile E.isRight l
insert' :: (MonadIO m)
=> [InsertOption] -> Collection -> [Document] -> Action m [Value]
-- ^ Insert documents into collection and return their \"_id\" values, which are created automatically if not supplied
insert' opts col docs = do
p <- asks mongoPipe
let sd = P.serverData p
docs' <- liftIO $ mapM assignId docs
mode <- asks mongoWriteMode
let writeConcern = case mode of
NoConfirm -> ["w" =: (0 :: Int)]
Confirm params -> params
let docSize = sizeOfDocument $ insertCommandDocument opts col [] writeConcern
let ordered = (not (KeepGoing `elem` opts))
let preChunks = splitAtLimit
(maxBsonObjectSize sd - docSize)
-- size of auxiliary part of insert
-- document should be subtracted from
-- the overall size
(maxWriteBatchSize sd)
docs'
let chunks =
if ordered
then takeRightsUpToLeft preChunks
else rights preChunks
let lens = map length chunks
let lSums = 0 : (zipWith (+) lSums lens)
chunkResults <- interruptibleFor ordered (zip lSums chunks) $ insertBlock opts col
let lchunks = lefts preChunks
when (not $ null lchunks) $ do
liftIO $ throwIO $ head lchunks
let lresults = lefts chunkResults
when (not $ null lresults) $ liftIO $ throwIO $ head lresults
return $ concat $ rights chunkResults
insertBlock :: (MonadIO m)
=> [InsertOption] -> Collection -> (Int, [Document]) -> Action m (Either Failure [Value])
-- ^ This will fail if the list of documents is bigger than restrictions
insertBlock _ _ (_, []) = return $ Right []
insertBlock opts col (prevCount, docs) = do
db <- thisDatabase
p <- asks mongoPipe
let sd = P.serverData p
if (maxWireVersion sd < 2)
then do
res <- liftDB $ write (Insert (db <.> col) opts docs)
let errorMessage = do
jRes <- res
em <- lookup "err" jRes
return $ WriteFailure prevCount (maybe 0 id $ lookup "code" jRes) em
-- In older versions of ^^ the protocol we can't really say which document failed.
-- So we just report the accumulated number of documents in the previous blocks.
case errorMessage of
Just failure -> return $ Left failure
Nothing -> return $ Right $ map (valueAt "_id") docs
else do
mode <- asks mongoWriteMode
let writeConcern = case mode of
NoConfirm -> ["w" =: (0 :: Int)]
Confirm params -> params
doc <- runCommand $ insertCommandDocument opts col docs writeConcern
case (look "writeErrors" doc, look "writeConcernError" doc) of
(Nothing, Nothing) -> return $ Right $ map (valueAt "_id") docs
(Just (Array errs), Nothing) -> do
let writeErrors = map (anyToWriteError prevCount) $ errs
let errorsWithFailureIndex = map (addFailureIndex prevCount) writeErrors
return $ Left $ CompoundFailure errorsWithFailureIndex
(Nothing, Just err) -> do
return $ Left $ WriteFailure
prevCount
(maybe 0 id $ lookup "ok" doc)
(show err)
(Just (Array errs), Just writeConcernErr) -> do
let writeErrors = map (anyToWriteError prevCount) $ errs
let errorsWithFailureIndex = map (addFailureIndex prevCount) writeErrors
return $ Left $ CompoundFailure $ (WriteFailure
prevCount
(maybe 0 id $ lookup "ok" doc)
(show writeConcernErr)) : errorsWithFailureIndex
(Just unknownValue, Nothing) -> do
return $ Left $ ProtocolFailure prevCount $ "Expected array of errors. Received: " ++ show unknownValue
(Just unknownValue, Just writeConcernErr) -> do
return $ Left $ CompoundFailure $ [ ProtocolFailure prevCount $ "Expected array of errors. Received: " ++ show unknownValue
, WriteFailure prevCount (maybe 0 id $ lookup "ok" doc) $ show writeConcernErr]
splitAtLimit :: Int -> Int -> [Document] -> [Either Failure [Document]]
splitAtLimit maxSize maxCount list = chop (go 0 0 []) list
where
go :: Int -> Int -> [Document] -> [Document] -> ((Either Failure [Document]), [Document])
go _ _ res [] = (Right $ reverse res, [])
go curSize curCount [] (x:xs) |
((curSize + (sizeOfDocument x) + 2 + curCount) > maxSize) =
(Left $ WriteFailure 0 0 "One document is too big for the message", xs)
go curSize curCount res (x:xs) =
if ( ((curSize + (sizeOfDocument x) + 2 + curCount) > maxSize)
-- we have ^ 2 brackets and curCount commas in
-- the document that we need to take into
-- account
|| ((curCount + 1) > maxCount))
then
(Right $ reverse res, x:xs)
else
go (curSize + (sizeOfDocument x)) (curCount + 1) (x:res) xs
chop :: ([a] -> (b, [a])) -> [a] -> [b]
chop _ [] = []
chop f as = let (b, as') = f as in b : chop f as'
sizeOfDocument :: Document -> Int
sizeOfDocument d = fromIntegral $ LBS.length $ runPut $ putDocument d
assignId :: Document -> IO Document
-- ^ Assign a unique value to _id field if missing
assignId doc = if any (("_id" ==) . label) doc
then return doc
else (\oid -> ("_id" =: oid) : doc) `liftM` genObjectId
-- ** Update
save :: (MonadIO m)
=> Collection -> Document -> Action m ()
-- ^ Save document to collection, meaning insert it if its new (has no \"_id\" field) or upsert it if its not new (has \"_id\" field)
save col doc = case look "_id" doc of
Nothing -> insert_ col doc
Just i -> upsert (Select ["_id" := i] col) doc
replace :: (MonadIO m)
=> Selection -> Document -> Action m ()
-- ^ Replace first document in selection with given document
replace = update []
repsert :: (MonadIO m)
=> Selection -> Document -> Action m ()
-- ^ Replace first document in selection with given document, or insert document if selection is empty
repsert = update [Upsert]
{-# DEPRECATED repsert "use upsert instead" #-}
upsert :: (MonadIO m)
=> Selection -> Document -> Action m ()
-- ^ Update first document in selection with given document, or insert document if selection is empty
upsert = update [Upsert]
type Modifier = Document
-- ^ Update operations on fields in a document. See <https://docs.mongodb.com/manual/reference/operator/update/>
modify :: (MonadIO m)
=> Selection -> Modifier -> Action m ()
-- ^ Update all documents in selection using given modifier
modify = update [MultiUpdate]
update :: (MonadIO m)
=> [UpdateOption] -> Selection -> Document -> Action m ()
-- ^ Update first document in selection using updater document, unless 'MultiUpdate' option is supplied then update all documents in selection. If 'Upsert' option is supplied then treat updater as document and insert it if selection is empty.
update opts (Select sel col) up = do
db <- thisDatabase
ctx <- ask
liftIO $ runReaderT (void $ write (Update (db <.> col) opts sel up)) ctx
updateCommandDocument :: Collection -> Bool -> [Document] -> Document -> Document
updateCommandDocument col ordered updates writeConcern =
[ "update" =: col
, "ordered" =: ordered
, "updates" =: updates
, "writeConcern" =: writeConcern
]
{-| Bulk update operation. If one update fails it will not update the remaining
- documents. Current returned value is only a place holder. With mongodb server
- before 2.6 it will send update requests one by one. In order to receive
- error messages in versions under 2.6 you need to user confirmed writes.
- Otherwise even if the errors had place the list of errors will be empty and
- the result will be success. After 2.6 it will use bulk update feature in
- mongodb.
-}
updateMany :: (MonadIO m)
=> Collection
-> [(Selector, Document, [UpdateOption])]
-> Action m WriteResult
updateMany = update' True
{-| Bulk update operation. If one update fails it will proceed with the
- remaining documents. With mongodb server before 2.6 it will send update
- requests one by one. In order to receive error messages in versions under
- 2.6 you need to use confirmed writes. Otherwise even if the errors had
- place the list of errors will be empty and the result will be success.
- After 2.6 it will use bulk update feature in mongodb.
-}
updateAll :: (MonadIO m)
=> Collection
-> [(Selector, Document, [UpdateOption])]
-> Action m WriteResult
updateAll = update' False
update' :: (MonadIO m)
=> Bool
-> Collection
-> [(Selector, Document, [UpdateOption])]
-> Action m WriteResult
update' ordered col updateDocs = do
p <- asks mongoPipe
let sd = P.serverData p
let updates = map (\(s, d, os) -> [ "q" =: s
, "u" =: d
, "upsert" =: (Upsert `elem` os)
, "multi" =: (MultiUpdate `elem` os)])
updateDocs
mode <- asks mongoWriteMode
ctx <- ask
liftIO $ do
let writeConcern = case mode of
NoConfirm -> ["w" =: (0 :: Int)]
Confirm params -> params
let docSize = sizeOfDocument $ updateCommandDocument
col
ordered
[]
writeConcern
let preChunks = splitAtLimit
(maxBsonObjectSize sd - docSize)
-- size of auxiliary part of update
-- document should be subtracted from
-- the overall size
(maxWriteBatchSize sd)
updates
let chunks =
if ordered
then takeRightsUpToLeft preChunks
else rights preChunks
let lens = map length chunks
let lSums = 0 : (zipWith (+) lSums lens)
blocks <- interruptibleFor ordered (zip lSums chunks) $ \b -> do
ur <- runReaderT (updateBlock ordered col b) ctx
return ur
`catch` \(e :: Failure) -> do
return $ WriteResult True 0 Nothing 0 [] [e] []
let failedTotal = or $ map failed blocks
let updatedTotal = sum $ map nMatched blocks
let modifiedTotal =
if all isNothing $ map nModified blocks
then Nothing
else Just $ sum $ catMaybes $ map nModified blocks
let totalWriteErrors = concat $ map writeErrors blocks
let totalWriteConcernErrors = concat $ map writeConcernErrors blocks
let upsertedTotal = concat $ map upserted blocks
return $ WriteResult
failedTotal
updatedTotal
modifiedTotal
0 -- nRemoved
upsertedTotal
totalWriteErrors
totalWriteConcernErrors
`catch` \(e :: Failure) -> return $ WriteResult True 0 Nothing 0 [] [e] []
updateBlock :: (MonadIO m)
=> Bool -> Collection -> (Int, [Document]) -> Action m WriteResult
updateBlock ordered col (prevCount, docs) = do
p <- asks mongoPipe
let sd = P.serverData p
if (maxWireVersion sd < 2)
then liftIO $ ioError $ userError "updateMany doesn't support mongodb older than 2.6"
else do
mode <- asks mongoWriteMode
let writeConcern = case mode of
NoConfirm -> ["w" =: (0 :: Int)]
Confirm params -> params
doc <- runCommand $ updateCommandDocument col ordered docs writeConcern
let n = fromMaybe 0 $ doc !? "n"
let writeErrorsResults =
case look "writeErrors" doc of
Nothing -> WriteResult False 0 (Just 0) 0 [] [] []
Just (Array err) -> WriteResult True 0 (Just 0) 0 [] (map (anyToWriteError prevCount) err) []
Just unknownErr -> WriteResult
True
0
(Just 0)
0
[]
[ ProtocolFailure
prevCount
$ "Expected array of error docs, but received: "
++ (show unknownErr)]
[]
let writeConcernResults =
case look "writeConcernError" doc of
Nothing -> WriteResult False 0 (Just 0) 0 [] [] []
Just (Doc err) -> WriteResult
True
0
(Just 0)
0
[]
[]
[ WriteConcernFailure
(fromMaybe (-1) $ err !? "code")
(fromMaybe "" $ err !? "errmsg")
]
Just unknownErr -> WriteResult
True
0
(Just 0)
0
[]
[]
[ ProtocolFailure
prevCount
$ "Expected doc in writeConcernError, but received: "
++ (show unknownErr)]
let upsertedList = map docToUpserted $ fromMaybe [] (doc !? "upserted")
let successResults = WriteResult False n (doc !? "nModified") 0 upsertedList [] []
return $ foldl1' mergeWriteResults [writeErrorsResults, writeConcernResults, successResults]
interruptibleFor :: (Monad m, Result b) => Bool -> [a] -> (a -> m b) -> m [b]
interruptibleFor ordered = go []
where
go !res [] _ = return $ reverse res
go !res (x:xs) f = do
y <- f x
if isFailed y && ordered
then return $ reverse (y:res)
else go (y:res) xs f
mergeWriteResults :: WriteResult -> WriteResult -> WriteResult
mergeWriteResults
(WriteResult failed1 nMatched1 nModified1 nDeleted1 upserted1 writeErrors1 writeConcernErrors1)
(WriteResult failed2 nMatched2 nModified2 nDeleted2 upserted2 writeErrors2 writeConcernErrors2) =
(WriteResult
(failed1 || failed2)
(nMatched1 + nMatched2)
((liftM2 (+)) nModified1 nModified2)
(nDeleted1 + nDeleted2)
-- This function is used in foldl1' function. The first argument is the accumulator.
-- The list in the accumulator is usually longer than the subsequent value which goes in the second argument.
-- So, changing the order of list concatenation allows us to keep linear complexity of the
-- whole list accumulation process.
(upserted2 ++ upserted1)
(writeErrors2 ++ writeErrors1)
(writeConcernErrors2 ++ writeConcernErrors1)
)
docToUpserted :: Document -> Upserted
docToUpserted doc = Upserted ind uid
where
ind = at "index" doc
uid = at "_id" doc
docToWriteError :: Document -> Failure
docToWriteError doc = WriteFailure ind code msg
where
ind = at "index" doc
code = at "code" doc
msg = at "errmsg" doc
-- ** Delete
delete :: (MonadIO m)
=> Selection -> Action m ()
-- ^ Delete all documents in selection
delete = deleteHelper []
deleteOne :: (MonadIO m)
=> Selection -> Action m ()
-- ^ Delete first document in selection
deleteOne = deleteHelper [SingleRemove]
deleteHelper :: (MonadIO m)
=> [DeleteOption] -> Selection -> Action m ()
deleteHelper opts (Select sel col) = do
db <- thisDatabase
ctx <- ask
liftIO $ runReaderT (void $ write (Delete (db <.> col) opts sel)) ctx
{-| Bulk delete operation. If one delete fails it will not delete the remaining
- documents. Current returned value is only a place holder. With mongodb server
- before 2.6 it will send delete requests one by one. After 2.6 it will use
- bulk delete feature in mongodb.
-}
deleteMany :: (MonadIO m)
=> Collection
-> [(Selector, [DeleteOption])]
-> Action m WriteResult
deleteMany = delete' True
{-| Bulk delete operation. If one delete fails it will proceed with the
- remaining documents. Current returned value is only a place holder. With
- mongodb server before 2.6 it will send delete requests one by one. After 2.6
- it will use bulk delete feature in mongodb.
-}
deleteAll :: (MonadIO m)
=> Collection
-> [(Selector, [DeleteOption])]
-> Action m WriteResult
deleteAll = delete' False
deleteCommandDocument :: Collection -> Bool -> [Document] -> Document -> Document
deleteCommandDocument col ordered deletes writeConcern =
[ "delete" =: col
, "ordered" =: ordered
, "deletes" =: deletes
, "writeConcern" =: writeConcern
]
delete' :: (MonadIO m)
=> Bool
-> Collection
-> [(Selector, [DeleteOption])]
-> Action m WriteResult
delete' ordered col deleteDocs = do
p <- asks mongoPipe
let sd = P.serverData p
let deletes = map (\(s, os) -> [ "q" =: s
, "limit" =: if SingleRemove `elem` os
then (1 :: Int) -- Remove only one matching
else (0 :: Int) -- Remove all matching
])
deleteDocs
mode <- asks mongoWriteMode
let writeConcern = case mode of
NoConfirm -> ["w" =: (0 :: Int)]
Confirm params -> params
let docSize = sizeOfDocument $ deleteCommandDocument col ordered [] writeConcern
let preChunks = splitAtLimit
(maxBsonObjectSize sd - docSize)
-- size of auxiliary part of delete
-- document should be subtracted from
-- the overall size
(maxWriteBatchSize sd)
deletes
let chunks =
if ordered
then takeRightsUpToLeft preChunks
else rights preChunks
ctx <- ask
let lens = map length chunks
let lSums = 0 : (zipWith (+) lSums lens)
blockResult <- liftIO $ interruptibleFor ordered (zip lSums chunks) $ \b -> do
dr <- runReaderT (deleteBlock ordered col b) ctx
return dr
`catch` \(e :: Failure) -> do
return $ WriteResult True 0 Nothing 0 [] [e] []
return $ foldl1' mergeWriteResults blockResult
addFailureIndex :: Int -> Failure -> Failure
addFailureIndex i (WriteFailure ind code s) = WriteFailure (ind + i) code s
addFailureIndex _ f = f
deleteBlock :: (MonadIO m)
=> Bool -> Collection -> (Int, [Document]) -> Action m WriteResult
deleteBlock ordered col (prevCount, docs) = do
p <- asks mongoPipe
let sd = P.serverData p
if (maxWireVersion sd < 2)
then liftIO $ ioError $ userError "deleteMany doesn't support mongodb older than 2.6"
else do
mode <- asks mongoWriteMode
let writeConcern = case mode of
NoConfirm -> ["w" =: (0 :: Int)]
Confirm params -> params
doc <- runCommand $ deleteCommandDocument col ordered docs writeConcern
let n = fromMaybe 0 $ doc !? "n"
let successResults = WriteResult False 0 Nothing n [] [] []
let writeErrorsResults =
case look "writeErrors" doc of
Nothing -> WriteResult False 0 Nothing 0 [] [] []
Just (Array err) -> WriteResult True 0 Nothing 0 [] (map (anyToWriteError prevCount) err) []
Just unknownErr -> WriteResult
True
0
Nothing
0
[]
[ ProtocolFailure
prevCount
$ "Expected array of error docs, but received: "
++ (show unknownErr)]
[]
let writeConcernResults =
case look "writeConcernError" doc of
Nothing -> WriteResult False 0 Nothing 0 [] [] []
Just (Doc err) -> WriteResult
True
0
Nothing
0
[]
[]
[ WriteConcernFailure
(fromMaybe (-1) $ err !? "code")
(fromMaybe "" $ err !? "errmsg")
]
Just unknownErr -> WriteResult
True
0
Nothing
0
[]
[]
[ ProtocolFailure
prevCount
$ "Expected doc in writeConcernError, but received: "
++ (show unknownErr)]
return $ foldl1' mergeWriteResults [successResults, writeErrorsResults, writeConcernResults]
anyToWriteError :: Int -> Value -> Failure
anyToWriteError _ (Doc d) = docToWriteError d
anyToWriteError ind _ = ProtocolFailure ind "Unknown bson value"
-- * Read
data ReadMode =
Fresh -- ^ read from master only
| StaleOk -- ^ read from slave ok
deriving (Show, Eq)
readModeOption :: ReadMode -> [QueryOption]
readModeOption Fresh = []
readModeOption StaleOk = [SlaveOK]
-- ** Query
-- | Use 'select' to create a basic query with defaults, then modify if desired. For example, @(select sel col) {limit = 10}@
data Query = Query {
options :: [QueryOption], -- ^ Default = []
selection :: Selection,
project :: Projector, -- ^ \[\] = all fields. Default = []
skip :: Word32, -- ^ Number of initial matching documents to skip. Default = 0
limit :: Limit, -- ^ Maximum number of documents to return, 0 = no limit. Default = 0
sort :: Order, -- ^ Sort results by this order, [] = no sort. Default = []
snapshot :: Bool, -- ^ If true assures no duplicates are returned, or objects missed, which were present at both the start and end of the query's execution (even if the object were updated). If an object is new during the query, or deleted during the query, it may or may not be returned, even with snapshot mode. Note that short query responses (less than 1MB) are always effectively snapshotted. Default = False
batchSize :: BatchSize, -- ^ The number of document to return in each batch response from the server. 0 means use Mongo default. Default = 0
hint :: Order -- ^ Force MongoDB to use this index, [] = no hint. Default = []
} deriving (Show, Eq)
type Projector = Document
-- ^ Fields to return, analogous to the select clause in SQL. @[]@ means return whole document (analogous to * in SQL). @[\"x\" =: 1, \"y\" =: 1]@ means return only @x@ and @y@ fields of each document. @[\"x\" =: 0]@ means return all fields except @x@.
type Limit = Word32
-- ^ Maximum number of documents to return, i.e. cursor will close after iterating over this number of documents. 0 means no limit.
type Order = Document
-- ^ Fields to sort by. Each one is associated with 1 or -1. Eg. @[\"x\" =: 1, \"y\" =: -1]@ means sort by @x@ ascending then @y@ descending
type BatchSize = Word32
-- ^ The number of document to return in each batch response from the server. 0 means use Mongo default.
query :: Selector -> Collection -> Query
-- ^ Selects documents in collection that match selector. It uses no query options, projects all fields, does not skip any documents, does not limit result size, uses default batch size, does not sort, does not hint, and does not snapshot.
query sel col = Query [] (Select sel col) [] 0 0 [] False 0 []
find :: MonadIO m => Query -> Action m Cursor
-- ^ Fetch documents satisfying query
find q@Query{selection, batchSize} = do
db <- thisDatabase
pipe <- asks mongoPipe
qr <- queryRequest False q
dBatch <- liftIO $ request pipe [] qr
newCursor db (coll selection) batchSize dBatch
findOne :: (MonadIO m) => Query -> Action m (Maybe Document)
-- ^ Fetch first document satisfying query or Nothing if none satisfy it
findOne q = do
pipe <- asks mongoPipe
qr <- queryRequest False q {limit = 1}
rq <- liftIO $ request pipe [] qr
Batch _ _ docs <- liftDB $ fulfill rq
return (listToMaybe docs)
fetch :: (MonadIO m) => Query -> Action m Document
-- ^ Same as 'findOne' except throw 'DocNotFound' if none match
fetch q = findOne q >>= maybe (liftIO $ throwIO $ DocNotFound $ selection q) return
data FindAndModifyOpts = FamRemove Bool
| FamUpdate
{ famUpdate :: Document
, famNew :: Bool
, famUpsert :: Bool
}
deriving Show
defFamUpdateOpts :: Document -> FindAndModifyOpts
defFamUpdateOpts ups = FamUpdate
{ famNew = True
, famUpsert = False
, famUpdate = ups
}
-- | runs the findAndModify command as an update without an upsert and new set to true.
-- Returns a single updated document (new option is set to true).
--
-- see 'findAndModifyOpts' if you want to use findAndModify in a differnt way
findAndModify :: (MonadIO m, MonadFail m)
=> Query
-> Document -- ^ updates
-> Action m (Either String Document)
findAndModify q ups = do
eres <- findAndModifyOpts q (defFamUpdateOpts ups)
return $ case eres of
Left l -> Left l
Right r -> case r of
-- only possible when upsert is True and new is False
Nothing -> Left "findAndModify: impossible null result"
Just doc -> Right doc
-- | runs the findAndModify command,
-- allows more options than 'findAndModify'
findAndModifyOpts :: (MonadIO m, MonadFail m)
=> Query
->FindAndModifyOpts
-> Action m (Either String (Maybe Document))
findAndModifyOpts (Query {
selection = Select sel collection
, project = project
, sort = sort
}) famOpts = do
result <- runCommand
([ "findAndModify" := String collection
, "query" := Doc sel
, "fields" := Doc project
, "sort" := Doc sort
] ++
case famOpts of
FamRemove shouldRemove -> [ "remove" := Bool shouldRemove ]
FamUpdate {..} ->
[ "update" := Doc famUpdate
, "new" := Bool famNew -- return updated document, not original document
, "upsert" := Bool famUpsert -- insert if nothing is found
])
return $ case lookupErr result of
Just e -> leftErr e
Nothing -> case lookup "value" result of
Nothing -> leftErr "no document found"
Just mdoc -> case mdoc of
Just doc@(_:_) -> Right (Just doc)
Just [] -> case famOpts of
FamUpdate { famUpsert = True, famNew = False } -> Right Nothing
_ -> leftErr $ show result
_ -> leftErr $ show result
where
leftErr err = Left $ "findAndModify " `mappend` show collection
`mappend` "\nfrom query: " `mappend` show sel
`mappend` "\nerror: " `mappend` err
-- return Nothing means ok, Just is the error message
lookupErr :: Document -> Maybe String
lookupErr result = do
errObject <- lookup "lastErrorObject" result
lookup "err" errObject
explain :: (MonadIO m) => Query -> Action m Document
-- ^ Return performance stats of query execution
explain q = do -- same as findOne but with explain set to true
pipe <- asks mongoPipe
qr <- queryRequest True q {limit = 1}
r <- liftIO $ request pipe [] qr
Batch _ _ docs <- liftDB $ fulfill r
return $ if null docs then error ("no explain: " ++ show q) else head docs
count :: (MonadIO m) => Query -> Action m Int
-- ^ Fetch number of documents satisfying query (including effect of skip and/or limit if present)
count Query{selection = Select sel col, skip, limit} = at "n" `liftM` runCommand
(["count" =: col, "query" =: sel, "skip" =: (fromIntegral skip :: Int32)]
++ ("limit" =? if limit == 0 then Nothing else Just (fromIntegral limit :: Int32)))
distinct :: (MonadIO m) => Label -> Selection -> Action m [Value]
-- ^ Fetch distinct values of field in selected documents
distinct k (Select sel col) = at "values" `liftM` runCommand ["distinct" =: col, "key" =: k, "query" =: sel]
queryRequest :: (Monad m) => Bool -> Query -> Action m (Request, Maybe Limit)
-- ^ Translate Query to Protocol.Query. If first arg is true then add special $explain attribute.
queryRequest isExplain Query{..} = do
ctx <- ask
return $ queryRequest' (mongoReadMode ctx) (mongoDatabase ctx)
where
queryRequest' rm db = (P.Query{..}, remainingLimit) where
qOptions = readModeOption rm ++ options
qFullCollection = db <.> coll selection
qSkip = fromIntegral skip
(qBatchSize, remainingLimit) = batchSizeRemainingLimit batchSize (if limit == 0 then Nothing else Just limit)
qProjector = project
mOrder = if null sort then Nothing else Just ("$orderby" =: sort)
mSnapshot = if snapshot then Just ("$snapshot" =: True) else Nothing
mHint = if null hint then Nothing else Just ("$hint" =: hint)
mExplain = if isExplain then Just ("$explain" =: True) else Nothing
special = catMaybes [mOrder, mSnapshot, mHint, mExplain]
qSelector = if null special then s else ("$query" =: s) : special where s = selector selection
batchSizeRemainingLimit :: BatchSize -> (Maybe Limit) -> (Int32, Maybe Limit)
-- ^ Given batchSize and limit return P.qBatchSize and remaining limit
batchSizeRemainingLimit batchSize mLimit =
let remaining =
case mLimit of
Nothing -> batchSize
Just limit ->
if 0 < batchSize && batchSize < limit
then batchSize
else limit
in (fromIntegral remaining, mLimit)
type DelayedBatch = IO Batch
-- ^ A promised batch which may fail
data Batch = Batch (Maybe Limit) CursorId [Document]
-- ^ CursorId = 0 means cursor is finished. Documents is remaining documents to serve in current batch. Limit is number of documents to return. Nothing means no limit.
request :: Pipe -> [Notice] -> (Request, Maybe Limit) -> IO DelayedBatch
-- ^ Send notices and request and return promised batch
request pipe ns (req, remainingLimit) = do
promise <- liftIOE ConnectionFailure $ P.call pipe ns req
let protectedPromise = liftIOE ConnectionFailure promise
return $ fromReply remainingLimit =<< protectedPromise
fromReply :: Maybe Limit -> Reply -> DelayedBatch
-- ^ Convert Reply to Batch or Failure
fromReply limit Reply{..} = do
mapM_ checkResponseFlag rResponseFlags
return (Batch limit rCursorId rDocuments)
where
-- If response flag indicates failure then throw it, otherwise do nothing
checkResponseFlag flag = case flag of
AwaitCapable -> return ()
CursorNotFound -> throwIO $ CursorNotFoundFailure rCursorId
QueryError -> throwIO $ QueryFailure (at "code" $ head rDocuments) (at "$err" $ head rDocuments)
fulfill :: DelayedBatch -> Action IO Batch
-- ^ Demand and wait for result, raise failure if exception
fulfill = liftIO
-- *** Cursor
data Cursor = Cursor FullCollection BatchSize (MVar DelayedBatch)
-- ^ Iterator over results of a query. Use 'next' to iterate or 'rest' to get all results. A cursor is closed when it is explicitly closed, all results have been read from it, garbage collected, or not used for over 10 minutes (unless 'NoCursorTimeout' option was specified in 'Query'). Reading from a closed cursor raises a 'CursorNotFoundFailure'. Note, a cursor is not closed when the pipe is closed, so you can open another pipe to the same server and continue using the cursor.
newCursor :: MonadIO m => Database -> Collection -> BatchSize -> DelayedBatch -> Action m Cursor
-- ^ Create new cursor. If you don't read all results then close it. Cursor will be closed automatically when all results are read from it or when eventually garbage collected.
newCursor db col batchSize dBatch = do
var <- liftIO $ MV.newMVar dBatch
let cursor = Cursor (db <.> col) batchSize var
_ <- liftDB $ mkWeakMVar var (closeCursor cursor)
return cursor
nextBatch :: MonadIO m => Cursor -> Action m [Document]
-- ^ Return next batch of documents in query result, which will be empty if finished.
nextBatch (Cursor fcol batchSize var) = liftDB $ modifyMVar var $ \dBatch -> do
-- Pre-fetch next batch promise from server and return current batch.
Batch mLimit cid docs <- liftDB $ fulfill' fcol batchSize dBatch
let newLimit = do
limit <- mLimit
return $ limit - (min limit $ fromIntegral $ length docs)
let emptyBatch = return $ Batch (Just 0) 0 []
let getNextBatch = nextBatch' fcol batchSize newLimit cid
let resultDocs = (maybe id (take . fromIntegral) mLimit) docs
case (cid, newLimit) of
(0, _) -> return (emptyBatch, resultDocs)
(_, Just 0) -> do
pipe <- asks mongoPipe
liftIOE ConnectionFailure $ P.send pipe [KillCursors [cid]]
return (emptyBatch, resultDocs)
(_, _) -> (, resultDocs) <$> getNextBatch
fulfill' :: FullCollection -> BatchSize -> DelayedBatch -> Action IO Batch
-- Discard pre-fetched batch if empty with nonzero cid.
fulfill' fcol batchSize dBatch = do
b@(Batch limit cid docs) <- fulfill dBatch
if cid /= 0 && null docs && (limit > (Just 0))
then nextBatch' fcol batchSize limit cid >>= fulfill
else return b
nextBatch' :: (MonadIO m) => FullCollection -> BatchSize -> (Maybe Limit) -> CursorId -> Action m DelayedBatch
nextBatch' fcol batchSize limit cid = do
pipe <- asks mongoPipe
liftIO $ request pipe [] (GetMore fcol batchSize' cid, remLimit)
where (batchSize', remLimit) = batchSizeRemainingLimit batchSize limit
next :: MonadIO m => Cursor -> Action m (Maybe Document)
-- ^ Return next document in query result, or Nothing if finished.
next (Cursor fcol batchSize var) = liftDB $ modifyMVar var nextState where
-- Pre-fetch next batch promise from server when last one in current batch is returned.
-- nextState:: DelayedBatch -> Action m (DelayedBatch, Maybe Document)
nextState dBatch = do
Batch mLimit cid docs <- liftDB $ fulfill' fcol batchSize dBatch
if mLimit == (Just 0)
then return (return $ Batch (Just 0) 0 [], Nothing)
else
case docs of
doc : docs' -> do
let newLimit = do
limit <- mLimit
return $ limit - 1
dBatch' <- if null docs' && cid /= 0 && ((newLimit > (Just 0)) || (isNothing newLimit))
then nextBatch' fcol batchSize newLimit cid
else return $ return (Batch newLimit cid docs')
when (newLimit == (Just 0)) $ unless (cid == 0) $ do
pipe <- asks mongoPipe
liftIOE ConnectionFailure $ P.send pipe [KillCursors [cid]]
return (dBatch', Just doc)
[] -> if cid == 0
then return (return $ Batch (Just 0) 0 [], Nothing) -- finished
else do
nb <- nextBatch' fcol batchSize mLimit cid
return (nb, Nothing)
nextN :: MonadIO m => Int -> Cursor -> Action m [Document]
-- ^ Return next N documents or less if end is reached
nextN n c = catMaybes `liftM` replicateM n (next c)
rest :: MonadIO m => Cursor -> Action m [Document]
-- ^ Return remaining documents in query result
rest c = loop (next c)
closeCursor :: MonadIO m => Cursor -> Action m ()
closeCursor (Cursor _ _ var) = liftDB $ modifyMVar var $ \dBatch -> do
Batch _ cid _ <- fulfill dBatch
unless (cid == 0) $ do
pipe <- asks mongoPipe
liftIOE ConnectionFailure $ P.send pipe [KillCursors [cid]]
return $ (return $ Batch (Just 0) 0 [], ())
isCursorClosed :: MonadIO m => Cursor -> Action m Bool
isCursorClosed (Cursor _ _ var) = do
Batch _ cid docs <- liftDB $ fulfill =<< readMVar var
return (cid == 0 && null docs)
-- ** Aggregate
type Pipeline = [Document]
-- ^ The Aggregate Pipeline
aggregate :: (MonadIO m, MonadFail m) => Collection -> Pipeline -> Action m [Document]
-- ^ Runs an aggregate and unpacks the result. See <http://docs.mongodb.org/manual/core/aggregation/> for details.
aggregate aColl agg = do
aggregateCursor aColl agg def >>= rest
data AggregateConfig = AggregateConfig {}
deriving Show
instance Default AggregateConfig where
def = AggregateConfig {}
aggregateCursor :: (MonadIO m, MonadFail m) => Collection -> Pipeline -> AggregateConfig -> Action m Cursor
-- ^ Runs an aggregate and unpacks the result. See <http://docs.mongodb.org/manual/core/aggregation/> for details.
aggregateCursor aColl agg _ = do
response <- runCommand ["aggregate" =: aColl, "pipeline" =: agg, "cursor" =: ([] :: Document)]
case true1 "ok" response of
True -> do
cursor :: Document <- lookup "cursor" response
firstBatch :: [Document] <- lookup "firstBatch" cursor
cursorId :: Int64 <- lookup "id" cursor
db <- thisDatabase
newCursor db aColl 0 $ return $ Batch Nothing cursorId firstBatch
False -> liftIO $ throwIO $ AggregateFailure $ at "errmsg" response
-- ** Group
-- | Groups documents in collection by key then reduces (aggregates) each group
data Group = Group {
gColl :: Collection,
gKey :: GroupKey, -- ^ Fields to group by
gReduce :: Javascript, -- ^ @(doc, agg) -> ()@. The reduce function reduces (aggregates) the objects iterated. Typical operations of a reduce function include summing and counting. It takes two arguments, the current document being iterated over and the aggregation value, and updates the aggregate value.
gInitial :: Document, -- ^ @agg@. Initial aggregation value supplied to reduce
gCond :: Selector, -- ^ Condition that must be true for a row to be considered. [] means always true.
gFinalize :: Maybe Javascript -- ^ @agg -> () | result@. An optional function to be run on each item in the result set just before the item is returned. Can either modify the item (e.g., add an average field given a count and a total) or return a replacement object (returning a new object with just _id and average fields).
} deriving (Show, Eq)
data GroupKey = Key [Label] | KeyF Javascript deriving (Show, Eq)
-- ^ Fields to group by, or function (@doc -> key@) returning a "key object" to be used as the grouping key. Use KeyF instead of Key to specify a key that is not an existing member of the object (or, to access embedded members).
groupDocument :: Group -> Document
-- ^ Translate Group data into expected document form
groupDocument Group{..} =
("finalize" =? gFinalize) ++ [
"ns" =: gColl,
case gKey of Key k -> "key" =: map (=: True) k; KeyF f -> "$keyf" =: f,
"$reduce" =: gReduce,
"initial" =: gInitial,
"cond" =: gCond ]
group :: (MonadIO m) => Group -> Action m [Document]
-- ^ Execute group query and return resulting aggregate value for each distinct key
group g = at "retval" `liftM` runCommand ["group" =: groupDocument g]
-- ** MapReduce
-- | Maps every document in collection to a list of (key, value) pairs, then for each unique key reduces all its associated values to a single result. There are additional parameters that may be set to tweak this basic operation.
-- This implements the latest version of map-reduce that requires MongoDB 1.7.4 or greater. To map-reduce against an older server use runCommand directly as described in http://www.mongodb.org/display/DOCS/MapReduce.
data MapReduce = MapReduce {
rColl :: Collection,
rMap :: MapFun,
rReduce :: ReduceFun,
rSelect :: Selector, -- ^ Operate on only those documents selected. Default is [] meaning all documents.
rSort :: Order, -- ^ Default is [] meaning no sort
rLimit :: Limit, -- ^ Default is 0 meaning no limit
rOut :: MROut, -- ^ Output to a collection with a certain merge policy. Default is no collection ('Inline'). Note, you don't want this default if your result set is large.
rFinalize :: Maybe FinalizeFun, -- ^ Function to apply to all the results when finished. Default is Nothing.
rScope :: Document, -- ^ Variables (environment) that can be accessed from map/reduce/finalize. Default is [].
rVerbose :: Bool -- ^ Provide statistics on job execution time. Default is False.
} deriving (Show, Eq)
type MapFun = Javascript
-- ^ @() -> void@. The map function references the variable @this@ to inspect the current object under consideration. The function must call @emit(key,value)@ at least once, but may be invoked any number of times, as may be appropriate.
type ReduceFun = Javascript
-- ^ @(key, [value]) -> value@. The reduce function receives a key and an array of values and returns an aggregate result value. The MapReduce engine may invoke reduce functions iteratively; thus, these functions must be idempotent. That is, the following must hold for your reduce function: @reduce(k, [reduce(k,vs)]) == reduce(k,vs)@. If you need to perform an operation only once, use a finalize function. The output of emit (the 2nd param) and reduce should be the same format to make iterative reduce possible.
type FinalizeFun = Javascript
-- ^ @(key, value) -> final_value@. A finalize function may be run after reduction. Such a function is optional and is not necessary for many map/reduce cases. The finalize function takes a key and a value, and returns a finalized value.
data MROut =
Inline -- ^ Return results directly instead of writing them to an output collection. Results must fit within 16MB limit of a single document
| Output MRMerge Collection (Maybe Database) -- ^ Write results to given collection, in other database if specified. Follow merge policy when entry already exists
deriving (Show, Eq)
data MRMerge =
Replace -- ^ Clear all old data and replace it with new data
| Merge -- ^ Leave old data but overwrite entries with the same key with new data
| Reduce -- ^ Leave old data but combine entries with the same key via MR's reduce function
deriving (Show, Eq)
type MRResult = Document
-- ^ Result of running a MapReduce has some stats besides the output. See http://www.mongodb.org/display/DOCS/MapReduce#MapReduce-Resultobject
mrDocument :: MapReduce -> Document
-- ^ Translate MapReduce data into expected document form
mrDocument MapReduce{..} =
("mapreduce" =: rColl) :
("out" =: mrOutDoc rOut) :
("finalize" =? rFinalize) ++ [
"map" =: rMap,
"reduce" =: rReduce,
"query" =: rSelect,
"sort" =: rSort,
"limit" =: (fromIntegral rLimit :: Int),
"scope" =: rScope,
"verbose" =: rVerbose ]
mrOutDoc :: MROut -> Document
-- ^ Translate MROut into expected document form
mrOutDoc Inline = ["inline" =: (1 :: Int)]
mrOutDoc (Output mrMerge coll mDB) = (mergeName mrMerge =: coll) : mdb mDB where
mergeName Replace = "replace"
mergeName Merge = "merge"
mergeName Reduce = "reduce"
mdb Nothing = []
mdb (Just db) = ["db" =: db]
mapReduce :: Collection -> MapFun -> ReduceFun -> MapReduce
-- ^ MapReduce on collection with given map and reduce functions. Remaining attributes are set to their defaults, which are stated in their comments.
mapReduce col map' red = MapReduce col map' red [] [] 0 Inline Nothing [] False
runMR :: MonadIO m => MapReduce -> Action m Cursor
-- ^ Run MapReduce and return cursor of results. Error if map/reduce fails (because of bad Javascript)
runMR mr = do
res <- runMR' mr
case look "result" res of
Just (String coll) -> find $ query [] coll
Just (Doc doc) -> useDb (at "db" doc) $ find $ query [] (at "collection" doc)
Just x -> error $ "unexpected map-reduce result field: " ++ show x
Nothing -> newCursor "" "" 0 $ return $ Batch (Just 0) 0 (at "results" res)
runMR' :: (MonadIO m) => MapReduce -> Action m MRResult
-- ^ Run MapReduce and return a MR result document containing stats and the results if Inlined. Error if the map/reduce failed (because of bad Javascript).
runMR' mr = do
doc <- runCommand (mrDocument mr)
return $ if true1 "ok" doc then doc else error $ "mapReduce error:\n" ++ show doc ++ "\nin:\n" ++ show mr
-- * Command
type Command = Document
-- ^ A command is a special query or action against the database. See <http://www.mongodb.org/display/DOCS/Commands> for details.
runCommand :: (MonadIO m) => Command -> Action m Document
-- ^ Run command against the database and return its result
runCommand c = maybe err id `liftM` findOne (query c "$cmd") where
err = error $ "Nothing returned for command: " ++ show c
runCommand1 :: (MonadIO m) => Text -> Action m Document
-- ^ @runCommand1 foo = runCommand [foo =: 1]@
runCommand1 c = runCommand [c =: (1 :: Int)]
eval :: (MonadIO m, Val v) => Javascript -> Action m v
-- ^ Run code on server
eval code = at "retval" `liftM` runCommand ["$eval" =: code]
modifyMVar :: MVar a -> (a -> Action IO (a, b)) -> Action IO b
modifyMVar v f = do
ctx <- ask
liftIO $ MV.modifyMVar v (\x -> runReaderT (f x) ctx)
mkWeakMVar :: MVar a -> Action IO () -> Action IO (Weak (MVar a))
mkWeakMVar m closing = do
ctx <- ask
#if MIN_VERSION_base(4,6,0)
liftIO $ MV.mkWeakMVar m $ runReaderT closing ctx
#else
liftIO $ MV.addMVarFinalizer m $ runReaderT closing ctx
#endif
{- Authors: Tony Hannan <[email protected]>
Copyright 2011 10gen Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -}
|
VictorDenisov/mongodb
|
Database/MongoDB/Query.hs
|
apache-2.0
| 69,002 | 1 | 28 | 19,952 | 15,853 | 8,292 | 7,561 | 1,066 | 9 |
{-|
Module : Learning.TinCan.Statement
Description : Statements and related Experience API objects.
Copyright : (c) Thomas Sutton
License : BSD2
Maintainer : [email protected]
Stability : experimental
Portability : portable
This module defines data types and functions to manipulate Statements
and related Exerience API objects.
-}
{-# LANGUAGE OverloadedStrings #-}
module Learning.TinCan.Statement where
import Data.Map.Lazy (Map)
import qualified Data.Map.Lazy as Map
import Data.Text (Text)
import Data.Time.Clock
import Data.UUID
import Data.Version (Version)
import Text.URI (URI)
import Learning.TinCan.Version (xAPIVersion)
type Result = String
type Context = String
type Attachment = String
type Extension = Map Text Text
-- | A map from language codes to strings.
type LangMap = Map Text Text
-- | Let's pretend that 'Data.URI' is IRI safe (maybe it is!) and that
-- we know it (alas, it's just a hope).
type IRI = URI
-- | An "inverse functional identifier" is a method of naming an actor.
data IFI = IFIMBox String -- ^ A mailto: IRI
| IFIMBoxSHA String -- ^ A SHA1 checksum of a mailto:
| IFIOpenID String -- ^ An OpenID IFI
| IFIAccount String String -- ^ An "account" IFI
-- | Actors identify the people, groups and systems which perform actions.
--
-- There are several varieties of Actors, each represented by a data type
-- carrying it's one specific data and passed through the 't' type parameter.
-- Values will have types like 'Actor Agent', 'Actor Group' and 'Actor
-- AnonymousGroup'.
data Actor = Actor { actorName :: Maybe Text
, actorIFI :: Maybe IFI
, groupMembers :: Maybe [Actor]
}
-- | Verbs identify the actions to be recorded in an LRS.
data Verb = Verb { verbID :: IRI -- ^ Identifying IRI for the verb.
, verbName :: Maybe LangMap
}
data Activity = Activity { activityID :: IRI
, activityName :: Maybe LangMap
, activityDescription :: Maybe LangMap
, activityType :: Maybe IRI
, activityMoreInfo :: Maybe IRI
, activityExtension :: Maybe Extension
}
-- | Objects identify the activities, materials, actors and other objects
-- that learners can interact with.
data Object = ObjectActivity Activity
| ObjectAgent Actor
-- | A TinCan API statement records describes an event to be recorded in an LRS.
data Statement = Statement
{ statementVersion :: Maybe Version
-- ^ Specification version.
, statementID :: Maybe UUID
-- ^ Unique ID of this statement.
, statementActor :: Actor
-- ^ Who performed the action.
, statementVerb :: Verb
-- ^ Which action they performed.
, statementObject :: Object -- ^ What they did it to.
, statementResult :: Maybe Result
-- ^ The result of the action.
, statementContext :: Maybe Context
-- ^ Context the action was performed in.
, statementTimestamp :: Maybe UTCTime
-- ^ Time the action was performed.
, statementStored :: Maybe UTCTime
-- ^ Time the statement was recorded.
, statementAuthority :: Maybe Actor
-- ^ Actor who recorded the statement.
, statementAttachment :: Maybe Attachment
}
{-
-- | Create a new object.
newObject :: URI -- ^ Unique identifier for the object.
-> Object
newObject uri = ObjectActivity $ Activity uri Nothing Nothing
-- | Add a key/value pair to the extension of an object.
setObjectExtension :: Object -- ^ Object to update.
-> URI -- ^ Extension identifier.
-> String -- ^ Extension value.
-> Object
setObjectExtension obj k v = case extensions obj of
Nothing -> obj { extensions = Just $ Map.singleton k v }
Just e -> obj { extensions = Just $ Map.insert k v e }
-}
-- | Create simple 'Statement' with all optional fields empty.
statement :: Actor -> Verb -> Object -> Statement
statement a v o = Statement ver sid a v o res ctx ts std ath att
where
ver = Just xAPIVersion
sid = Nothing
res = Nothing
ctx = Nothing
ts = Nothing
std = Nothing
ath = Nothing
att = Nothing
|
thsutton/tincan
|
src/Learning/TinCan/Statement.hs
|
bsd-2-clause
| 4,387 | 0 | 10 | 1,256 | 517 | 314 | 203 | 55 | 1 |
{-# LANGUAGE
NoImplicitPrelude
#-}
import qualified Hakflow.Abstraction as A
import Hakflow.Makeflow
import Hakflow.Monad
import Hakflow.Util
import Hakflow.Magma
import Hakflow.Instances.Vector
import Data.Default
import Data.Vector (Vector)
import qualified Data.Vector as V
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.Set (Set)
import qualified Data.Set as S
import Data.Default
import Prelude.Plus
testMap s = let prog = do let c1 = Cmd { exec = executable "/bin/echo"
, params = []
, depends = S.empty
, redirection = Nothing
}
A.map def {A.chunksize = s} c1 (map (Param . TextArg . T.pack . (++) "test" . show) [1..10])
in do (r,_,_) <- run prog def def
T.putStrLn . emerge $ r
|
badi/hakflow
|
tests/Abstraction.hs
|
bsd-2-clause
| 962 | 0 | 18 | 333 | 272 | 158 | 114 | 25 | 1 |
{-# LANGUAGE DeriveDataTypeable,
FlexibleInstances,
MultiParamTypeClasses,
OverloadedStrings,
TemplateHaskell,
TypeSynonymInstances #-}
module TH.APIs where
import Language.Haskell.TH
import qualified Data.TH.API as TH
import Data.TH.Convert ()
import TH.API
$(do
runIO $ putStrLn "API generation"
apis <- generateAPIs "apis"
runIO . putStrLn $ "..Generated " ++
(show . length $ apis) ++
" apis"
runIO $ putStrLn "..Done"
return $ foldr
(\(TH.API _
(TH.APIInput _ _ _ iDecs)
(TH.APIOutput _ _ _ oDecs)) a -> iDecs ++ oDecs ++ a)
[] apis
)
|
fabianbergmark/APIs
|
src/TH/APIs.hs
|
bsd-2-clause
| 718 | 0 | 17 | 256 | 177 | 92 | 85 | 23 | 0 |
{-# LANGUAGE CPP, GeneralizedNewtypeDeriving, ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- |
-- Module: System.FilePath.Find
-- Copyright: Bryan O'Sullivan
-- License: BSD3
-- Maintainer: Bryan O'Sullivan <[email protected]>
-- Stability: unstable
-- Portability: Unix-like systems (requires newtype deriving)
--
-- This module provides functions for traversing a filesystem
-- hierarchy. The 'find' function generates a lazy list of matching
-- files, while 'fold' performs a left fold.
--
-- Both 'find' and 'fold' allow fine control over recursion, using the
-- 'FindClause' type. This type is also used to pre-filter the results
-- returned by 'find'.
--
-- The 'FindClause' type lets you write filtering and recursion
-- control expressions clearly and easily.
--
-- For example, this clause matches C source files.
--
-- @
-- 'extension' '==?' \".c\" '||?' 'extension' '==?' \".h\"
-- @
--
-- Because 'FindClause' is a monad, you can use the usual monad
-- machinery to, for example, lift pure functions into it.
--
-- Here's a clause that will return 'True' for any file whose
-- directory name contains the word @\"temp\"@.
--
-- @
-- (isInfixOf \"temp\") \`liftM\` 'directory'
-- @
module System.FilePath.Find (
FileInfo(..)
, FileType(..)
, FindClause
, FilterPredicate
, RecursionPredicate
-- * Simple entry points
, find
, fold
-- * More expressive entry points
, findWithHandler
, foldWithHandler
-- * Helper functions
, evalClause
, statusType
, liftOp
-- * Combinators for controlling recursion and filtering behaviour
, filePath
, fileStatus
, depth
, fileInfo
, always
, extension
, directory
, fileName
, fileType
, contains
-- ** Combinator versions of 'F.FileStatus' functions from "System.Posix.Files"
-- $statusFunctions
, deviceID
, fileID
, fileOwner
, fileGroup
, fileSize
, linkCount
, specialDeviceID
, fileMode
, accessTime
, modificationTime
, statusChangeTime
-- *** Convenience combinators for file status
, filePerms
, anyPerms
-- ** Combinators for canonical path and name
, canonicalPath
, canonicalName
-- ** Combinators that operate on symbolic links
, readLink
, followStatus
-- ** Common binary operators, lifted as combinators
-- $binaryOperators
, (~~?)
, (/~?)
, (==?)
, (/=?)
, (>?)
, (<?)
, (>=?)
, (<=?)
, (.&.?)
-- ** Combinators for gluing clauses together
, (&&?)
, (||?)
) where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative (Applicative)
#endif
import qualified Control.Exception as E
import Control.Exception (IOException, handle)
import Control.Monad (foldM, forM, liftM, liftM2)
import Control.Monad.State (State, evalState, get)
import Data.Bits (Bits, (.&.))
import Data.List (sort)
import System.Directory (getDirectoryContents, canonicalizePath)
import System.FilePath ((</>), takeDirectory, takeExtension, takeFileName)
import System.FilePath.GlobPattern (GlobPattern, (~~), (/~))
import System.IO (hPutStrLn, stderr)
import System.IO.Unsafe (unsafeInterleaveIO, unsafePerformIO)
import qualified System.PosixCompat.Files as F
import qualified System.PosixCompat.Types as T
-- | Information collected during the traversal of a directory.
data FileInfo = FileInfo
{
infoPath :: FilePath -- ^ file path
, infoDepth :: Int -- ^ current recursion depth
, infoStatus :: F.FileStatus -- ^ status of file
} deriving (Eq)
instance Eq F.FileStatus where
a == b = F.deviceID a == F.deviceID b &&
F.fileID a == F.fileID b
-- | Construct a 'FileInfo' value.
mkFI :: FilePath -> Int -> F.FileStatus -> FileInfo
mkFI = FileInfo
-- | Monadic container for file information, allowing for clean
-- construction of combinators. Wraps the 'State' monad, but doesn't
-- allow 'get' or 'put'.
newtype FindClause a = FC { runFC :: State FileInfo a }
deriving (Functor, Applicative, Monad)
-- | Run the given 'FindClause' on the given 'FileInfo' and return its
-- result. This can be useful if you are writing a function to pass
-- to 'fold'.
--
-- Example:
--
-- @
-- myFoldFunc :: a -> 'FileInfo' -> a
-- myFoldFunc a i = let useThisFile = 'evalClause' ('fileName' '==?' \"foo\") i
-- in if useThisFile
-- then fiddleWith a
-- else a
-- @
evalClause :: FindClause a -> FileInfo -> a
evalClause = evalState . runFC
evalFI :: FindClause a
-> FilePath
-> Int
-> F.FileStatus
-> a
evalFI m p d s = evalClause m (mkFI p d s)
-- | Return the current 'FileInfo'.
fileInfo :: FindClause FileInfo
fileInfo = FC $ get
-- | Return the name of the file being visited.
filePath :: FindClause FilePath
filePath = infoPath `liftM` fileInfo
-- | Return the current recursion depth.
depth :: FindClause Int
depth = infoDepth `liftM` fileInfo
-- | Return the 'F.FileStatus' for the current file.
fileStatus :: FindClause F.FileStatus
fileStatus = infoStatus `liftM` fileInfo
type FilterPredicate = FindClause Bool
type RecursionPredicate = FindClause Bool
-- | List the files in the given directory, sorted, and without \".\"
-- or \"..\".
getDirContents :: FilePath -> IO [FilePath]
getDirContents dir = (sort . filter goodName) `liftM` getDirectoryContents dir
where goodName "." = False
goodName ".." = False
goodName _ = True
-- | Search a directory recursively, with recursion controlled by a
-- 'RecursionPredicate'. Lazily return a sorted list of all files
-- matching the given 'FilterPredicate'. Any errors that occur are
-- dealt with by the given handler.
findWithHandler ::
(FilePath -> IOException -> IO [FilePath]) -- ^ error handler
-> RecursionPredicate -- ^ control recursion into subdirectories
-> FilterPredicate -- ^ decide whether a file appears in the result
-> FilePath -- ^ directory to start searching
-> IO [FilePath] -- ^ files that matched the 'FilterPredicate'
findWithHandler errHandler recurse filt path0 =
handle (errHandler path0) $ F.getSymbolicLinkStatus path0 >>= visit path0 0
where visit path depth st =
if F.isDirectory st && evalFI recurse path depth st
then unsafeInterleaveIO (traverse path (succ depth) st)
else filterPath path depth st []
traverse dir depth dirSt = do
names <- E.catch (getDirContents dir) (errHandler dir)
filteredPaths <- forM names $ \name -> do
let path = dir </> name
unsafeInterleaveIO $ handle (errHandler path)
(F.getSymbolicLinkStatus path >>= visit path depth)
filterPath dir depth dirSt (concat filteredPaths)
filterPath path depth st result =
return $ if evalFI filt path depth st
then path:result
else result
-- | Search a directory recursively, with recursion controlled by a
-- 'RecursionPredicate'. Lazily return a sorted list of all files
-- matching the given 'FilterPredicate'. Any errors that occur are
-- ignored, with warnings printed to 'stderr'.
find :: RecursionPredicate -- ^ control recursion into subdirectories
-> FilterPredicate -- ^ decide whether a file appears in the result
-> FilePath -- ^ directory to start searching
-> IO [FilePath] -- ^ files that matched the 'FilterPredicate'
find = findWithHandler warnOnError
where warnOnError path err =
hPutStrLn stderr (path ++ ": " ++ show err) >> return []
-- | Search a directory recursively, with recursion controlled by a
-- 'RecursionPredicate'. Fold over all files found. Any errors that
-- occur are dealt with by the given handler. The fold is strict, and
-- run from \"left\" to \"right\", so the folded function should be
-- strict in its left argument to avoid space leaks. If you need a
-- right-to-left fold, use 'foldr' on the result of 'findWithHandler'
-- instead.
foldWithHandler
:: (FilePath -> a -> IOException -> IO a) -- ^ error handler
-> RecursionPredicate -- ^ control recursion into subdirectories
-> (a -> FileInfo -> a) -- ^ function to fold with
-> a -- ^ seed value for fold
-> FilePath -- ^ directory to start searching
-> IO a -- ^ final value after folding
foldWithHandler errHandler recurse f state path =
handle (errHandler path state) $
F.getSymbolicLinkStatus path >>= visit state path 0
where visit state path depth st =
if F.isDirectory st && evalFI recurse path depth st
then traverse state path (succ depth) st
else let state' = f state (mkFI path depth st)
in state' `seq` return state'
traverse state dir depth dirSt = handle (errHandler dir state) $
getDirContents dir >>=
let state' = f state (mkFI dir depth dirSt)
in state' `seq` flip foldM state' (\state name ->
handle (errHandler dir state) $
let path = dir </> name
in F.getSymbolicLinkStatus path >>= visit state path depth)
-- | Search a directory recursively, with recursion controlled by a
-- 'RecursionPredicate'. Fold over all files found. Any errors that
-- occur are ignored, with warnings printed to 'stderr'. The fold
-- function is run from \"left\" to \"right\", so it should be strict
-- in its left argument to avoid space leaks. If you need a
-- right-to-left fold, use 'foldr' on the result of 'findWithHandler'
-- instead.
fold :: RecursionPredicate
-> (a -> FileInfo -> a)
-> a
-> FilePath
-> IO a
fold = foldWithHandler warnOnError
where warnOnError path a err =
hPutStrLn stderr (path ++ ": " ++ show err) >> return a
-- | Unconditionally return 'True'.
always :: FindClause Bool
always = return True
-- | Return the file name extension.
--
-- Example:
--
-- @
-- 'extension' \"foo\/bar.txt\" => \".txt\"
-- @
extension :: FindClause FilePath
extension = takeExtension `liftM` filePath
-- | Return the file name, without the directory name.
--
-- What this means in practice:
--
-- @
-- 'fileName' \"foo\/bar.txt\" => \"bar.txt\"
-- @
--
-- Example:
--
-- @
-- 'fileName' '==?' \"init.c\"
-- @
fileName :: FindClause FilePath
fileName = takeFileName `liftM` filePath
-- | Return the directory name, without the file name.
--
-- What this means in practice:
--
-- @
-- 'directory' \"foo\/bar.txt\" => \"foo\"
-- @
--
-- Example in a clause:
--
-- @
-- let hasSuffix = 'liftOp' 'isSuffixOf'
-- in directory \`hasSuffix\` \"tests\"
-- @
directory :: FindClause FilePath
directory = takeDirectory `liftM` filePath
-- | Return the canonical path of the file being visited.
--
-- See `canonicalizePath` for details of what canonical path means.
canonicalPath :: FindClause FilePath
canonicalPath = (unsafePerformIO . canonicalizePath) `liftM` filePath
-- | Return the canonical name of the file (canonical path with the
-- directory part removed).
canonicalName :: FindClause FilePath
canonicalName = takeFileName `liftM` canonicalPath
-- | Run the given action in the 'IO' monad (using 'unsafePerformIO')
-- if the current file is a symlink. Hide errors by wrapping results
-- in the 'Maybe' monad.
withLink :: (FilePath -> IO a) -> FindClause (Maybe a)
withLink f = do
path <- filePath
st <- fileStatus
return $ if F.isSymbolicLink st
then unsafePerformIO $ handle (\(_::IOException) -> return Nothing) $
Just `liftM` f path
else Nothing
-- | If the current file is a symbolic link, return 'Just' the target
-- of the link, otherwise 'Nothing'.
readLink :: FindClause (Maybe FilePath)
readLink = withLink F.readSymbolicLink
-- | If the current file is a symbolic link, return 'Just' the status
-- of the ultimate endpoint of the link. Otherwise (including in the
-- case of an error), return 'Nothing'.
--
-- Example:
--
-- @
-- 'statusType' \`liftM\` 'followStatus' '==?' 'RegularFile'
-- @
followStatus :: FindClause (Maybe F.FileStatus)
followStatus = withLink F.getFileStatus
data FileType = BlockDevice
| CharacterDevice
| NamedPipe
| RegularFile
| Directory
| SymbolicLink
| Socket
| Unknown
deriving (Eq, Ord, Show)
-- | Return the type of file currently being visited.
--
-- Example:
--
-- @
-- 'fileType' '==?' 'RegularFile'
-- @
fileType :: FindClause FileType
fileType = statusType `liftM` fileStatus
-- | Return the type of a file. This is much more useful for case
-- analysis than the usual functions on 'F.FileStatus' values.
statusType :: F.FileStatus -> FileType
statusType st | F.isBlockDevice st = BlockDevice
statusType st | F.isCharacterDevice st = CharacterDevice
statusType st | F.isNamedPipe st = NamedPipe
statusType st | F.isRegularFile st = RegularFile
statusType st | F.isDirectory st = Directory
statusType st | F.isSymbolicLink st = SymbolicLink
statusType st | F.isSocket st = Socket
statusType _ = Unknown
-- $statusFunctions
--
-- These are simply lifted versions of the 'F.FileStatus' accessor
-- functions in the "System.Posix.Files" module. The definitions all
-- have the following form:
--
-- @
-- 'deviceID' :: 'FindClause' "System.Posix.Types".DeviceID
-- 'deviceID' = "System.Posix.Files".deviceID \`liftM\` 'fileStatus'
-- @
deviceID :: FindClause T.DeviceID
deviceID = F.deviceID `liftM` fileStatus
fileID :: FindClause T.FileID
fileID = F.fileID `liftM` fileStatus
fileOwner :: FindClause T.UserID
fileOwner = F.fileOwner `liftM` fileStatus
fileGroup :: FindClause T.GroupID
fileGroup = F.fileGroup `liftM` fileStatus
fileSize :: FindClause T.FileOffset
fileSize = F.fileSize `liftM` fileStatus
linkCount :: FindClause T.LinkCount
linkCount = F.linkCount `liftM` fileStatus
specialDeviceID :: FindClause T.DeviceID
specialDeviceID = F.specialDeviceID `liftM` fileStatus
fileMode :: FindClause T.FileMode
fileMode = F.fileMode `liftM` fileStatus
-- | Return the permission bits of the 'T.FileMode'.
filePerms :: FindClause T.FileMode
filePerms = (.&. 0777) `liftM` fileMode
-- | Return 'True' if any of the given permission bits is set.
--
-- Example:
--
-- @
-- 'anyPerms' 0444
-- @
anyPerms :: T.FileMode
-> FindClause Bool
anyPerms m = filePerms >>= \p -> return (p .&. m /= 0)
accessTime :: FindClause T.EpochTime
accessTime = F.accessTime `liftM` fileStatus
modificationTime :: FindClause T.EpochTime
modificationTime = F.modificationTime `liftM` fileStatus
statusChangeTime :: FindClause T.EpochTime
statusChangeTime = F.statusChangeTime `liftM` fileStatus
-- | Return 'True' if the given path exists, relative to the current
-- file. For example, if @\"foo\"@ is being visited, and you call
-- contains @\"bar\"@, this combinator will return 'True' if
-- @\"foo\/bar\"@ exists.
contains :: FilePath -> FindClause Bool
contains p = do
d <- filePath
return $ unsafePerformIO $
handle (\(_::IOException) -> return False) $
F.getFileStatus (d </> p) >> return True
-- | Lift a binary operator into the 'FindClause' monad, so that it
-- becomes a combinator. The left hand side of the combinator should
-- be a @'FindClause' a@, while the right remains a normal value of
-- type @a@.
liftOp :: Monad m => (a -> b -> c) -> m a -> b -> m c
liftOp f a b = a >>= \a' -> return (f a' b)
-- $binaryOperators
--
-- These are lifted versions of the most commonly used binary
-- operators. They have the same fixities and associativities as
-- their unlifted counterparts. They are lifted using 'liftOp', like
-- so:
--
-- @('==?') = 'liftOp' (==)@
-- | Return 'True' if the current file's name matches the given
-- 'GlobPattern'.
(~~?) :: FindClause FilePath -> GlobPattern -> FindClause Bool
(~~?) = liftOp (~~)
infix 4 ~~?
-- | Return 'True' if the current file's name does not match the given
-- 'GlobPattern'.
(/~?) :: FindClause FilePath -> GlobPattern -> FindClause Bool
(/~?) = liftOp (/~)
infix 4 /~?
(==?) :: Eq a => FindClause a -> a -> FindClause Bool
(==?) = liftOp (==)
infix 4 ==?
(/=?) :: Eq a => FindClause a -> a -> FindClause Bool
(/=?) = liftOp (/=)
infix 4 /=?
(>?) :: Ord a => FindClause a -> a -> FindClause Bool
(>?) = liftOp (>)
infix 4 >?
(<?) :: Ord a => FindClause a -> a -> FindClause Bool
(<?) = liftOp (<)
infix 4 <?
(>=?) :: Ord a => FindClause a -> a -> FindClause Bool
(>=?) = liftOp (>=)
infix 4 >=?
(<=?) :: Ord a => FindClause a -> a -> FindClause Bool
(<=?) = liftOp (<=)
infix 4 <=?
-- | This operator is useful to check if bits are set in a
-- 'T.FileMode'.
(.&.?) :: Bits a => FindClause a -> a -> FindClause a
(.&.?) = liftOp (.&.)
infixl 7 .&.?
(&&?) :: FindClause Bool -> FindClause Bool -> FindClause Bool
(&&?) = liftM2 (&&)
infixr 3 &&?
(||?) :: FindClause Bool -> FindClause Bool -> FindClause Bool
(||?) = liftM2 (||)
infixr 2 ||?
|
bos/filemanip
|
System/FilePath/Find.hs
|
bsd-3-clause
| 17,036 | 0 | 19 | 3,765 | 3,226 | 1,844 | 1,382 | 274 | 3 |
module Text.ICalendar.Component.VCalendarSpec
( main
, spec
) where
-- haskell platform libraries
import Data.List
-- foreign libraries
import Test.Hspec
-- native libraries
import Spec.Expectations
import Spec.Helpers
import Text.ICalendar.Component.VCalendar
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
let prodidLine = "PRODID:prodid"
versionLine = "VERSION:version"
vCalendarLines = [ prodidLine, versionLine ]
appendOnce line = vCalendarLines ++ [line]
appendTwice line = vCalendarLines ++ [line, line]
parse = parseLinesWith parseVCalendar
describe "test factory" $ do
it "should generate a valid VCalendar" $ do
shouldSucceed $ parse vCalendarLines
describe "vCalendar format" $ do
it "must contain the properties first, then any components" $ do
pendingWith "how to easily add a valid vEvent to the default lines"
describe "vCalendar properties" $ do
describe "PRODID" $ do
it "requires a product ID" $ do
shouldFail . parse $ delete prodidLine vCalendarLines
it "cannot have multiple product IDs" $ do
shouldFail . parse $ appendTwice prodidLine
it "sets the \"productId\" record field" $ do
let (Right newVCalendar) = parse vCalendarLines
productId newVCalendar `shouldBe` "prodid"
describe "VERSION" $ do
it "requries a version number" $ do
shouldFail . parse $ delete versionLine vCalendarLines
it "cannot have multiple version numbers" $ do
shouldFail . parse $ appendTwice versionLine
it "sets the \"version\" record field" $ do
let (Right newVCalendar) = parse vCalendarLines
version newVCalendar `shouldBe` "version"
describe "CALSCALE" $ do
let calscaleLine = "CALSCALE:calscale"
it "can have a single calendar scale" $ do
shouldSucceed . parse $ appendOnce calscaleLine
it "cannot have multiple calendar scales" $ do
shouldFail . parse $ appendTwice calscaleLine
context "with an unrecognized calendar scale" $ do
let (Right newVCalendar) = parse $ appendOnce calscaleLine
it "sets the \"scale\" record field to unsupported" $ do
scale newVCalendar `shouldBe` (Unsupported "calscale")
context "with a Gregorian calendar scale" $ do
let (Right newVCalendar) = parse $ appendOnce "CALSCALE:GREGORIAN"
it "sets the \"scale\" record field to Gregorian" $ do
scale newVCalendar `shouldBe` Gregorian
describe "METHOD" $ do
let methodLine = "METHOD:method"
it "can have a single method" $ do
shouldSucceed . parse $ appendOnce methodLine
it "cannot have multiple methods" $ do
shouldFail . parse $ appendTwice methodLine
it "sets the \"method\" record field" $ do
let (Right newVCalendar) = parse $ appendOnce methodLine
method newVCalendar `shouldBe` Just "method"
describe "vCalendar components" $ do
it "can have multiple vEvents" $ do
pendingWith "how to easily add a valid vEvent to the default lines"
|
Jonplussed/iCalendar
|
test/Text/ICalendar/Component/VCalendarSpec.hs
|
bsd-3-clause
| 3,121 | 0 | 21 | 792 | 732 | 332 | 400 | 67 | 1 |
{-# LANGUAGE OverloadedStrings, QuasiQuotes, TypeApplications, FlexibleContexts #-}
module Main (main) where
import Control.Monad.Trans
import Data.Int
import Data.Word
import Numeric.Natural
import Data.Scientific
import Data.Maybe
import Data.String
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import Test.QuickCheck
import Test.QuickCheck.Monadic
import Test.Framework
import Test.Framework.Providers.QuickCheck2
import qualified Database.PostgreSQL.LibPQ as P
import Database.PostgreSQL.Store.Entity
import Database.PostgreSQL.Store.Errand
import Database.PostgreSQL.Store.Query
import System.Environment
instance Arbitrary B.ByteString where
arbitrary = B.pack <$> arbitrary
shrink bs
| B.null bs = [bs]
| otherwise = B.tail bs : shrink (B.tail bs)
instance Arbitrary BL.ByteString where
arbitrary = BL.pack <$> arbitrary
shrink bs
| BL.null bs = [bs]
| otherwise = BL.tail bs : shrink (BL.tail bs)
instance Arbitrary T.Text where
arbitrary = T.pack <$> arbitrary
shrink bs
| T.null bs = [bs]
| otherwise = T.tail bs : shrink (T.tail bs)
instance Arbitrary TL.Text where
arbitrary = TL.pack <$> arbitrary
shrink bs
| TL.null bs = [bs]
| otherwise = TL.tail bs : shrink (TL.tail bs)
instance Arbitrary Scientific where
arbitrary = scientific <$> arbitrary <*> arbitrary
-- |
testEntity :: (Entity a, Eq a, Show a) => P.Connection -> a -> Property
testEntity db x = monadicIO $ do
result <- lift (runErrand db (query [pgQuery| SELECT $x |]))
elem <- case result of
Left err -> fail ("ErrandError: " ++ show err)
Right [x] -> pure x
Right xs -> fail ("Weird result: " ++ show xs)
stop (elem === x)
-- |
testEntityWith :: (Entity a, Eq a, Show a) => P.Connection -> (a -> a) -> a -> Property
testEntityWith db f x =
testEntity db (f x)
-- |
filterStringNulls :: String -> String
filterStringNulls = filter (/= '\NUL')
-- |
filterTextNulls :: T.Text -> T.Text
filterTextNulls x = T.concat (T.split (== '\NUL') x)
-- |
filterLazyTextNulls :: TL.Text -> TL.Text
filterLazyTextNulls x = TL.concat (TL.split (== '\NUL') x)
-- | Test entry point
main :: IO ()
main = do
pgInfo <- lookupEnv "PGINFO"
db <- P.connectdb (fromString (fromMaybe "user=pgstore dbname=pgstore" pgInfo))
defaultMain
[
testProperty "entity-bool" (testEntity @Bool db),
testProperty "entity-integer" (testEntity @Integer db),
testProperty "entity-int" (testEntity @Int db),
testProperty "entity-int8" (testEntity @Int8 db),
testProperty "entity-int16" (testEntity @Int16 db),
testProperty "entity-int32" (testEntity @Int32 db),
testProperty "entity-int64" (testEntity @Int64 db),
testProperty "entity-natural" (testEntity @Natural db),
testProperty "entity-word" (testEntity @Word db),
testProperty "entity-word8" (testEntity @Word8 db),
testProperty "entity-word16" (testEntity @Word16 db),
testProperty "entity-word32" (testEntity @Word32 db),
testProperty "entity-word64" (testEntity @Word64 db),
testProperty "entity-float" (testEntity @Float db),
testProperty "entity-double" (testEntity @Double db),
testProperty "entity-scientific" (testEntity @Scientific db),
testProperty "entity-bytestring" (testEntity @B.ByteString db),
testProperty "entity-bytestring-lazy" (testEntity @BL.ByteString db),
testProperty "entity-string" (testEntityWith @String db filterStringNulls),
testProperty "entity-text" (testEntityWith @T.Text db filterTextNulls),
testProperty "entity-text-lazy" (testEntityWith @TL.Text db filterLazyTextNulls)
]
|
vapourismo/pg-store
|
tests/Entities.hs
|
bsd-3-clause
| 4,002 | 48 | 15 | 942 | 1,282 | 663 | 619 | 88 | 3 |
module Main where
import qualified PureFlowy.Api as Api
main :: IO ()
main = Api.main
|
parsonsmatt/pureflowy
|
app/Main.hs
|
bsd-3-clause
| 88 | 0 | 6 | 17 | 29 | 18 | 11 | 4 | 1 |
-- |Model for mutually recursive data
module Data.Timeless.Mutual where
import ZM.Types
import Data.Word
-- Mutual recursive data types
-- Test
data Forest a = Forest (List (Tree a))
data Tree a = Tree a (Forest a)
data List a = Cons a (List a)
| Nil
type MutualADTEnv = [(MutualAbsRef,MutualAbsADT)]
type MutualAbsType = Type MutualAbsRef
-- newtype or type?
newtype MutualAbsRef = MutualAbsRef (SHA3_256_6 MutualAbsADT)
type MutualAbsADT = ADT Identifier Identifier (MutualADTRef AbsRef)
data MutualADTRef a =
Var Word8 -- Variable
| Rec String -- Recursive reference, either to the type being defined or a mutually recursive type
| Ext MutualAbsRef -- Pointer to external definition
-- Single type
data SingleRef a = SingleRef
type SingleType = Type (SingleRef Boolean)
data Boolean = And Boolean Boolean | Or Boolean Boolean | Not Boolean | True | False
-- Alternative Hash
|
tittoassini/typed
|
src/Data/Timeless/Mutual.hs
|
bsd-3-clause
| 920 | 0 | 10 | 182 | 216 | 129 | 87 | 18 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Bort.ServerMessage where
import Bort.Types
import Control.Applicative ((<$>))
import Data.Attoparsec.ByteString.Char8
import qualified Data.ByteString.Char8 as C
-- :letsbreelhere!~textual@50-205-32-182-static.hfc.comcastbusiness.net PRIVMSG ##botopia :hi
serverMessage :: [C.ByteString] -> Maybe Message
serverMessage (header:"PRIVMSG":r:body) = do
handle <- either (const Nothing) return $ parseOnly parseHandle header
return (Message handle r body')
where body' = C.tail . C.unwords $ body
serverMessage _ = Nothing
serverPing :: [C.ByteString] -> Maybe C.ByteString
serverPing ("PING":ping) = Just . C.tail . C.unwords $ ping
serverPing _ = Nothing
parseHandle :: Parser C.ByteString
parseHandle = do
_ <- char ':'
C.pack <$> many1 (notChar '!')
|
breestanwyck/bort
|
src/Bort/ServerMessage.hs
|
bsd-3-clause
| 810 | 0 | 11 | 115 | 252 | 133 | 119 | 19 | 1 |
-- Exercises/Ch2/Pt1/Ex6.hs
module Ex6 where
-- Exercise 6
-- Add a `Float` constructor to `LispVal`, and create a parser for character
-- literals as described in R5RS.
import Data.Char (digitToInt, isSpace)
import Control.Monad
import Numeric
import System.Environment
import Text.ParserCombinators.Parsec hiding (spaces)
data LispVal = Atom String
| List [LispVal]
| DottedList [LispVal] LispVal -- (a b c ... . z)
| Number Integer
| Float Float -- could use Double
| Character String
| String String
| Bool Bool
deriving Show -- debug purposes
parseCharacter :: Parser LispVal
parseCharacter = do
string "#\\"
character <- many $ satisfy $ not . isSpace
return $ Character character
parseString :: Parser LispVal
parseString = do
char '"'
-- order is important here; need to try parsing an escape sequence first because
-- otherwise we fail when we reach the second character of the escape
-- sequence
x <- many $ choice $ escChars ++ [nonQuote]
char '"'
return $ String x
where
nonQuote = noneOf "\""
-- taken from here:
-- https://en.wikipedia.org/wiki/Escape_sequences_in_C#Table_of_escape_sequences
-- (excluded characters by oct/hex codes)
escChars = [ char '\\' >> char x | x <- "abfnrtv\\'\"?" ]
parseBool :: Parser LispVal
parseBool = do
try (char '#')
v <- oneOf "tf"
return $ case v of
't' -> Bool True
'f' -> Bool False
parseAtom :: Parser LispVal
parseAtom = do
first <- letter <|> symbol
rest <- many (letter <|> digit <|> symbol)
return $ Atom (first:rest)
parseNumber :: Parser LispVal
parseNumber = (try parseBin) <|> (try parseOct) <|> (try parseHex) <|> (try parseFlt) <|> parseDec
where
parseBin = do
string "#b"
binStr <- many1 $ oneOf "01"
-- cribbed from http://stackoverflow.com/a/26961027/1893155
let binVal = foldl (\acc x -> acc * 2 + digitToInt x) 0 binStr
return $ Number (toInteger binVal)
parseOct = do
string "#o"
octStr <- many1 octDigit
let octVal = fst $ (readOct octStr) !! 0
return $ Number octVal
parseDec = parseDecNoPre <|> parseDecPre
parseDecNoPre = do
decStr <- many1 digit
return $ (Number . read) decStr
parseDecPre = do
string "#d"
decStr <- many1 digit
return $ (Number . read) decStr
parseHex = do
string "#x"
hexStr <- many1 hexDigit
let hexVal = fst $ (readHex hexStr) !! 0
return $ Number hexVal
parseFlt = do
whole <- many1 digit
string "."
part <- many1 digit
let fltVal = fst $ (readFloat (whole ++ "." ++ part) !! 0)
return $ Float $ fltVal
-- TODO : I don't like all these `try`s -- better way to do this?
parseExpr :: Parser LispVal
parseExpr = (try parseNumber)
<|> (try parseString)
<|> (try parseCharacter)
<|> (try parseBool)
<|> (try parseAtom)
symbol :: Parser Char
symbol = oneOf "!$%&|*+-/:<=>?@^_~"
spaces :: Parser ()
spaces = skipMany1 space
readExpr :: String -> String
readExpr input = case parse parseExpr "lisp" input of
Left err -> "No match: " ++ show err
Right val -> "Found value"
main :: IO ()
main = do
(expr:_) <- getArgs
putStrLn (readExpr expr)
|
EFulmer/haskell-scheme-wikibook
|
src/Exercises/Ch2/Pt1/Ex6.hs
|
bsd-3-clause
| 3,391 | 0 | 18 | 957 | 962 | 476 | 486 | 89 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE CPP #-}
module Game.Pal.Window where
import Graphics.UI.GLFW.Pal
import Graphics.VR.OpenVR
import Control.Monad
import System.Hardware.Hydra
import Control.Monad.Trans
import Linear.Extra
import Game.Pal.View
import Game.Pal.Types
import Graphics.GL.Pal
import System.Mem
import Data.Time
import Data.IORef
#ifdef USE_OCULUS_SDK
import Graphics.Oculus
#endif
initGamePal :: String -> GCPerFrame -> [GamePalDevices] -> IO GamePal
initGamePal windowName gcPerFrame devices = do
maybeSixenseBase <- if UseHydra `elem` devices then Just <$> initSixense else return Nothing
let (resX, resY) = (2000, 1000)
(window, events) <- createWindow windowName resX resY
swapInterval 0
hmdType <- if
| UseOpenVR `elem` devices -> do
mOpenVR <- createOpenVR
case mOpenVR of
Just openVR -> do
forM_ (ovrEyes openVR) $ \eye -> case eiEye eye of
LeftEye -> do
let (_, _, w, h) = eiViewport eye
setWindowSize window (fromIntegral w) (fromIntegral h)
_ -> return ()
return (OpenVRHMD openVR)
#ifdef USE_OCULUS_SDK
| UseOculus `elem` devices && oculusSupported -> do
hmd <- createHMD
setWindowSize window
(fromIntegral . fst . hmdBufferSize $ hmd)
(fromIntegral . snd . hmdBufferSize $ hmd)
return (OculusHMD hmd)
#endif
| otherwise -> return NoHMD
getDelta <- makeGetDelta
return $ GamePal
{ gpWindow = window
, gpEvents = events
, gpHMD = hmdType
, gpSixenseBase = maybeSixenseBase
, gpGetDelta = getDelta
, gpGCPerFrame = gcPerFrame
}
renderWith :: MonadIO m
=> GamePal
-> M44 GLfloat
-> m ()
-> (M44 GLfloat -> M44 GLfloat -> m b)
-> m ()
renderWith GamePal{..} viewMat frameRenderFunc eyeRenderFunc = do
case gpHMD of
NoHMD -> do
frameRenderFunc
renderFlat gpWindow viewMat eyeRenderFunc
OpenVRHMD openVR -> do
renderOpenVR openVR viewMat frameRenderFunc eyeRenderFunc
#ifdef USE_OCULUS_SDK
OculusHMD hmd -> do
renderOculus hmd viewMat frameRenderFunc eyeRenderFunc
renderHMDMirror hmd
#endif
-- We always call swapBuffers since mirroring is handled manually in 0.6+ and OpenVR
swapBuffers gpWindow
when (gpGCPerFrame == GCPerFrame) $
liftIO performGC
renderOpenVR OpenVR{..} viewMat frameRenderFunc eyeRenderFunc = do
headPose <- safeInv44 <$> waitGetPoses ovrCompositor
forM_ ovrEyes $ \eye@EyeInfo{..} -> do
withFramebuffer eiFramebuffer $ do
frameRenderFunc
let (x, y, w, h) = eiViewport
finalView = eiEyeHeadTrans !*! headPose !*! viewMat
glViewport x y w h
eyeRenderFunc eiProjection finalView
submitFrameForEye ovrCompositor eiEye eiFramebufferTexture
mirrorOpenVREyeToWindow eye
renderFlat :: MonadIO m
=> Window -> M44 GLfloat -> (M44 GLfloat -> M44 GLfloat -> m b) -> m ()
renderFlat win viewMat renderFunc = do
projection <- makeProjection win
_ <- renderFunc projection viewMat
return ()
makeGetDelta :: IO (IO NominalDiffTime)
makeGetDelta = do
start <- getCurrentTime
timeRef <- newIORef start
let getDelta = do
lastTime <- readIORef timeRef
currTime <- getCurrentTime
let diffTime = diffUTCTime currTime lastTime
writeIORef timeRef currTime
return diffTime
return getDelta
getPoseForHMDType hmdType = case hmdType of
OpenVRHMD openVR -> do
poses <- getDevicePosesOfClass (ovrSystem openVR) TrackedDeviceClassHMD
return $ if not (null poses) then head poses else identity
NoHMD -> return identity
#ifdef USE_OCULUS_SDK
OculusHMD hmd -> liftIO . getHMDPose . hmdInfo $ hmd
#endif
recenterWhenOculus gamePal = case gpHMD gamePal of
#ifdef USE_OCULUS_SDK
OculusHMD hmd -> liftIO $ recenterPose hmd
#endif
_ -> return ()
#ifdef USE_OCULUS_SDK
renderOculus :: MonadIO m
=> HMD
-> M44 GLfloat
-> m ()
-> (M44 GLfloat -> M44 GLfloat -> m b) -> m ()
renderOculus hmd viewMat frameRenderFunc eyeRenderFunc = renderHMDFrame hmd $ \eyeViews -> do
frameRenderFunc
renderHMDEyes eyeViews $ \projection eyeView -> do
let finalView = eyeView !*! viewMat
eyeRenderFunc projection finalView
#endif
|
cabbibo/loom-haskell
|
src/Game/Pal/Window.hs
|
bsd-3-clause
| 4,489 | 0 | 27 | 1,169 | 1,278 | 622 | 656 | 94 | 4 |
{-# language CPP #-}
-- | = Name
--
-- VK_KHR_dedicated_allocation - device extension
--
-- == VK_KHR_dedicated_allocation
--
-- [__Name String__]
-- @VK_KHR_dedicated_allocation@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
-- 128
--
-- [__Revision__]
-- 3
--
-- [__Extension and Version Dependencies__]
--
-- - Requires Vulkan 1.0
--
-- - Requires @VK_KHR_get_memory_requirements2@
--
-- [__Deprecation state__]
--
-- - /Promoted/ to
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#versions-1.1-promotions Vulkan 1.1>
--
-- [__Contact__]
--
-- - James Jones
-- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_dedicated_allocation] @cubanismo%0A<<Here describe the issue or question you have about the VK_KHR_dedicated_allocation extension>> >
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
-- 2017-09-05
--
-- [__IP Status__]
-- No known IP claims.
--
-- [__Interactions and External Dependencies__]
--
-- - Promoted to Vulkan 1.1 Core
--
-- [__Contributors__]
--
-- - Jeff Bolz, NVIDIA
--
-- - Jason Ekstrand, Intel
--
-- == Description
--
-- This extension enables resources to be bound to a dedicated allocation,
-- rather than suballocated. For any particular resource, applications
-- /can/ query whether a dedicated allocation is recommended, in which case
-- using a dedicated allocation /may/ improve the performance of access to
-- that resource. Normal device memory allocations must support multiple
-- resources per allocation, memory aliasing and sparse binding, which
-- could interfere with some optimizations. Applications should query the
-- implementation for when a dedicated allocation /may/ be beneficial by
-- adding a 'MemoryDedicatedRequirementsKHR' structure to the @pNext@ chain
-- of the
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_memory_requirements2.MemoryRequirements2'
-- structure passed as the @pMemoryRequirements@ parameter of a call to
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_memory_requirements2.getBufferMemoryRequirements2'
-- or
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_memory_requirements2.getImageMemoryRequirements2'.
-- Certain external handle types and external images or buffers /may/ also
-- depend on dedicated allocations on implementations that associate image
-- or buffer metadata with OS-level memory objects.
--
-- This extension adds a two small structures to memory requirements
-- querying and memory allocation: a new structure that flags whether an
-- image\/buffer should have a dedicated allocation, and a structure
-- indicating the image or buffer that an allocation will be bound to.
--
-- == Promotion to Vulkan 1.1
--
-- All functionality in this extension is included in core Vulkan 1.1, with
-- the KHR suffix omitted. The original type, enum and command names are
-- still available as aliases of the core functionality.
--
-- == New Structures
--
-- - Extending 'Vulkan.Core10.Memory.MemoryAllocateInfo':
--
-- - 'MemoryDedicatedAllocateInfoKHR'
--
-- - Extending
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_memory_requirements2.MemoryRequirements2':
--
-- - 'MemoryDedicatedRequirementsKHR'
--
-- == New Enum Constants
--
-- - 'KHR_DEDICATED_ALLOCATION_EXTENSION_NAME'
--
-- - 'KHR_DEDICATED_ALLOCATION_SPEC_VERSION'
--
-- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType':
--
-- - 'STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR'
--
-- - 'STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR'
--
-- == Examples
--
-- > // Create an image with a dedicated allocation based on the
-- > // implementation's preference
-- >
-- > VkImageCreateInfo imageCreateInfo =
-- > {
-- > // Image creation parameters
-- > };
-- >
-- > VkImage image;
-- > VkResult result = vkCreateImage(
-- > device,
-- > &imageCreateInfo,
-- > NULL, // pAllocator
-- > &image);
-- >
-- > VkMemoryDedicatedRequirementsKHR dedicatedRequirements =
-- > {
-- > VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR,
-- > NULL, // pNext
-- > };
-- >
-- > VkMemoryRequirements2 memoryRequirements =
-- > {
-- > VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
-- > &dedicatedRequirements, // pNext
-- > };
-- >
-- > const VkImageMemoryRequirementsInfo2 imageRequirementsInfo =
-- > {
-- > VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
-- > NULL, // pNext
-- > image
-- > };
-- >
-- > vkGetImageMemoryRequirements2(
-- > device,
-- > &imageRequirementsInfo,
-- > &memoryRequirements);
-- >
-- > if (dedicatedRequirements.prefersDedicatedAllocation) {
-- > // Allocate memory with VkMemoryDedicatedAllocateInfoKHR::image
-- > // pointing to the image we are allocating the memory for
-- >
-- > VkMemoryDedicatedAllocateInfoKHR dedicatedInfo =
-- > {
-- > VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR, // sType
-- > NULL, // pNext
-- > image, // image
-- > VK_NULL_HANDLE, // buffer
-- > };
-- >
-- > VkMemoryAllocateInfo memoryAllocateInfo =
-- > {
-- > VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, // sType
-- > &dedicatedInfo, // pNext
-- > memoryRequirements.size, // allocationSize
-- > FindMemoryTypeIndex(memoryRequirements.memoryTypeBits), // memoryTypeIndex
-- > };
-- >
-- > VkDeviceMemory memory;
-- > vkAllocateMemory(
-- > device,
-- > &memoryAllocateInfo,
-- > NULL, // pAllocator
-- > &memory);
-- >
-- > // Bind the image to the memory
-- >
-- > vkBindImageMemory(
-- > device,
-- > image,
-- > memory,
-- > 0);
-- > } else {
-- > // Take the normal memory sub-allocation path
-- > }
--
-- == Version History
--
-- - Revision 1, 2017-02-27 (James Jones)
--
-- - Copy content from VK_NV_dedicated_allocation
--
-- - Add some references to external object interactions to the
-- overview.
--
-- - Revision 2, 2017-03-27 (Jason Ekstrand)
--
-- - Rework the extension to be query-based
--
-- - Revision 3, 2017-07-31 (Jason Ekstrand)
--
-- - Clarify that memory objects allocated with
-- VkMemoryDedicatedAllocateInfoKHR can only have the specified
-- resource bound and no others.
--
-- == See Also
--
-- 'MemoryDedicatedAllocateInfoKHR', 'MemoryDedicatedRequirementsKHR'
--
-- == Document Notes
--
-- For more information, see the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_KHR_dedicated_allocation Vulkan Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module Vulkan.Extensions.VK_KHR_dedicated_allocation ( pattern STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR
, pattern STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR
, MemoryDedicatedRequirementsKHR
, MemoryDedicatedAllocateInfoKHR
, KHR_DEDICATED_ALLOCATION_SPEC_VERSION
, pattern KHR_DEDICATED_ALLOCATION_SPEC_VERSION
, KHR_DEDICATED_ALLOCATION_EXTENSION_NAME
, pattern KHR_DEDICATED_ALLOCATION_EXTENSION_NAME
) where
import Data.String (IsString)
import Vulkan.Core11.Promoted_From_VK_KHR_dedicated_allocation (MemoryDedicatedAllocateInfo)
import Vulkan.Core11.Promoted_From_VK_KHR_dedicated_allocation (MemoryDedicatedRequirements)
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS))
-- No documentation found for TopLevel "VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR"
pattern STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR = STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS
-- No documentation found for TopLevel "VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR"
pattern STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR = STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO
-- No documentation found for TopLevel "VkMemoryDedicatedRequirementsKHR"
type MemoryDedicatedRequirementsKHR = MemoryDedicatedRequirements
-- No documentation found for TopLevel "VkMemoryDedicatedAllocateInfoKHR"
type MemoryDedicatedAllocateInfoKHR = MemoryDedicatedAllocateInfo
type KHR_DEDICATED_ALLOCATION_SPEC_VERSION = 3
-- No documentation found for TopLevel "VK_KHR_DEDICATED_ALLOCATION_SPEC_VERSION"
pattern KHR_DEDICATED_ALLOCATION_SPEC_VERSION :: forall a . Integral a => a
pattern KHR_DEDICATED_ALLOCATION_SPEC_VERSION = 3
type KHR_DEDICATED_ALLOCATION_EXTENSION_NAME = "VK_KHR_dedicated_allocation"
-- No documentation found for TopLevel "VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME"
pattern KHR_DEDICATED_ALLOCATION_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern KHR_DEDICATED_ALLOCATION_EXTENSION_NAME = "VK_KHR_dedicated_allocation"
|
expipiplus1/vulkan
|
src/Vulkan/Extensions/VK_KHR_dedicated_allocation.hs
|
bsd-3-clause
| 9,935 | 0 | 8 | 2,481 | 430 | 348 | 82 | -1 | -1 |
import System.Cmd
import System.Environment
import Control.Monad
import System.FilePath
main :: IO ()
main = do
fps <- getArgs
forM fps $ \fp -> do
rawSystem "md5sum" [fp]
rawSystem "md5sum" [outFilePath fp]
putStrLn ""
return ()
outFilePath infp =
takeDirectory infp `combine` "out" `combine` takeFileName infp
|
YoshikuniJujo/iccp-file
|
tools/showmd5.hs
|
bsd-3-clause
| 324 | 2 | 13 | 57 | 125 | 61 | 64 | 14 | 1 |
-- |
-- Statistics for per-module compilations
--
-- (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
--
module HscStats ( ppSourceStats ) where
import Bag
import HsSyn
import Outputable
import RdrName
import SrcLoc
import Util
import Data.Char
-- | Source Statistics
ppSourceStats :: Bool -> Located (HsModule RdrName) -> SDoc
ppSourceStats short (L _ (HsModule _ exports imports ldecls _ _))
= (if short then hcat else vcat)
(map pp_val
[("ExportAll ", export_all), -- 1 if no export list
("ExportDecls ", export_ds),
("ExportModules ", export_ms),
("Imports ", imp_no),
(" ImpSafe ", imp_safe),
(" ImpQual ", imp_qual),
(" ImpAs ", imp_as),
(" ImpAll ", imp_all),
(" ImpPartial ", imp_partial),
(" ImpHiding ", imp_hiding),
("FixityDecls ", fixity_sigs),
("DefaultDecls ", default_ds),
("TypeDecls ", type_ds),
("DataDecls ", data_ds),
("NewTypeDecls ", newt_ds),
("TypeFamilyDecls ", type_fam_ds),
("DataConstrs ", data_constrs),
("DataDerivings ", data_derivs),
("ClassDecls ", class_ds),
("ClassMethods ", class_method_ds),
("DefaultMethods ", default_method_ds),
("InstDecls ", inst_ds),
("InstMethods ", inst_method_ds),
("InstType ", inst_type_ds),
("InstData ", inst_data_ds),
("TypeSigs ", bind_tys),
("GenericSigs ", generic_sigs),
("ValBinds ", val_bind_ds),
("FunBinds ", fn_bind_ds),
("InlineMeths ", method_inlines),
("InlineBinds ", bind_inlines),
("SpecialisedMeths ", method_specs),
("SpecialisedBinds ", bind_specs)
])
where
decls = map unLoc ldecls
pp_val (_, 0) = empty
pp_val (str, n)
| not short = hcat [text str, int n]
| otherwise = hcat [text (trim str), equals, int n, semi]
trim ls = takeWhile (not.isSpace) (dropWhile isSpace ls)
(fixity_sigs, bind_tys, bind_specs, bind_inlines, generic_sigs)
= count_sigs [d | SigD d <- decls]
-- NB: this omits fixity decls on local bindings and
-- in class decls. ToDo
tycl_decls = [d | TyClD d <- decls]
(class_ds, type_ds, data_ds, newt_ds, type_fam_ds) =
countTyClDecls tycl_decls
inst_decls = [d | InstD d <- decls]
inst_ds = length inst_decls
default_ds = count (\ x -> case x of { DefD{} -> True; _ -> False}) decls
val_decls = [d | ValD d <- decls]
real_exports = case exports of { Nothing -> []; Just es -> es }
n_exports = length real_exports
export_ms = count (\ e -> case unLoc e of { IEModuleContents{} -> True;_ -> False})
real_exports
export_ds = n_exports - export_ms
export_all = case exports of { Nothing -> 1; _ -> 0 }
(val_bind_ds, fn_bind_ds)
= foldr add2 (0,0) (map count_bind val_decls)
(imp_no, imp_safe, imp_qual, imp_as, imp_all, imp_partial, imp_hiding)
= foldr add7 (0,0,0,0,0,0,0) (map import_info imports)
(data_constrs, data_derivs)
= foldr add2 (0,0) (map data_info tycl_decls)
(class_method_ds, default_method_ds)
= foldr add2 (0,0) (map class_info tycl_decls)
(inst_method_ds, method_specs, method_inlines, inst_type_ds, inst_data_ds)
= foldr add5 (0,0,0,0,0) (map inst_info inst_decls)
count_bind (PatBind { pat_lhs = L _ (VarPat _) }) = (1,0)
count_bind (PatBind {}) = (0,1)
count_bind (FunBind {}) = (0,1)
count_bind b = pprPanic "count_bind: Unhandled binder" (ppr b)
count_sigs sigs = foldr add5 (0,0,0,0,0) (map sig_info sigs)
sig_info (FixSig _) = (1,0,0,0,0)
sig_info (TypeSig _ _) = (0,1,0,0,0)
sig_info (SpecSig _ _ _) = (0,0,1,0,0)
sig_info (InlineSig _ _) = (0,0,0,1,0)
sig_info (GenericSig _ _) = (0,0,0,0,1)
sig_info _ = (0,0,0,0,0)
import_info (L _ (ImportDecl { ideclSafe = safe, ideclQualified = qual
, ideclAs = as, ideclHiding = spec }))
= add7 (1, safe_info safe, qual_info qual, as_info as, 0,0,0) (spec_info spec)
safe_info = qual_info
qual_info False = 0
qual_info True = 1
as_info Nothing = 0
as_info (Just _) = 1
spec_info Nothing = (0,0,0,0,1,0,0)
spec_info (Just (False, _)) = (0,0,0,0,0,1,0)
spec_info (Just (True, _)) = (0,0,0,0,0,0,1)
data_info (TyDecl { tcdTyDefn = TyData {td_cons = cs, td_derivs = derivs}})
= (length cs, case derivs of Nothing -> 0
Just ds -> length ds)
data_info _ = (0,0)
class_info decl@(ClassDecl {})
= case count_sigs (map unLoc (tcdSigs decl)) of
(_,classops,_,_,_) ->
(classops, addpr (foldr add2 (0,0) (map (count_bind.unLoc) (bagToList (tcdMeths decl)))))
class_info _ = (0,0)
inst_info (FamInstD { lid_inst = d })
= case countATDecl d of
(tyd, dtd) -> (0,0,0,tyd,dtd)
inst_info (ClsInstD { cid_binds = inst_meths, cid_sigs = inst_sigs, cid_fam_insts = ats })
= case count_sigs (map unLoc inst_sigs) of
(_,_,ss,is,_) ->
case foldr add2 (0, 0) (map (countATDecl . unLoc) ats) of
(tyDecl, dtDecl) ->
(addpr (foldr add2 (0,0)
(map (count_bind.unLoc) (bagToList inst_meths))),
ss, is, tyDecl, dtDecl)
where
countATDecl (FamInstDecl { fid_defn = TyData {} }) = (0, 1)
countATDecl (FamInstDecl { fid_defn = TySynonym {} }) = (1, 0)
addpr :: (Int,Int) -> Int
add2 :: (Int,Int) -> (Int,Int) -> (Int, Int)
add5 :: (Int,Int,Int,Int,Int) -> (Int,Int,Int,Int,Int) -> (Int, Int, Int, Int, Int)
add7 :: (Int,Int,Int,Int,Int,Int,Int) -> (Int,Int,Int,Int,Int,Int,Int) -> (Int, Int, Int, Int, Int, Int, Int)
addpr (x,y) = x+y
add2 (x1,x2) (y1,y2) = (x1+y1,x2+y2)
add5 (x1,x2,x3,x4,x5) (y1,y2,y3,y4,y5) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5)
add7 (x1,x2,x3,x4,x5,x6,x7) (y1,y2,y3,y4,y5,y6,y7) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5,x6+y6,x7+y7)
|
nomeata/ghc
|
compiler/main/HscStats.hs
|
bsd-3-clause
| 6,587 | 0 | 20 | 2,154 | 2,486 | 1,446 | 1,040 | 128 | 24 |
module Main where
import BeanParser
import System.Environment
import Data.List.Split
import Data.Maybe
-- id=someidentifier;class=somdidentifier
queryKeyValuePairs :: String -> Maybe [(String, String)]
queryKeyValuePairs s
| all (\x -> length x == 2) l = Just $ map (\a -> (head a, a!!1)) l
| otherwise = Nothing
where l = map (splitOn "=") $ splitOn ";" $ filter (/=' ') s
-- dataSource.appName;xxx.xxx.xxx;xxx
keypathList :: String -> [[String]]
keypathList s = map (splitOn ".") $ splitOn ";" $ filter (/=' ') s
helpMessage :: String
helpMessage = unlines ["HBeanParser [Bean XML Path] [Bean Identify Key Value Pairs] [Query Key Paths]"
,"Example:"
,"hbeanparser path_to_bean_xml_file.xml id=some_kind_of_id;class=some_kind_of_class dataSource.appName;dataLocation.appConf"]
errorMessage :: String
errorMessage = unlines ["Please make sure your input is valid", helpMessage]
processArgs :: [String] -> Maybe ([(String, String)], [[String]])
processArgs [bi, kp]
| isNothing kv || null kpl = Nothing
| otherwise = Just (fromJust kv, kpl)
where kv = queryKeyValuePairs bi
kpl = keypathList kp
processArgs s = Nothing
main :: IO ()
main = do
(path:xs) <- getArgs
-- putStrLn $ show $ processArgs xs
case processArgs xs of Just (kv,kpl) -> startParse path kv kpl
Nothing -> putStrLn errorMessage
|
chainone/HBeanParser
|
app/Main.hs
|
bsd-3-clause
| 1,515 | 0 | 12 | 408 | 432 | 228 | 204 | 30 | 2 |
-- |
-- Module : $Header$
-- Copyright : (c) 2013-2014 Galois, Inc.
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
module Cryptol.Prims.Types (typeOf) where
import Cryptol.Prims.Syntax
import Cryptol.TypeCheck.AST
import Cryptol.Utils.Panic(panic)
-- | Types of built-in constants.
typeOf :: ECon -> Schema
typeOf econ =
case econ of
ECTrue -> Forall [] [] tBit
ECFalse -> Forall [] [] tBit
-- {at,len} (fin len) => [len][8] -> at
ECError ->
let aT = var 0 KType
len = var 1 KNum
in forAllNamed [ (Just "at", aT), (Just "len",len) ]
[ pFin len ]
(tSeq len (tWord (tNum (8::Int))) `tFun` aT)
-- Infinite word sequences
-- {a} (fin a) => [a] -> [inf][a]
ECInfFrom ->
let bits = var 0 KNum
in forAllNamed [ (Just "bits", bits) ]
[ pFin bits ]
(tWord bits `tFun` tSeq tInf (tWord bits))
-- {a} (fin a) => [a] -> [a] -> [inf][a]
ECInfFromThen ->
let bits = var 0 KNum
in forAllNamed [ (Just "bits", bits) ]
[ pFin bits ]
(tWord bits `tFun` tWord bits `tFun` tSeq tInf (tWord bits))
-- Static word sequences
-- fromThen : {first,next,bits}
-- ( fin first, fin next, fin bits
-- , bits >= width first, bits >= width next
-- , lengthFromThen first next bits == len
-- )
-- => [len] [bits]
ECFromThen ->
let first = var 0 KNum
next = var 1 KNum
bits = var 3 KNum
len = var 4 KNum
in forAllNamed [ (Just "first", first)
, (Just "next", next)
, (Just "bits", bits)
, (Just "len", len)
]
[ pFin first, pFin next, pFin bits
, bits >== tWidth first, bits >== tWidth next
, tLenFromThen first next bits =#= len
]
(tSeq len (tWord bits))
{- { first, last, bits }
(fin last, fin bits, last >= first, bits >= width last)
=> [1 + (last - first)] [bits]
-}
ECFromTo ->
let first = var 0 KNum
lst = var 1 KNum
bits = var 3 KNum
in forAllNamed [ (Just "first", first)
, (Just "last", lst)
, (Just "bits", bits)
]
[ pFin lst, pFin bits, lst >== first, bits >== tWidth lst ]
(tSeq (tNum (1 :: Int) .+. (lst .-. first)) (tWord bits))
ECFromThenTo ->
let first = var 0 KNum
next = var 1 KNum
lst = var 2 KNum
bits = var 4 KNum
len = var 5 KNum
in forAllNamed [ (Just "first", first)
, (Just "next", next)
, (Just "last", lst)
, (Just "bits", bits)
, (Just "len", len)
]
[ pFin first, pFin next, pFin lst, pFin bits
, bits >== tWidth first, bits >== tWidth next, bits >== tWidth lst
, tLenFromThenTo first next lst =#= len
]
(tSeq len (tWord bits))
-- { val, bits } (fin val, fin bits, bits >= width val) => [bits]
ECDemote ->
let val = var 0 KNum
bits = var 1 KNum
in forAllNamed [ (Just "val", val), (Just "bits", bits) ]
[ pFin val, pFin bits, bits >== tWidth val ] (tWord bits)
-- Polynomials
-- {a,b} (fin a, fin b) => [a] -> [b] -> [max 1 (a + b) - 1]
ECPMul ->
let a = var 0 KNum
b = var 1 KNum
in forAllNamed [ (Nothing, a), (Nothing, b) ]
[ pFin a, pFin b ]
$ tWord a `tFun` tWord b `tFun`
tWord (tMax (tNum (1::Int)) (a .+. b) .-. tNum (1::Int))
-- {a,b} (fin a, fin b) => [a] -> [b] -> [a]
ECPDiv ->
let a = var 0 KNum
b = var 1 KNum
in forAllNamed [ (Nothing, a), (Nothing, b) ]
[ pFin a, pFin b ]
$ tWord a `tFun` tWord b `tFun` tWord a
-- {a,b} (fin a, fin b) => [a] -> [b+1] -> [b]
ECPMod ->
let a = var 0 KNum
b = var 1 KNum
in forAllNamed [ (Nothing, a), (Nothing, b) ]
[ pFin a, pFin b ]
$ tWord a `tFun` tWord (tNum (1::Int) .+. b) `tFun` tWord b
-- Arith
ECPlus -> arith2
ECMinus -> arith2
ECMul -> arith2
ECDiv -> arith2
ECMod -> arith2
ECExp -> arith2
ECLg2 -> arith1
ECNeg -> arith1
-- Cmp
ECLt -> rel2
ECGt -> rel2
ECLtEq -> rel2
ECGtEq -> rel2
ECEq -> rel2
ECNotEq -> rel2
ECFunEq -> cmpFun
ECFunNotEq -> cmpFun
ECMin -> cmp2
ECMax -> cmp2
-- Logic
ECAnd -> logic2
ECOr -> logic2
ECXor -> logic2
ECCompl -> logic1
ECZero -> logic0
ECShiftL -> logicShift
ECShiftR -> logicShift
ECRotL -> logicRot
ECRotR -> logicRot
-- {a,b,c} (fin b) => [a][b]c -> [a * b]c
ECJoin ->
let parts = var 0 KNum
each = var 1 KNum
a = var 2 KType
in forAllNamed
[ (Just "parts", parts)
, (Just "each", each)
, (Nothing, a)
]
[ pFin each ]
$ tSeq parts (tSeq each a) `tFun` tSeq (parts .*. each) a
-- {a,b,c} (fin b) => [a * b] c -> [a][b] c
ECSplit ->
let parts = var 0 KNum
each = var 1 KNum
a = var 2 KType
in forAllNamed
[ (Just "parts", parts)
, (Just "each", each)
, (Nothing, a)
]
[ pFin each ]
$ tSeq (parts .*. each) a `tFun` tSeq parts (tSeq each a)
-- {a,b} (fin a) => [a] b -> [a] b
ECReverse ->
let a = var 0 KNum
b = var 1 KType
in forAllNamed [ (Nothing, a), (Nothing, b) ]
[ pFin a ]
(tSeq a b `tFun` tSeq a b)
-- {a,b,c} [a][b]c -> [b][a]c
ECTranspose ->
let a = var 0 KNum
b = var 1 KNum
c = var 2 KType
in forAllNamed [ (Nothing, a), (Nothing, b), (Nothing, c) ]
[]
(tSeq a (tSeq b c) `tFun` tSeq b (tSeq a c))
-- Sequence selectors
ECAt ->
let n = var 0 KNum
a = var 1 KType
i = var 2 KNum
in forAll [n,a,i] [ pFin i ] (tSeq n a `tFun` tWord i `tFun` a)
ECAtRange ->
let n = var 0 KNum
a = var 1 KType
m = var 2 KNum
i = var 3 KNum
in forAll [n,a,m,i] [ pFin i ]
(tSeq n a `tFun` tSeq m (tWord i) `tFun` tSeq m a)
ECAtBack ->
let n = var 0 KNum
a = var 1 KType
i = var 2 KNum
in forAll [n,a,i] [ pFin n, pFin i ] (tSeq n a `tFun` tWord i `tFun` a)
ECAtRangeBack ->
let n = var 0 KNum
a = var 1 KType
m = var 2 KNum
i = var 3 KNum
in forAll [n,a,m,i] [ pFin n, pFin i ]
(tSeq n a `tFun` tSeq m (tWord i) `tFun` tSeq m a)
-- {a,b,c} (fin a) => [a+b] c -> ([a]c,[b]c)
ECSplitAt ->
let front = var 0 KNum
back = var 1 KNum
a = var 2 KType
in forAllNamed
[ (Just "front", front)
, (Just "back", back)
, (Nothing, a)
] [ pFin front ]
$ tSeq (front .+. back) a `tFun` tTuple [tSeq front a, tSeq back a]
-- {a,b,d} (fin a) => [a] d -> [b] d -> [a + b] d
ECCat ->
let a = var 0 KNum
b = var 1 KNum
d = var 3 KType
in forAllNamed [ (Just "front", a)
, (Just "back" , b)
, (Nothing,d)
] [ pFin a ]
$ tSeq a d `tFun` tSeq b d `tFun` tSeq (a .+. b) d
-- {a} => [32] -> a
ECRandom ->
let a = var 0 KType
in forAll [a] [] (tWord (tNum (32 :: Int)) `tFun` a)
where
var x k = TVar (TVBound x k)
toTP (mb,TVar (TVBound x k)) = TParam { tpName = fmap (mkUnqual . Name) mb
, tpUnique = x, tpKind = k }
toTP (_,x) = panic "Cryptol.Prims.Types.typeOf"
[ "Not TBound", show x ]
forAllNamed xs ys p = Forall (map toTP xs) ys p
forAll xs = forAllNamed (zip (repeat Nothing) xs)
-- {a} (Arith a) => a -> a -> a
arith2 = let a = var 0 KType
in forAll [a] [ pArith a ] $ a `tFun` a `tFun` a
-- {a} (Arith a) => a -> a
arith1 = let a = var 0 KType
in forAll [a] [ pArith a ] $ a `tFun` a
-- {a} (Cmp a) => a -> a -> Bit
rel2 = let a = var 0 KType
in forAll [a] [ pCmp a ] $ a `tFun` a `tFun` tBit
-- {a} (Cmp a) => a -> a -> a
cmp2 = let a = var 0 KType
in forAll [a] [ pCmp a ] $ a `tFun` a `tFun` a
-- {a b} (Cmp b) => (a -> b) -> (a -> b) -> a -> Bit
cmpFun = let a = var 0 KType
b = var 1 KType
in forAll [a,b] [ pCmp b ]
$ (a `tFun` b) `tFun` (a `tFun` b) `tFun` a `tFun` tBit
-- {a} a
logic0 = let a = var 0 KType
in forAll [a] [] a
-- {a} a -> a
logic1 = let a = var 0 KType
in forAll [a] [] (a `tFun` a)
-- {a} a -> a -> a
logic2 = let a = var 0 KType
in forAll [a] [] (a `tFun` a `tFun` a)
-- {m,n,a} (fin n) => [m] a -> [n] -> [m] a
logicShift = let m = var 0 KNum
n = var 1 KNum
a = var 2 KType
in forAll [m,n,a] [pFin n]
$ tSeq m a `tFun` tWord n `tFun` tSeq m a
-- {m,n,a} (fin n, fin m) => [m] a -> [n] -> [m] a
logicRot = let m = var 0 KNum
n = var 1 KNum
a = var 2 KType
in forAll [m,n,a] [pFin m, pFin n]
$ tSeq m a `tFun` tWord n `tFun` tSeq m a
|
TomMD/cryptol
|
src/Cryptol/Prims/Types.hs
|
bsd-3-clause
| 10,070 | 0 | 18 | 4,343 | 3,419 | 1,801 | 1,618 | 227 | 51 |
module LaTeXGrapher.Data.Markup
(
Markup(..)
, isView
, isLabel
) where
import LaTeXGrapher.Data.Function
import LaTeXGrapher.Data.Expression
data Markup = View [EPoint]
| Label EPoint String
| Points [EPoint]
| Line [EPoint]
| Segment [EPoint]
| Secant String Expr Expr
| Tangent String Expr
| Shade String Expr Expr
deriving (Show)
isView :: Markup -> Bool
isView (View _) = True
isView _ = False
isLabel :: Markup -> Bool
isLabel (Label _ _) = True
isLabel _ = False
|
fryguybob/LaTeXGrapher
|
src/LaTeXGrapher/Data/Markup.hs
|
bsd-3-clause
| 611 | 0 | 7 | 218 | 173 | 100 | 73 | 22 | 1 |
module Language.Lambda.Syntax.Named.Parser
(
expression
, exprP
) where
{-
=== Grammar
<expr> = <variable>
| <expr> <expr>
| \<var>.<expr>
| let <expr> in <expr>
| (<expr>)
Todo: constants (Integers, Chars, Strings, ...)
-}
import Control.Applicative
import qualified Text.Parsec as P
import qualified Text.Parsec.String as S
import Text.Parsec.Language as L
import qualified Text.Parsec.Token as T
import Language.Lambda.Syntax.Named.Exp
lexer :: T.TokenParser ()
lexer = T.makeTokenParser style
where
keys = ["let", "in"]
ops = ["\\", "λ", ".", ";", "="]
style = emptyDef
{ T.reservedNames = keys
, T.reservedOpNames = ops
, T.identStart = P.alphaNum <|> P.char '_'
, T.identLetter = P.alphaNum <|> P.char '_'
, T.commentLine = "--"
, T.commentStart = "{-"
, T.commentEnd = "-}"
}
parens :: S.Parser a -> S.Parser a
parens = T.parens lexer
dot :: S.Parser String
dot = T.dot lexer
reserved :: String -> S.Parser ()
reserved = T.reserved lexer
reservedOp :: String -> S.Parser ()
reservedOp = T.reservedOp lexer
identifier :: S.Parser String
identifier = T.identifier lexer
whiteSpace :: S.Parser ()
whiteSpace = T.whiteSpace lexer
variableP :: S.Parser (Exp String)
variableP = Var <$> identifier
atomP :: S.Parser (Exp String)
atomP = variableP <|> parens exprP
appP :: S.Parser (Exp String)
appP = atomP `P.chainl1` pure App
lamP :: S.Parser (Exp String)
lamP = do
reservedOp "\\" <|> reservedOp "λ"
n <- identifier
_ <- dot
e <- exprP
return (Lam n e)
letP :: S.Parser (Exp String)
letP = do
reserved "let"
d <- defP
reserved "in"
term <- exprP
return (Let d term)
defP :: S.Parser (String, Exp String)
defP = do
n <- identifier
reservedOp "="
term <- exprP
return (n, term)
exprP :: S.Parser (Exp String)
exprP = do
whiteSpace
letP <|> lamP <|> appP <|> atomP
expression :: String -> Either P.ParseError (Exp String)
expression = P.parse exprP "ExpParser"
|
julmue/UntypedLambda
|
src/Language/Lambda/Syntax/Named/Parser.hs
|
bsd-3-clause
| 2,074 | 0 | 11 | 508 | 692 | 365 | 327 | 66 | 1 |
module Main where
import Control.Monad (liftM)
import IRTS.CodegenCil
import IRTS.CodegenCommon
import IRTS.Compiler
import Idris.AbsSyntax
import Idris.ElabDecls
import Idris.Main
import System.Environment
import System.Exit
data Opts = Opts { inputs :: [FilePath]
, output :: FilePath }
main :: IO ()
main = do
opts <- getOpts
if null (inputs opts)
then showUsage
else runMain (cilMain opts)
getOpts :: IO Opts
getOpts = process (Opts [] "a.il") <$> getArgs
where process opts ("-o":o:xs) = process (opts { output = o }) xs
process opts (x:xs) = process (opts { inputs = x:inputs opts }) xs
process opts [] = opts
showUsage :: IO ()
showUsage = do
putStrLn "CIL code generator mainly intended to be called by the idris compiler and not directly by a user."
putStrLn "Usage: idris-codegen-cil <ibc-files> [-o <output-file>]"
exitSuccess
cilMain :: Opts -> Idris ()
cilMain opts = do
ci <- compileCilCodegenInfo (inputs opts) (output opts)
runIO $ codegenCil ci
|
bamboo/idris-cil
|
main/Main.hs
|
bsd-3-clause
| 1,066 | 0 | 12 | 256 | 336 | 175 | 161 | 32 | 3 |
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
module NPNTool.NPNConstr (
-- * Datatypes
NPNConstr(..), NPNConstrM,
-- * Operations
new,
-- * Monadic interface
run,
addElemNet,
mkPlace, mkTrans, label,
insPlace,
inT, outT, mark, marks,
-- ** 'PTC.PTConstrM' and 'PTNet' interface
liftPTC, liftElemNet, insElemNet, liftElemNet_,
-- * Generalized arcs (with expressions)
ArcExpr (..)
) where
import qualified NPNTool.PTConstr as PTC
import NPNTool.PetriNet
import NPNTool.NPNet
import qualified Data.Map as M
import qualified Data.IntMap as IM
import Control.Monad.State
import Control.Arrow (second)
import Control.Applicative ((<$>))
import Data.Monoid
import Data.Set (Set)
import qualified Data.Set as Set
import Data.MultiSet (MultiSet)
import qualified Data.MultiSet as MSet
import Data.Maybe (fromMaybe)
import Data.Tuple (swap)
import qualified Data.Foldable as F
-- | Datatype for dynamically constructing Nested Petri nets
data NPNConstr l v c =
NPNConstr
{ p :: M.Map PTPlace [Either c ElemNetId]
, key :: Int, keyT :: Int, keyEN :: Int
, tin :: M.Map Trans (SArc v c PTPlace)
, tout :: M.Map Trans (SArc v c PTPlace)
, nets :: IM.IntMap (ElemNet l)
, tlab :: M.Map Trans l
}
toNPN :: (Ord l, Ord v, Ord c) => NPNConstr l v c -> NPNet l v c
toNPN c =
NPNet
{ net = Net { places = M.keysSet (p c)
, trans = M.keysSet (tin c)
`Set.union` M.keysSet (tout c)
`Set.union` M.keysSet (tlab c)
, pre = pre'
, post = post'
, initial = NPMark (p c)
}
, elementNets = nets c
, labelling = toLabelling c
, labels = Set.fromList (M.elems (tlab c))
}
where pre' t = fromMaybe mempty (M.lookup t (tin c))
post' t = fromMaybe mempty (M.lookup t (tout c))
toLabelling c t = M.lookup t (tlab c)
type NPNConstrM l v = State (NPNConstr l v Int)
-- | Runs a @NPNConstrM@ monad and returns a NP-net together with a result
run :: (Ord v, Ord l) => NPNConstrM l v a -> NPNConstr l v Int -> (a, NPNet l v Int)
run c s =
let (a, s') = runState c s
in (a, toNPN s')
-- | New (empty) 'NPNConstr'
new :: NPNConstr l v c
new = NPNConstr { p = M.empty
, key = 1, keyT = 1, keyEN = 1
, tin = M.empty, tout = M.empty
, nets = IM.empty
, tlab = M.empty
}
intToExpr :: Int -> Expr v Int
intToExpr x = if x == 1 then Const 1 else Plus (Const 1) (intToExpr (x-1))
intToList :: Int -> [Either Int ElemNetId]
intToList x = if x == 0 then [] else (Left 1):(intToList (x-1))
toSArc :: Ord v => MultiSet PTPlace -> SArc v Int PTPlace
toSArc = F.foldMap (SArc . Set.singleton . swap . (second intToExpr)) . MSet.toOccurList
isLeft :: Either t t1 -> Bool
isLeft (Left _) = True
isLeft (Right _) = False
-- | Lift a 'PTC.PTConstrM' constructions to 'NPNConstrM' monad
liftPTC :: Ord v => PTC.PTConstrM l a -> NPNConstrM l v a
liftPTC ptc = do
st <- get
let c = PTC.new { PTC.p = M.map (const 0) $ p st
, PTC.key = key st, PTC.keyT = keyT st
, PTC.tlab = tlab st }
(res,c') = runState ptc c
st' = st { p = M.unionWith (++) (p st) (M.map (intToList) $ PTC.p c')
, key = PTC.key c', keyT = PTC.keyT c'
, tlab = PTC.tlab c'
, tin = M.unionWith mappend (tin st) (M.map toSArc (PTC.tin c'))
, tout = M.unionWith mappend (tout st) (M.map toSArc (PTC.tout c'))
}
put st'
return res
-- | Adds an existing element net to the system
addElemNet :: ElemNet l -> NPNConstrM l v ElemNetId
addElemNet en = do
st <- get
let nets' = nets st
keyEN' = keyEN st + 1
put $ st { nets = IM.insert keyEN' en nets', keyEN = keyEN' }
return (ElemNetId keyEN')
-- | Useful for working with a priori correct data,
-- generally use 'liftElemNet' instead
insElemNet :: Int -> PTC.PTConstrM l a -> NPNConstrM l v a
insElemNet k ptc = do
st <- get
let (r,net,lab) = PTC.runL ptc PTC.new
en = (net,lab,initial net)
nets' = nets st
put $ st { nets = IM.insert k en nets' }
return r
-- | `Lifts' an elementary net, described by the 'PTC.PTConstrM' into the
-- 'NPNConstrM' monad and adds it to the system.
liftElemNet :: PTC.PTConstrM l a -> NPNConstrM l v ElemNetId
liftElemNet ptc = snd <$> liftElemNet_ ptc
-- | `Lifts' an elementary net, described by the 'PTC.PTConstrM' into
-- the 'NPNConstrM' monad and adds it to the system. Also keeps track
-- of the 'PTC.PTconstrM' value.
liftElemNet_ :: PTC.PTConstrM l a -> NPNConstrM l v (a, ElemNetId)
liftElemNet_ ptc = do
st <- get
let ptc' = ptc >>= \a -> do
kk <- get
return (a, PTC.key kk, PTC.keyT kk)
let ((res, key', keyT'),net,lab) = PTC.runL ptc'
(PTC.new { PTC.key = key st
, PTC.keyT = keyT st
} )
en = (net,lab,initial net)
nets' = nets st
keyEN' = keyEN st + 1
put $ st { nets = IM.insert keyEN' en nets'
, keyEN = keyEN'
, key = key'
, keyT = keyT' }
return (res, ElemNetId keyEN')
-- | Creates a new place not yet present in the net
mkPlace :: Ord v => NPNConstrM l v PTPlace
mkPlace = liftPTC PTC.mkPlace
-- | Creates a new tranisition not yet present in the net
mkTrans :: Ord v => NPNConstrM l v Trans
mkTrans = liftPTC PTC.mkTrans
-- | Inserts a place into the system
insPlace :: Ord v => PTPlace -> NPNConstrM l v ()
insPlace = liftPTC . PTC.insPlace
-- | Specifies a label for some transition
label :: Ord v => Trans -> l -> NPNConstrM l v ()
label t = liftPTC . PTC.label t
-- | Marks a place with a token or an element net
mark :: PTPlace -> Either Int ElemNetId -> NPNConstrM l v ()
mark pl v = do
st <- get
let p' = p st
p' `seq` put $ st { p = M.insertWith (++) pl [v] p' }
-- | Marks a place with several tokens or element nets
marks :: PTPlace -> [Either Int ElemNetId] -> NPNConstrM l v ()
marks pl vs = do
st <- get
put $ st { p = M.insertWith (++) pl vs (p st) }
inT :: Ord v => PTPlace -> Expr v Int -> Trans -> NPNConstrM l v ()
inT p e t = do
c <- get
let pre' = tin c
put $ c { tin = M.insertWith mappend t (SArc (Set.singleton (e,p))) pre' }
outT :: Ord v => Trans -> Expr v Int -> PTPlace -> NPNConstrM l v ()
outT t e p = do
c <- get
let post' = tout c
put $ c { tout = M.insertWith mappend t (SArc (Set.singleton (e,p))) post' }
class PTC.Arc a => ArcExpr a v where
arcExpr :: a -> Expr v Int -> PTC.Co a -> NPNConstrM l v ()
arc :: a -> PTC.Co a -> NPNConstrM l v ()
arc k j = arcExpr k (Const 1) j
instance Ord v => ArcExpr Trans v where
arcExpr = outT
instance Ord v => ArcExpr PTPlace v where
arcExpr = inT
|
co-dan/NPNTool
|
src/NPNTool/NPNConstr.hs
|
bsd-3-clause
| 6,991 | 0 | 17 | 2,070 | 2,582 | 1,360 | 1,222 | 154 | 2 |
-- Signature
module Skolem
( simplify
, nnf
, prenex
, pnf
, specialize
, skolem
, skolemize
, askolemize
)
where
-- Imports
import Prelude hiding (print)
import qualified Fol as Fol
import FormulaSyn
import qualified Prop as Prop
import Util.Lib((⟾))
import qualified Data.List as List
-- Simplification
simplify :: Formula -> Formula
simplify fm = case fm of
[form| ¬ $p |] -> simplify1 $ (¬) $ simplify p
[form| $p ∧ $q |] -> simplify1 $ simplify p ∧ simplify q
[form| $p ∨ $q |] -> simplify1 $ simplify p ∨ simplify q
[form| $p ⊃ $q |] -> simplify1 $ simplify p ⊃ simplify q
[form| $p ⇔ $q |] -> simplify1 $ simplify p ⇔ simplify q
[form| ∀ $x. $p |] -> simplify1 $ (¥) x (simplify p)
[form| ∃ $x. $p |] -> simplify1 $ (∃) x (simplify p)
_ -> fm
simplify1 :: Formula -> Formula
simplify1 fm = case fm of
All x p -> if List.elem x (Fol.fv p) then fm else p
Ex x p -> if List.elem x (Fol.fv p) then fm else p
_ -> Prop.simplify1 fm
-- Negation normal form
nnf :: Formula -> Formula
nnf fm = case fm of
[form| $p ∧ $q |] -> nnf p ∧ nnf q
[form| $p ∨ $q |] -> nnf p ∨ nnf q
[form| $p ⊃ $q |] -> np' ∨ nnf q
where np' = nnf $ (¬) p
[form| $p ⇔ $q |] -> p' ∧ q' ∨ np' ∧ nq'
where p' = nnf $ p
np' = nnf $ (¬) p
q' = nnf q
nq' = nnf $ (¬) q
[form| ¬ ¬ $p |] -> nnf p
[form| ¬ ($p ∧ $q) |] -> np' ∨ nq'
where np' = nnf $ (¬) p
nq' = nnf $ (¬) q
[form| ¬ ($p ∨ $q) |] -> np' ∧ nq'
where np' = nnf $ (¬) p
nq' = nnf $ (¬) q
[form| ¬ ($p ⊃ $q) |] -> p' ∧ nq'
where p' = nnf p
nq' = nnf $ (¬) q
[form| ¬ ($p ⇔ $q) |] -> p' ∧ nq' ∨ np' ∧ q'
where p' = nnf $ p
np' = nnf $ (¬) p
q' = nnf q
nq' = nnf $ (¬) q
[form| ∀ $x. $p |] -> (¥) x (nnf p)
[form| ∃ $x. $p |] -> (∃) x (nnf p)
[form| ¬ (∀ $x. $p) |] -> (∃) x (nnf $ (¬) p)
[form| ¬ (∃ $x. $p) |] -> (¥) x (nnf $ (¬) p)
_ -> fm
-- nnf $ parse "(∀ x. P(x)) ⊃ ((∃ y. Q(y)) ⇔ ∃ z. P(z) ∧ Q(z))"
-- Prenex normal form
pnf :: Formula -> Formula
pnf = prenex . nnf . simplify
prenex :: Formula -> Formula
prenex (All x p) = All x (prenex p)
prenex (Ex x p) = Ex x (prenex p)
prenex (And p q) = pullquants (prenex p ∧ prenex q)
prenex (Or p q) = pullquants (prenex p ∨ prenex q)
prenex fm = fm
pullquants :: Formula -> Formula
pullquants fm = case fm of
[form| (∀ $x. $p) ∧ (∀ $y. $q) |] -> pullq (True,True) fm (¥) (∧) x y p q
[form| (∃ $x. $p) ∨ (∃ $y. $q) |] -> pullq (True,True) fm (∃) (∨) x y p q
[form| (∀ $x. $p) ∧ $q |] -> pullq (True,False) fm (¥) (∧) x x p q
[form| $p ∧ (∀ $y. $q) |] -> pullq (False,True) fm (¥) (∧) y y p q
[form| (∀ $x. $p) ∨ $q |] -> pullq (True,False) fm (¥) (∨) x x p q
[form| $p ∨ (∀ $y. $q) |] -> pullq (False,True) fm (¥) (∨) y y p q
[form| (∃ $x. $p) ∧ $q |] -> pullq (True,False) fm (∃) (∧) x x p q
[form| $p ∧ (∃ $y. $q) |] -> pullq (False,True) fm (∃) (∧) y y p q
[form| (∃ $x. $p) ∨ $q |] -> pullq (True,False) fm (∃) (∨) x x p q
[form| $p ∨ (∃ $y. $q) |] -> pullq (False,True) fm (∃) (∨) y y p q
_ -> fm
pullq :: (Bool, Bool) -> Formula
-> (Var -> Formula -> Formula)
-> (Formula -> Formula -> Formula) -> Var -> Var
-> Formula -> Formula -> Formula
pullq (l,r) fm quant op x y p q =
let z = Fol.variant x (Fol.fv fm)
p' = if l then Fol.apply (x ⟾ Var z) p else p
q' = if r then Fol.apply (y ⟾ Var z) q else q in
quant z (pullquants(op p' q'))
-- print $ pullquants [form| (∀ y. Q(y)) ∧ (∀ x. P(y)) |]
-- Skolemization
specialize :: Formula -> Formula
specialize (All _ p) = specialize p
specialize fm = fm
skolemize :: Formula -> Formula
skolemize = specialize . pnf . askolemize
askolemize :: Formula -> Formula
askolemize fm = fst ((skolem $ nnf $ simplify fm) (map fst (Fol.functions fm)))
skolem :: Formula -> Vars -> (Formula, [Func])
skolem fm fns = case fm of
Ex y p ->
let xs = Fol.fv(fm)
f = Fol.variant (if null xs then "c_" ++ y else "f_" ++ y) fns
fx = Fn f (map Var xs) in
skolem (Fol.apply (y ⟾ fx) p) (f:fns)
All x p -> let (p', fns') = skolem p fns in (All x p', fns')
And p q -> skolem2 And (p, q) fns
Or p q -> skolem2 Or (p, q) fns
_ -> (fm, fns)
skolem2 :: (Formula -> Formula -> Formula) -> (Formula, Formula)
-> Vars -> (Formula, [Func])
skolem2 cons (p,q) fns =
let (p', fns') = skolem p fns
(q', fns'') = skolem q fns' in
(cons p' q', fns'')
-- m +ATP.Util.Parse
-- print $ skolemize [form| ∃ y. x < y ⊃ ∀ u. ∃ v. x * u < y * v |]
-- print $ skolemize [form| ∀ x. P(x) ⊃ (∃ y z. Q(y) ∨ ~(∃ z. P(z) ∧ Q(z))) |]
|
etu-fkti5301-bgu/alt-exam_automated_theorem_proving
|
src/Skolem.hs
|
bsd-3-clause
| 4,895 | 0 | 15 | 1,378 | 2,096 | 1,176 | 920 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
import Test.Hspec
import Todo.Todo
import Control.Lens
import Data.Time
import System.Random
import Control.Monad.State
tstM :: State TaskStat ()
tstM = do
actives .= []
pool .= []
today .= read "2010-01-01"
rand .= mkStdGen 0
tst = execState tstM emptyTaskStat
main :: IO ()
main = hspec $ do
describe "The task handling" $ do
it "should be able to add an active task" $ do
let tst' = execState (addActiveTaskM ("title", "desc", 1.2, 3)) tst
length (tst' ^. actives) `shouldBe` 1
let aTask : _ = tst' ^. actives
(aTask ^. atTask . tTitle) `shouldBe` "title"
(aTask ^. atTask . tDesc) `shouldBe` "desc"
(aTask ^. atTask . tFactor) `shouldBe` 1.2
(aTask ^. atDue) `shouldBe` (read "2010-01-04")
|
neosam/haskelltodo
|
src/HSpecTests.hs
|
bsd-3-clause
| 831 | 0 | 20 | 184 | 289 | 149 | 140 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Properties.Screen where
import Utils
import Test.QuickCheck
import Instances
import Control.Applicative
import XMonad.StackSet hiding (filter)
import XMonad.Operations
import Graphics.X11.Xlib.Types (Dimension)
import Graphics.X11 (Rectangle(Rectangle))
import XMonad.Layout
prop_screens (x :: T) = n `elem` screens x
where
n = current x
-- screens makes sense
prop_screens_works (x :: T) = screens x == current x : visible x
------------------------------------------------------------------------
-- Hints
prop_resize_inc (Positive inc_w,Positive inc_h) b@(w,h) =
w' `mod` inc_w == 0 && h' `mod` inc_h == 0
where (w',h') = applyResizeIncHint a b
a = (inc_w,inc_h)
prop_resize_inc_extra ((NonNegative inc_w)) b@(w,h) =
(w,h) == (w',h')
where (w',h') = applyResizeIncHint a b
a = (-inc_w,0::Dimension)-- inc_h)
prop_resize_max (Positive inc_w,Positive inc_h) b@(w,h) =
w' <= inc_w && h' <= inc_h
where (w',h') = applyMaxSizeHint a b
a = (inc_w,inc_h)
prop_resize_max_extra ((NonNegative inc_w)) b@(w,h) =
(w,h) == (w',h')
where (w',h') = applyMaxSizeHint a b
a = (-inc_w,0::Dimension)-- inc_h)
prop_aspect_hint_shrink hint (w,h) = case applyAspectHint hint (w,h) of
(w',h') -> w' <= w && h' <= h
-- applyAspectHint does nothing when the supplied (x,y) fits
-- the desired range
prop_aspect_fits =
forAll ((,,,) <$> pos <*> pos <*> pos <*> pos) $ \ (x,y,a,b) ->
let f v = applyAspectHint ((x, y+a), (x+b, y)) v
in and [ noOverflows (*) x (y+a), noOverflows (*) (x+b) y ]
==> f (x,y) == (x,y)
where pos = choose (0, 65535)
prop_point_within r@(Rectangle x y w h) =
forAll ((,) <$>
choose (0, fromIntegral w - 1) <*>
choose (0, fromIntegral h - 1)) $
\(dx,dy) ->
and [ dx > 0, dy > 0,
noOverflows (\ a b -> a + abs b) x w,
noOverflows (\ a b -> a + abs b) y h ]
==> pointWithin (x+dx) (y+dy) r
prop_point_within_mirror r (x,y) = pointWithin x y r == pointWithin y x (mirrorRect r)
|
xmonad/xmonad
|
tests/Properties/Screen.hs
|
bsd-3-clause
| 2,112 | 0 | 15 | 493 | 915 | 511 | 404 | 48 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Main
-- Copyright : (c) 2010 Bernie Pope
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : ghc
--
-- The Main module of Berp. Both the compiler and the interactive interpreter
-- are started from here.
--
-----------------------------------------------------------------------------
module Main where
import System.FilePath (dropExtension, (<.>))
import System.IO (hPutStrLn, stderr)
import Control.Monad (when, unless)
import System.Console.ParseArgs
(Argtype (..), argDataOptional, argDataRequired, Arg (..)
, gotArg, getArg, parseArgsIO, ArgsComplete (..), Args(..))
import System.Exit (ExitCode (..), exitWith, exitFailure)
import System.FilePath (takeBaseName)
import System.Directory (removeFile, doesFileExist)
import Berp.Version (versionString)
import qualified Data.Set as Set (Set, empty, insert, notMember)
import Berp.Compile (compilePythonToHaskell)
import System.Cmd (system)
main :: IO ()
main = do
let args = [withGHC, version, help, clobber, clean, compile, inputFile]
argMap <- parseArgsIO ArgsComplete args
when (gotArg argMap Help) $ do
putStrLn $ argsUsage argMap
exitWith ExitSuccess
when (gotArg argMap Version) $ do
putStrLn $ "berp version " ++ versionString
exitWith ExitSuccess
maybeInputDetails <- getInputDetails argMap
case maybeInputDetails of
Nothing -> return ()
Just (sourceName, _fileContents) -> do
let exeName = pyBaseName sourceName
exeExists <- doesFileExist exeName
-- XXX should catch any exceptions here
genHaskellFiles <- compilePythonFilesToHaskell Set.empty [] [sourceName]
-- recompile if any of the source files was translated into Haskell
-- or if the exe does not exist.
when (not (null genHaskellFiles) || not exeExists) $ do
writeFile "Main.hs" $ mkMainFunction $ mkHaskellModName sourceName
ghc <- getGHC argMap
compileStatus <- system $ ghc ++ " --make -O2 -v0 Main.hs -o " ++ exeName
case compileStatus of
ExitFailure _code -> exitWith compileStatus
ExitSuccess -> return ()
let intermediates = intermediateFiles ("Main.hs":genHaskellFiles)
when (gotArg argMap Clean || gotArg argMap Clobber) $
removeFiles intermediates
unless (gotArg argMap Compile) $ do
runStatus <- system $ "./" ++ exeName
-- we only make it possible to remove the exe if the --compile flag was not given
-- it makes no sense to compile to exe (without running it) and then remove the exe.
when (gotArg argMap Clobber) $
removeFiles [exeName]
exitWith runStatus
intermediateFiles :: [FilePath] -> [FilePath]
intermediateFiles = concatMap mkIntermediates
where
mkIntermediates :: FilePath -> [FilePath]
mkIntermediates hsFile =
[hsFile, hiFile, objFile]
where
base = dropExtension hsFile
hiFile = base <.> "hi"
objFile = base <.> "o"
removeFiles :: [FilePath] -> IO ()
removeFiles = mapM_ removeFile
getGHC :: Args ArgIndex -> IO FilePath
getGHC argMap =
case getArg argMap WithGHC of
Nothing -> return "ghc"
Just pathName -> do
ghcExists <- doesFileExist pathName
if ghcExists
then return pathName
else do
hPutStrLn stderr $ "berp: requested version of GHC does not exist: " ++ pathName
exitFailure
-- return the list of generated Haskell files.
compilePythonFilesToHaskell :: Set.Set String -> [FilePath] -> [FilePath] -> IO [FilePath]
compilePythonFilesToHaskell _compiledPython genHaskellFiles [] = return genHaskellFiles
compilePythonFilesToHaskell compiledPython prevGenHaskellFiles (f:fs)
| f `Set.notMember` compiledPython = do
(imports, nextGenHaskellFiles) <- compilePythonToHaskell f
let pyImports = map (++ ".py") imports
genHaskellFiles = nextGenHaskellFiles ++ prevGenHaskellFiles
compilePythonFilesToHaskell (Set.insert f compiledPython) genHaskellFiles (fs ++ pyImports)
| otherwise = compilePythonFilesToHaskell compiledPython prevGenHaskellFiles fs
getInputDetails :: Args ArgIndex -> IO (Maybe (FilePath, String))
getInputDetails argMap =
case getArg argMap InputFile of
Nothing -> return Nothing
Just inputFileName -> do
cs <- readFile inputFileName
return $ Just (inputFileName, cs)
pyBaseName :: String -> String
pyBaseName pyFileName = takeBaseName pyFileName
mkHaskellModName :: String -> String
mkHaskellModName pyFileName = "Berp_" ++ pyBaseName pyFileName
mkMainFunction :: String -> String
mkMainFunction modName = unlines
[ "module Main where"
, "import Prelude ()"
, "import Berp.Base (run)"
, "import " ++ modName ++ " (init)"
, "main = run init" ]
data ArgIndex
= Help
| InputFile
| Compile
| Clobber
| Clean
| WithGHC
| Version
deriving (Eq, Ord, Show)
help :: Arg ArgIndex
help =
Arg
{ argIndex = Help
, argAbbr = Just 'h'
, argName = Just "help"
, argData = Nothing
, argDesc = "Display a help message."
}
inputFile :: Arg ArgIndex
inputFile =
Arg
{ argIndex = InputFile
, argAbbr = Nothing
, argName = Nothing
, argData = argDataOptional "input file" ArgtypeString
, argDesc = "Name of the input Python file."
}
compile :: Arg ArgIndex
compile =
Arg
{ argIndex = Compile
, argAbbr = Just 'c'
, argName = Just "compile"
, argData = Nothing
, argDesc = "Compile the input program, but do not run it."
}
clobber :: Arg ArgIndex
clobber =
Arg
{ argIndex = Clobber
, argAbbr = Nothing
, argName = Just "clobber"
, argData = Nothing
, argDesc = "Remove all compiler generated files after the compiled program has run."
}
clean :: Arg ArgIndex
clean =
Arg
{ argIndex = Clean
, argAbbr = Nothing
, argName = Just "clean"
, argData = Nothing
, argDesc = "Remove all compiler generated files except the executable after the compiled program has run."
}
withGHC :: Arg ArgIndex
withGHC =
Arg
{ argIndex = WithGHC
, argAbbr = Nothing
, argName = Just "with-ghc"
, argData = argDataOptional "filepath to ghc" ArgtypeString
, argDesc = "Specify the filepath of ghc."
}
version :: Arg ArgIndex
version =
Arg
{ argIndex = Version
, argAbbr = Nothing
, argName = Just "version"
, argData = Nothing
, argDesc = "Show the version number of berp."
}
|
bjpop/berp
|
compiler/src/Berp/Main.hs
|
bsd-3-clause
| 6,669 | 0 | 19 | 1,598 | 1,571 | 843 | 728 | 159 | 3 |
module WebParser
( langAttr2StemAlgo
, parseBody
, parseFeedLink
, parseHeadlines
, parseLang
, parseLinkTexts
, parseMain
, parseMeta
, parseTitles
, tld2StemAlgo
) where
import Data.List (intersect, isSuffixOf)
import Data.List.Utils (replace)
import Data.Maybe (isJust, mapMaybe)
import Network.Shpider (gatherLinks, linkText)
import NLP.Tokenize (tokenize)
import NLP.Snowball
import Text.HTML.TagSoup
import Util (appendUrlStrings, isStringAbsoluteHttpUrl, hasLetters, lowerString)
-- |Parse all acceptable inner text out of the given tags.
parseBody :: [Tag String] -> [String]
parseBody =
filterFormulas . map lowerString . tokenize . innerText . filterScript
-- |Try to parse HTML lang attribute.
parseLang :: [Tag String] -> Maybe String
parseLang t@(TagOpen "html" _ : _) =
let
hl = fromAttrib "lang" (head t)
xl = fromAttrib "xml:lang" (head t)
l = if null hl then xl else hl
in if null l then Nothing else Just l
parseLang (_:xs) = parseLang xs
parseLang [] = Nothing
-- |Parse the meta, title, hx and href tags as the main information of a page.
parseMain :: [Tag String] -> [String]
parseMain tgs =
let
mtgs = parseMeta tgs
ttgs = parseTitles tgs
htgs = parseHeadlines tgs
ltgs = parseLinkTexts tgs
in
concat [mtgs, ttgs, htgs, ltgs]
-- |Parse the meta description and keywords out of the tags.
parseMeta :: [Tag String] -> [String]
parseMeta tgs =
let
meta = "meta" :: String
descTags = filter (\t ->
(t ~== TagOpen meta [("name", "description")]) ||
(t ~== TagOpen meta [("name", "Description")]) ||
(t ~== TagOpen meta [("name", "DESCRIPTION")]) ||
(t ~== TagOpen meta [("http-equiv", "description")]) ||
(t ~== TagOpen meta [("http-equiv", "Description")]) ||
(t ~== TagOpen meta [("http-equiv", "DESCRIPTION")])) tgs
keywTags = filter (\t ->
(t ~== TagOpen meta [("name", "keywords")]) ||
(t ~== TagOpen meta [("name", "Keywords")]) ||
(t ~== TagOpen meta [("name", "KEYWORDS")]) ||
(t ~== TagOpen meta [("http-equiv", "keywords")]) ||
(t ~== TagOpen meta [("http-equiv", "Keywords")]) ||
(t ~== TagOpen meta [("http-equiv", "KEYWORDS")])) tgs
desc = getFirstTagContentAttrib descTags
keyw = getFirstTagContentAttrib keywTags
metaWords = words (replace "," " " (desc ++ " " ++ keyw))
in
(filterFormulas . map lowerString . concatMap tokenize) metaWords
-- |Helper for parseMeta. Get the content attribute value ouf of the first tag
-- in the given list if it's there.
getFirstTagContentAttrib :: [Tag String] -> String
getFirstTagContentAttrib [] = ""
getFirstTagContentAttrib (x:_) = fromAttrib "content" x
-- |Parse all <title> tags.
parseTitles :: [Tag String] -> [String]
parseTitles tgs =
let
titleParts = partitions (~== ("<title>" :: String)) tgs
titles = mapMaybe (maybeTagText . (!! 1)) titleParts
in
(filterFormulas . map lowerString . concatMap tokenize)
(concatMap words titles)
-- |Parse and postprocess data out of hx tags.
parseHeadlines :: [Tag String] -> [String]
parseHeadlines tgs =
let
h1s = mapMaybe (parseHx "h1") (sections (~== ("<h1>" :: String)) tgs)
h2s = mapMaybe (parseHx "h2") (sections (~== ("<h2>" :: String)) tgs)
h3s = mapMaybe (parseHx "h3") (sections (~== ("<h3>" :: String)) tgs)
h4s = mapMaybe (parseHx "h4") (sections (~== ("<h4>" :: String)) tgs)
hxs = concat [h1s, h2s, h3s, h4s]
in
(filterFormulas . map lowerString . concatMap tokenize) hxs
-- |Parse a single hx section.
parseHx :: String -> [Tag String] -> Maybe String
parseHx hx tgs =
let
tgs' = dropWhile (not . isTagText) (takeWhile (/= TagClose hx) tgs)
in
case tgs' of
TagText txt : _ -> Just txt
_ -> Nothing
-- |Parse the atom/rss feed links. Prefer atom.
parseFeedLink :: String -> [Tag String] -> Maybe String
parseFeedLink url tgs =
let
link = "link" :: String
atom = sections (~== TagOpen link
[("rel", "alternate"), ("type", "application/atom+xml")]) tgs
rss = sections (~== TagOpen link
[("rel", "alternate"), ("type", "application/rss+xml")]) tgs
alink = getFirstTagHrefAttrib atom
rlink = getFirstTagHrefAttrib rss
in
if isJust alink
then prepareFeedLink url alink
else prepareFeedLink url rlink
-- |Helper for parseFeedLink. Get the href attribute value ouf of the first tag
-- in the given list if it's there.
getFirstTagHrefAttrib :: [[Tag String]] -> Maybe String
getFirstTagHrefAttrib [] = Nothing
getFirstTagHrefAttrib (x:_) =
let attr = fromAttrib "href" (head x)
in if attr == ""
then Nothing
else Just attr
-- |Deal with relative feed links. Prepend the url if needed.
prepareFeedLink :: String -> Maybe String -> Maybe String
prepareFeedLink _ Nothing = Nothing
prepareFeedLink url (Just feedlink)
| isStringAbsoluteHttpUrl feedlink = Just feedlink
| otherwise = Just (appendUrlStrings url feedlink)
-- |Parse the link texts out of all links.
parseLinkTexts :: [Tag String] -> [String]
parseLinkTexts tgs =
let lnkTexts = map linkText (gatherLinks tgs)
in (filterFormulas . map lowerString . concatMap tokenize) lnkTexts
-- |HTML lang attribute to Snowball stemming Algorithm.
langAttr2StemAlgo :: String -> Maybe Algorithm
langAttr2StemAlgo lng =
let lng' = takeWhile (/= '-') lng
-- besides "en" the lang attribute is pretty much equal to the tld
in if lng' == "en"
then Just English
else tld2StemAlgo ('.' : lng')
-- |TLD to Snowball stemming Algorithm.
tld2StemAlgo :: String -> Maybe Algorithm
tld2StemAlgo url
| ".com" `isSuffixOf` url = Just English
| ".org" `isSuffixOf` url = Just English
| ".de" `isSuffixOf` url = Just German
| ".at" `isSuffixOf` url = Just German
| ".dk" `isSuffixOf` url = Just Danish
| ".nl" `isSuffixOf` url = Just Dutch
| ".uk" `isSuffixOf` url = Just English
| ".au" `isSuffixOf` url = Just English
| ".us" `isSuffixOf` url = Just English
| ".gov" `isSuffixOf` url = Just English
| ".mil" `isSuffixOf` url = Just English
| ".fi" `isSuffixOf` url = Just Finnish
| ".fr" `isSuffixOf` url = Just French
| ".hu" `isSuffixOf` url = Just Hungarian
| ".it" `isSuffixOf` url = Just Italian
| ".no" `isSuffixOf` url = Just Norwegian
| ".pt" `isSuffixOf` url = Just Portuguese
| ".br" `isSuffixOf` url = Just Portuguese
| ".ro" `isSuffixOf` url = Just Romanian
| ".ru" `isSuffixOf` url = Just Russian
| ".es" `isSuffixOf` url = Just Spanish
| ".mx" `isSuffixOf` url = Just Spanish
| ".se" `isSuffixOf` url = Just Swedish
| ".tr" `isSuffixOf` url = Just Turkish
| otherwise = Nothing
-- |Filter ok length, hasLetters, isNoStopWord and isAcceptableWord.
filterFormulas :: [String] -> [String]
filterFormulas =
filter (\x -> hasOkLength x && hasLetters x && isNoStopWord x &&
isAcceptableWord x)
-- |True if length between 2 and 80 inclusive.
hasOkLength :: String -> Bool
hasOkLength s =
let l = length s
in l >= 2 && l <= 80
-- |True if String is not in stopWords.
isNoStopWord :: String -> Bool
isNoStopWord s = s `notElem` stopWords
-- |True if String doesn't contains badChars.
isAcceptableWord :: String -> Bool
isAcceptableWord s = s `intersect` badChars == []
-- |List of StopWords of different languages.
stopWords :: [String]
stopWords = gerStopWords ++ engStopWords
-- |List of german StopWords.
gerStopWords :: [String]
gerStopWords =
["ab", "aber", "alle", "allem", "allen", "alles", "als", "also", "am",
"an", "andere", "anderem", "anderer", "anderes", "anders", "ans", "auch",
"auf", "aufs", "aus", "ausser", "ausserdem", "bei", "beide", "beiden",
"beides", "beim", "bereits", "bestehen", "besteht", "bevor", "bin", "bis",
"bloss", "brauchen", "braucht", "bzw", "da", "dabei", "dadurch", "dafür",
"dagegen", "daher", "damit", "danach", "dann", "dar", "daran", "darauf",
"darf", "darum", "darunter", "darüber", "das", "dass", "davon", "dazu",
"dein", "dem", "demnach", "den", "denen", "denn", "dennoch", "der",
"deren", "des", "deshalb", "dessen", "dich", "die", "dies", "diese",
"dieselbte", "diesem", "diesen", "dieser", "dieses", "diesmal", "dir",
"doch", "dort", "du", "durch", "durfte", "durften", "dürfen", "ebenfalls",
"ebenso", "eigene", "eigenem", "eigenen", "eigener", "eigenes", "ein",
"eine", "einem", "einen", "einer", "eines", "einige", "einiges", "einmal",
"einzelne", "einzelnen", "einzig", "entweder", "er", "erst", "erste",
"ersten", "es", "etwa", "etwas", "euch", "falls", "fast", "ferner",
"folgender", "folglich", "für", "ganz", "ganze", "gar", "geben", "gegen",
"gehabt", "gekonnt", "gemäss", "getan", "gewesen", "gewollt", "geworden",
"gibt", "hab", "habe", "haben", "hallo", "hat", "hatte", "hatten",
"heraus", "herein", "hier", "hin", "hinaus", "hinein", "hinter", "hinzu",
"hätte", "hätten", "ich", "ihm", "ihn", "ihnen", "ihr", "ihre", "ihrem",
"ihren", "ihrer", "ihres", "im", "immer", "in", "indem", "infolge",
"innen", "innerhalb", "ins", "inzwischen", "irgend", "irgendwas",
"irgendwen", "irgendwer", "irgendwie", "irgendwo", "ist", "jede", "jedem",
"jeden", "jeder", "jederzeit", "jedes", "jedoch", "jene", "jenem", "jenen",
"jener", "jenes", "jeweiligen", "jeweils", "kann", "kein", "keine",
"keinem", "keinen", "keiner", "keines", "kommen", "kommt", "konnte",
"konnten", "können", "könnte", "könnten", "lassen", "leer", "machen",
"macht", "machte", "machten", "man", "mehr", "mein", "meine", "meinem",
"meinen", "meiner", "meist", "meiste", "meisten", "mich", "mit", "muss",
"musste", "mussten", "möchte", "möchten", "müssen", "müssten", "nach",
"nachdem", "nacher", "neben", "nein", "nicht", "nichts", "noch", "nun",
"nur", "nämlich", "ob", "obgleich", "obwohl", "oder", "ohne", "schon",
"sehr", "seid", "sein", "seine", "seinem", "seinen", "seiner", "seines",
"seit", "seitdem", "seither", "selber", "selbst", "sich", "sie", "siehe",
"sind", "so", "sobald", "sofern", "sofort", "sogar", "solange", "solch",
"solche", "solchem", "solchen", "solcher", "solches", "soll", "sollen",
"sollte", "sollten", "somit", "sondern", "sonst", "sonstiges", "soweit",
"sowie", "sowohl", "statt", "stets", "such", "u.v.m.", "um", "ums", "und",
"uns", "unser", "unsere", "unserem", "unseren", "unserer", "unter", "viel",
"viele", "vielen", "vieler", "vom", "von", "vor", "vorbei", "vorher",
"vorüber", "wann", "war", "waren", "warum", "was", "weg", "wegen", "weil",
"weit", "weiter", "weitere", "weiterem", "weiteren", "weiterer",
"weiteres", "weiterhin", "welche", "welchem", "welchen", "welcher",
"welches", "wem", "wen", "wenigstens", "wenn", "wenngleich", "wer",
"werde", "werden", "weshalb", "wessen", "wie", "wieder", "will", "wir",
"wird", "wo", "wodurch", "wohin", "wollen", "wollte", "wollten", "worin",
"wurde", "wurden", "während", "wäre", "wären", "würde", "würden", "z.b",
"zeigen", "zeigt", "zu", "zudem", "zufolge", "zum", "zur", "zurück",
"zusammen", "zwar", "zwischen", "zzgl", "über"]
-- |List of english StopWords.
engStopWords :: [String]
engStopWords =
["'d", "'ll", "'m", "'s", "'ve", "about", "above", "after", "again",
"against", "all", "am", "an", "and", "any", "are", "aren't", "as", "at",
"be", "because", "been", "before", "being", "below", "between", "both",
"but", "by", "can", "can't", "cannot", "could", "couldn't", "did",
"didn't", "do", "does", "doesn't", "doing", "don't", "down", "during",
"each", "few", "for", "from", "further", "get", "had", "hadn't", "has",
"hasn't", "have", "haven't", "having", "he", "he'd", "he'll", "he's",
"her", "here", "here's", "hers", "herself", "him", "himself", "his", "how",
"how's", "i'd", "i'll", "i'm", "i've", "if", "in", "into", "is", "isn't",
"it", "it's", "its", "itself", "let's", "me", "more", "most", "mustn't",
"my", "myself", "no", "none", "nor", "not", "of", "off", "on", "once",
"only", "or", "other", "ought", "our", "ours ", "ourselves", "out", "over",
"own", "same", "shan't", "she", "she'd", "she'll", "she's", "should",
"shouldn't", "so", "some", "such", "than", "that", "that's", "the",
"their", "theirs", "them", "themselves", "then", "there", "there's",
"these", "they", "they'd", "they'll", "they're", "they've", "this",
"those", "through", "to", "too", "under", "until", "up", "very", "want",
"was", "wasn't", "we", "we'd", "we'll", "we're", "we've", "were",
"weren't", "what", "what's", "when", "when's", "where", "where's", "which",
"while", "who", "who's", "whom", "why", "why's", "with", "won't", "would",
"wouldn't", "you", "you'd", "you'll", "you're", "you've", "your", "yours",
"yourself", "yourselves"]
-- |List of characters a lambda formula word is not allowed to contain.
badChars :: String
badChars = "#$%()*,0123456789:;<>@[]{|}§"
-- |Filter out <script>...</script> parts.
filterScript :: [Tag String] -> [Tag String]
filterScript (TagOpen "script" _ : xs) = filterScript (dropTillScriptEnd xs)
filterScript (x:xs) = x : filterScript xs
filterScript [] = []
-- |Helper for filterScript.
-- Drop elements from list till </script> element was processed.
dropTillScriptEnd :: [Tag String] -> [Tag String]
dropTillScriptEnd xs =
let xs' = dropWhile (/= TagClose "script") xs
in if null xs' then xs' else tail xs'
|
dawedawe/kripkeweb
|
src/WebParser.hs
|
bsd-3-clause
| 14,078 | 0 | 21 | 3,107 | 4,222 | 2,465 | 1,757 | 248 | 3 |
-- |
-- Module : Crypto.Number.Generate
-- License : BSD-style
-- Maintainer : Vincent Hanquez <[email protected]>
-- Stability : experimental
-- Portability : Good
module Crypto.Number.Generate
( GenTopPolicy(..)
, generateParams
, generateMax
, generateBetween
) where
import Crypto.Internal.Imports
import Crypto.Number.Basic
import Crypto.Number.Serialize
import Crypto.Random.Types
import Control.Monad (when)
import Foreign.Ptr
import Foreign.Storable
import Data.Bits ((.|.), (.&.), shiftL, complement, testBit)
import Crypto.Internal.ByteArray (ScrubbedBytes)
import qualified Crypto.Internal.ByteArray as B
-- | Top bits policy when generating a number
data GenTopPolicy =
SetHighest -- ^ set the highest bit
| SetTwoHighest -- ^ set the two highest bit
deriving (Show,Eq)
-- | Generate a number for a specific size of bits,
-- and optionaly set bottom and top bits
--
-- If the top bit policy is 'Nothing', then nothing is
-- done on the highest bit (it's whatever the random generator set).
--
-- If @generateOdd is set to 'True', then the number generated
-- is guaranteed to be odd. Otherwise it will be whatever is generated
--
generateParams :: MonadRandom m
=> Int -- ^ number of bits
-> Maybe GenTopPolicy -- ^ top bit policy
-> Bool -- ^ force the number to be odd
-> m Integer
generateParams bits genTopPolicy generateOdd
| bits <= 0 = return 0
| otherwise = os2ip . tweak <$> getRandomBytes bytes
where
tweak :: ScrubbedBytes -> ScrubbedBytes
tweak orig = B.copyAndFreeze orig $ \p0 -> do
let p1 = p0 `plusPtr` 1
pEnd = p0 `plusPtr` (bytes - 1)
case genTopPolicy of
Nothing -> return ()
Just SetHighest -> p0 |= (1 `shiftL` bit)
Just SetTwoHighest
| bit == 0 -> do p0 $= 0x1
p1 |= 0x80
| otherwise -> p0 |= (0x3 `shiftL` (bit - 1))
p0 &= (complement $ mask)
when generateOdd (pEnd |= 0x1)
($=) :: Ptr Word8 -> Word8 -> IO ()
($=) p w = poke p w
(|=) :: Ptr Word8 -> Word8 -> IO ()
(|=) p w = peek p >>= \v -> poke p (v .|. w)
(&=) :: Ptr Word8 -> Word8 -> IO ()
(&=) p w = peek p >>= \v -> poke p (v .&. w)
bytes = (bits + 7) `div` 8;
bit = (bits - 1) `mod` 8;
mask = 0xff `shiftL` (bit + 1);
-- | Generate a positive integer x, s.t. 0 <= x < range
generateMax :: MonadRandom m
=> Integer -- ^ range
-> m Integer
generateMax range
| range <= 1 = return 0
| range < 127 = generateSimple
| canOverGenerate = loopGenerateOver tries
| otherwise = loopGenerate tries
where
-- this "generator" is mostly for quickcheck benefits. it'll be biased if
-- range is not a multiple of 2, but overall, no security should be
-- assumed for a number between 0 and 127.
generateSimple = flip mod range `fmap` generateParams bits Nothing False
loopGenerate count
| count == 0 = error $ "internal: generateMax(" ++ show range ++ " bits=" ++ show bits ++ ") (normal) doesn't seems to work properly"
| otherwise = do
r <- generateParams bits Nothing False
if isValid r then return r else loopGenerate (count-1)
loopGenerateOver count
| count == 0 = error $ "internal: generateMax(" ++ show range ++ " bits=" ++ show bits ++ ") (over) doesn't seems to work properly"
| otherwise = do
r <- generateParams (bits+1) Nothing False
let r2 = r - range
r3 = r2 - range
if isValid r
then return r
else if isValid r2
then return r2
else if isValid r3
then return r3
else loopGenerateOver (count-1)
bits = numBits range
canOverGenerate = bits > 3 && not (range `testBit` (bits-2)) && not (range `testBit` (bits-3))
isValid n = n < range
tries :: Int
tries = 100
-- | generate a number between the inclusive bound [low,high].
generateBetween :: MonadRandom m => Integer -> Integer -> m Integer
generateBetween low high
| low == 1 = generateMax high >>= \r -> if r == 0 then generateBetween low high else return r
| otherwise = (low +) <$> generateMax (high - low + 1)
|
nomeata/cryptonite
|
Crypto/Number/Generate.hs
|
bsd-3-clause
| 4,693 | 0 | 19 | 1,618 | 1,188 | 630 | 558 | 85 | 5 |
-- ellipticcurves.hs
module MPS.Math.EllipticCurves where
-- import MPS.Math.MPoly
import MPS.Math.FF
import MPS.Math.QQ
import MPS.Math.Primes -- (primePowerFactors)
import MPS.Math.NumberTheoryFundamentals (divides, power, intSqrt, legendreSymbol, sqrtsmodp)
import MPS.Math.RedBlackTree
import MPS.Math.RandomGenerator (randomInteger)
import MPS.Math.PowerSeries
import MPS.Math.UPoly
import MPS.Math.IrreduciblePolyFp
import MPS.Math.MathsPrimitives
import MPS.Math.DirichletSeries hiding (($*))
import MPS.Math.QuadraticField
-- Sources
-- Koblitz, Introduction to Elliptic Curves and Modular Forms
-- Ireland, Rosen, A Classical Introduction to Modern Number Theory (second edition)
-- Cohen, A Course in Computational Algebraic Number Theory
-- ELLIPTIC CURVES
data EllipticCurve a = EC a a deriving (Eq, Show)
-- EC a b represents the curve y^2 == x^3+ax+b
-- To be a valid elliptic curve, x^3+ax+b must not have repeated roots (the discriminant must not be zero)
data EllipticCurvePt a = Inf | P a a deriving (Eq, Ord, Show)
-- P x y
-- if the discriminant is zero, x^3+a*x+b has repeated roots
discriminantEC (EC a b) = -16 * (4 * a * a * a + 27 * b * b)
-- Cohen p372. This is -16 * the discriminant of the polynomial x^3+ax+b
-- !! Check sign - Ireland, Rosen use x^3-ax-b instead, so their sign may be wrong
isPtEC _ Inf = True
isPtEC (EC a b) (P x y) = y*y == x*x*x + a*x + b
-- ELLIPTIC CURVES OVER FP
ecfp p a b = EC (toFp p a) (toFp p b)
ptfp p x y = P (toFp p x) (toFp p y)
charECFp (EC (F p _) _) = p
ptsECFp (EC (F p a) (F _ b)) = Inf : [P (F p x) (F p y) | x <- [0..p-1], y <- sqrtsmodp (x*x*x + a*x + b) p]
countPtsECFp (EC (F p a) (F _ b)) = p + 1 + sum [legendreSymbol (x*x*x + a*x + b) p | x <- [0..p-1] ]
numPtsECFp curve@(EC (F p _) _)
| p > 457 = findGpOrderECFp curve -- see below
| otherwise = countPtsECFp curve
-- GROUP LAW
-- Koblitz p34
-- assumes Fractional a
-- !! Not valid over F2 or F3
ecAdd _ Inf pt = pt
ecAdd _ pt Inf = pt
ecAdd (EC a b) (P x1 y1) (P x2 y2)
| x1 /= x2 =
let
m = (y1-y2)/(x1-x2)
x3 = m*m - x1 - x2
y3 = - y1 + m * (x1 - x3)
in P x3 y3
| x1 == x2 =
if y1 == -y2 -- includes the case y1 == y2 == 0
then Inf
else
let
m = (fromInteger 3 * x1 * x1 + a) / (fromInteger 2 * y1)
x3 = m*m - 2*x1
y3 = - y1 + m * (x1 - x3)
in P x3 y3
ecMult ec k pt
| k >= 0 = power (Inf, ecAdd ec) pt k
| k < 0 = power (Inf, ecAdd ec) (ecNegate pt) (-k)
{-
ecMult _ 0 _ = Inf
ecMult _ _ Inf = Inf
ecMult ec k pt | k > 0 = doECMult Inf pt k
where
-- doECMult p q n = p + n * q
doECMult p _ 0 = p
doECMult p q n =
let p' = if odd n then ecAdd ec p q else p
q' = ecAdd ec q q
in doECMult p' q' (n `div` 2)
-}
ecNegate Inf = Inf
ecNegate (P x y) = P x (-y)
-- ORDER OF POINTS IN E(Fp)
-- The next two functions work in any group
-- Cohen p25
-- we are given that the order of g divides m
findOrderFromMultiple (idG,multG) m g = doFindOrder m (primePowerFactors m)
where
doFindOrder m [] = m
doFindOrder m ((p,a):factors) =
let
m_p = m `div` (p^a)
g' = power (idG,multG) g m_p
m' = doFindLocalOrder p g' m_p
in doFindOrder m' factors
doFindLocalOrder p h n
| h == idG = n
| otherwise = doFindLocalOrder p (power (idG,multG) h p) (n*p)
-- we could perhaps do better using inverses
-- rather than calculating g^m_p each time, we could simply do g^m * (g^p^a)^-1
-- Cohen p240-2
-- Shanks' baby-step giant-step algorithm
-- given a g <- G, and an upper bound ub on its order, calculate its order. (We don't know the order of the group)
findOrderFromUpperBound (idG,multG,invG) ub g =
let
q = 1 + intSqrt ub
(babySteps, g1:_) = splitAt (fromInteger q) (iterate (multG g) idG)
babySteps' = rbfromlist (zip babySteps [0..]) -- == [1,g,g^2...g^(q-1)]
g1' = invG g1
giantSteps = zip [1..] (iterate (multG g1') g1') -- == g^-q, g^-2q, ...
(a,r) = head [(a,r) | (a,g1_a) <- giantSteps, Just r <- [babySteps' `rblookup` g1_a] ] -- g^-aq == g^r, hence g^(aq+r) == 1
in findOrderFromMultiple (idG,multG) (a*q+r) g
-- we know g^(aq+r) == idG, so aq+r is a multiple of the order
findPtOrderECFp _ Inf = 1
findPtOrderECFp curve@(EC a@(F p _) b) pt@(P x y) = findOrderFromUpperBound (Inf, ecAdd curve, ecNegate) (p + 1 + 2 * intSqrt p) pt
findPtOrderECFpTest curve@(EC a@(F p _) b) pt@(P x y) = head [k | (k,kpt) <- zip [1..] (iterate (ecAdd curve pt) pt), kpt == Inf]
-- ORDER OF GROUP E(Fp)
-- Cohen p375
-- We know that either E(Fp) is cyclic, or E(Fp) ~== Z/d1Z * Z/d2Z, with d1 | d2 and d1 | p-1
-- Also, from Hasse's theorem
-- p + 1 - 2 * sqrt p < # E(Fp) < p + 1 + 2 * sqrt p
-- Now, given d a quadratic non-residue mod p, consider the "anti-curve" E'(Fp) defined by y^2 == x^3 + a*d^2 x + b*d^3
-- The point about the anticurve is that d is a quadratic non-residue, and x^3+ad^2x+bd^3 = d^3 * ( (x/d)^3 + a (x/d) + b)
-- Hence each value of x gives rise either to two points on the curve and none on the anticurve, or vice versa, or to one on each (if x^3+ax+b == 0)
-- Hence if the number of points on the curve is p+1-a_p, then the number of points on the anticurve is p+1+a_p,
-- Then if E(Fp) ~== Z/d1Z * Z/d2Z, d1 | d2, and E'(Fp) ~== Z/d1'Z * Z/d2'Z, d1' | d2',
-- then for p > 457, we have max (d2, d2') > 4 sqrt p -- Cohen p404
-- If we can find an elt of order > 4 sqrt p, then we are done, because # E(Fp) = d1 d2 lies in an interval of length 4 sqrt p, so this determines d1 uniquely
mix (a:as) (b:bs) = a : b : mix as bs
mix as [] = as
mix [] bs = bs
findGpOrderECFp curve@(EC a@(F p _) b) | p > 457 =
let
d = fromInteger (head [n | (n,_) <- iterate (\(_,seed) -> randomInteger p seed) (0,342349871), legendreSymbol n p == -1])
anticurve = EC (a*d*d) (b*d*d*d)
bound = intSqrt (16*p) -- 4 * sqrt p
in findGpOrder (findElt bound anticurve)
where
findElt bound anticurve@(EC a' b') =
let
ptorders = [(1, findPtOrderECFp curve (P x y)) | x <- map (F p) [0..p-1], F _ y2 <- [x*x*x+a*x+b], (y:_) <- [map (F p) (sqrtsmodp y2 p)]]
antiptorders = [(-1, findPtOrderECFp anticurve (P x y)) | x <- map (F p) [0..p-1], F _ y2 <- [x*x*x+a'*x+b'], (y:_) <- [map (F p) (sqrtsmodp y2 p)]]
in head (filter (\(sign,order) -> order > bound) (mix ptorders antiptorders))
findGpOrder (sign, d2) =
let
d1 = (p + 1 + intSqrt (4*p)) `div` d2
a_p = sign * (p+1-d1*d2)
in p+1-a_p
-- We may be able to do more in the cases where the point we find is on the curve rather than the anticurve
-- eg if d1 and d2 are coprime, we know the group is cyclic
-- Is there a way that we can tell when it isn't cyclic?
-- ZETA FUNCTION OF E/Fp
zetaECFp curve
| discriminantEC curve /= 0 =
let
p = fromInteger (charECFp curve)
n1 = fromInteger (numPtsECFp curve)
a = p + 1 - n1
in (1 - a*t + p*t*t) / ((1-t) * (1-p*t))
| otherwise = error "zetaECFp: characteristic divides discriminant"
numPtsECFqSeries curve = zipWith (*) (map fromInteger [0..]) (coeffsPS (log (zetaECFp curve)))
-- Ireland, Rosen, p302-3
-- Note that Cohen treats the case where p divides the discriminant slightly differently
localZetaEC :: EllipticCurve Integer -> Integer -> DirichletSeries QQ
localZetaEC curve@(EC a b) p =
let
n1 = fromInteger (numPtsECFp (ecfp p a b))
a_p = p + 1 - n1
p' = fromInteger p
numerator =
if p `divides` discriminantEC curve
then 1
else DS (1 : replicate (p'-2) 0 ++ fromInteger (-a_p) : replicate (p'^2-p'-1) 0 ++ fromInteger p : repeat 0) -- == 1 - a_p p^-s + p p^-2s
denominator = (eulerTermDS (p',1) * eulerTermDS (p',fromInteger p)) -- == 1/ ((1-p^-s)*(1-p p^-s))
in numerator * denominator -- eulerTermDS has already done reciprocal for us
globalZetaEC curve = fromPrimeProductDS [(fromInteger p, localZetaEC curve p) | p <- 2:[3,5..], isPrime p]
hasseWeilLfunctionEC curve = zeta s * zeta (s-1) / globalZetaEC curve
-- The following is slightly faster
_L_EC :: EllipticCurve Integer -> DirichletSeries QQ
-- _L_EC curve@(EC a b) = fromPrimeProductDS [(p, recip (term p)) | p <- 2:[3,5..], p' <- [toInteger p], isPrime p', not (p' `divides` discriminant)]
_L_EC curve@(EC a b) = recip (fromPrimeProductDS [(p, term p) | p <- 2:[3,5..], p' <- [toInteger p], isPrime p', not (p' `divides` discriminant)])
where
discriminant = discriminantEC curve
term p =
let
p' = toInteger p
n1 = numPtsECFp (ecfp p' a b)
a_p = fromInteger (p' + 1 - n1)
in DS (1 : replicate (p-2) 0 ++ (-a_p) : replicate (p^2-p-1) 0 ++ fromInteger p' : repeat 0) -- == 1 - a_p p^-s + p p^-2s
-- HECKE CHARACTERS
qch n x@(QF (-1) _ _) =
if coprimeQF x (2*n')
then let Q m 1 = normQF x in qch1 x * QF (-1) (fromInteger (legendreSymbol n m)) 0
else QF (-1) 0 0
where n' = QF (-1) (Q n 1) 0
qch1 x = head [i^j | j <- [0..3], (i^j * x) `modQF` (2+2*i) == 1]
heckeqch n x = x * qch n x
-- Koblitz p82
-- L(En,s) = (1/4) sum [heckeqch n x * (normQF x)^-s | x <- ZZ[i]\{0} ]
eltsZZi n = [fromInteger a + fromInteger b * i | a <- let x = intSqrt n in [-x..x], b <- let y = intSqrt (n-a*a) in if y == 0 then [0] else [-y,y], a*a+b*b == n]
-- L function for the curve y^2 = x^3 - n^2 x
_L_En n = DS (map (\i -> sum [heckeqch n x | x <- eltsZZi i] / 4) [1..])
-- testL n = _L_En n == hasseWeilLfunctionEC (EC (-n*n) 0)
-- COUNTING POINTS OVER Fq
-- counting points over extension fields of Fp
-- !! This code is inefficient
-- !! I need a better way to find sqrts mod Fq
allEltsFq f = map (toUPoly . map (F p)) (ptsAnFp p d)
where
p = charUPFF f
d = degUP f
-- simple improvement to this - when you find the first sqrt, immediately work out the second as its negative, and stop
-- need to check for -x == x (only happens for 0, and in F2)
numPtsECFq curve p d = length (ptsECFq curve (findIrreduciblePolyFp p d))
ptsECFq (EC a b) f = Inf : [P x y | x <- allEltsFq f, y <- sqrtsFq f (x*x*x + a' * x + b')]
where
a' = toUPoly [a]
b' = toUPoly [b]
sqrtsFq _ (UP []) = [UP []]
sqrtsFq f h =
case [g | g <- allEltsFq f, (g*g-h) `modUP` f == UP []] of
g : _ -> if g == -g then [g] else [g,-g]
otherwise -> []
-- !! We need a better algorithm for finding sqrts in Fq
{-
-- Working over UPoly Integer instead makes things slightly faster, but of course it doesn't change the asymptotic complexity
ptsECFq' f (EC a b) = Inf : [P (toUPoly (map (F p) x)) y | x <- ptsAnFp p d, y <- sqrtsFq' f (x $* x $* x $+ a' $* x $+ b')]
where
p = charUPFF f
d = degUP f
a' = if a == 0 then [] else [a]
b' = if b == 0 then [] else [b]
sqrtsFq' _ [] = []
sqrtsFq' f h =
case [g | g <- ptsAnFp p d, toUPoly (map (toFp p) (g $* g $- h)) `modUP` f == UP []] of
g : _ -> let g' = toUPoly (map (F p) g) in if g' == -g' then [g'] else [g',-g']
otherwise -> []
where
p = charUPFF f
d = degUP f
-}
-- FINITE GEOMETRY
-- needs to move into CombinatoricsGeneration
ptsAnFp p n = doAnFp [[]] 0
where
doAnFp pts i
| i == n = pts
| otherwise = doAnFp [x:xs | x <- [0..p-1], xs <- pts] (i+1)
-- TESTING
-- for p > 457, findGpOrderECFp should return same answer as countPtsECFp
-- so for a test, check that all of the following are true
-- [(p,a,b,countPtsECFp curve == findGpOrderECFp curve) | p <- filter isPrime [500..600],
-- a <- [0..10], b <- [0..10],
-- curve <- [ecfp p a b], discriminantEC curve /= 0]
eltOrdersECFp curve = map (findPtOrderECFp curve) (ptsECFp curve)
-- OLD CODE
{-
pointsFp curve p = [(x,y) | x <- map (toFp p) [0..p-1], y <- map (toFp p) [0..p-1], evalMP (curve /% p) [x,y] == 0]
pointsAnFp p 0 = [[]]
pointsAnFp p n = [x:xs | x <- map (toFp p) [0..p-1], xs <- pointsAnFp p (n-1)]
-- pointsA2Fp p = [ [x,y] | x <- map (toFp p) [0..p-1], y <- map (toFp p) [0..p-1] ]
solutionsA2Fp curve p = [(x,y) | [x,y] <- pointsAnFp p 2, evalMP (curve /% p) [x,y] == 0]
pointsPnFp p 0 = [[1]]
pointsPnFp p n = map (1:) (pointsAnFp p n) ++ map (0:) (pointsPnFp p (n-1))
-- pointsP2Fp p = [ [1,x,y] | x <- map (toFp p) [0..p-1], y <- map (toFp p) [0..p-1]] ++ [ [0,1,x] | x <- map (toFp p) [0..p-1]] ++ [[0,0,1]]
solutionsP2Fp curve p = filter (\[t,x,y] -> evalMP (curve' /% p) [t,x,y] == 0) (pointsPnFp p 2)
where curve' = toHomogeneous curve
-}
|
nfjinjing/mps
|
src/MPS/Math/EllipticCurves.hs
|
bsd-3-clause
| 12,757 | 40 | 19 | 3,392 | 3,932 | 2,062 | 1,870 | 148 | 3 |
-- | Common functions used by different parts of LRC DB.
module Pos.DB.Lrc.Common
(
-- * Getters
getEpoch
-- * Initialization
, prepareLrcCommon
-- * Helpers
, dbHasKey
, getBi
, putBi
, putBatch
, putBatchBi
, delete
, toRocksOps
-- * Operations
, putEpoch
) where
import Universum
import qualified Database.RocksDB as Rocks
import Pos.Binary.Class (Bi, serialize')
import Pos.Core.Slotting (EpochIndex)
import Pos.DB.Class (DBTag (LrcDB), MonadDB (dbDelete, dbWriteBatch),
MonadDBRead (dbGet))
import Pos.DB.Error (DBError (DBMalformed))
import Pos.DB.Functions (dbGetBi, dbPutBi)
import Pos.Util.Util (maybeThrow)
----------------------------------------------------------------------------
-- Common Helpers
----------------------------------------------------------------------------
dbHasKey :: MonadDBRead m => ByteString -> m Bool
dbHasKey key = isJust <$> dbGet LrcDB key
getBi
:: (MonadDBRead m, Bi v)
=> ByteString -> m (Maybe v)
getBi = dbGetBi LrcDB
putBi
:: (MonadDB m, Bi v)
=> ByteString -> v -> m ()
putBi = dbPutBi LrcDB
putBatch :: MonadDB m => [Rocks.BatchOp] -> m ()
putBatch = dbWriteBatch LrcDB
putBatchBi
:: (MonadDB m, Bi v)
=> [(ByteString, v)] -> m ()
putBatchBi = putBatch . toRocksOps
delete :: (MonadDB m) => ByteString -> m ()
delete = dbDelete LrcDB
toRocksOps :: Bi v => [(ByteString, v)] -> [Rocks.BatchOp]
toRocksOps ops =
[Rocks.Put key (serialize' value) | (key, value) <- ops]
----------------------------------------------------------------------------
-- Common getters
----------------------------------------------------------------------------
-- | Get epoch up to which LRC is definitely known.
getEpoch :: MonadDBRead m => m EpochIndex
getEpoch = maybeThrow (DBMalformed "no epoch in LRC DB") =<< getEpochMaybe
----------------------------------------------------------------------------
-- Operations
----------------------------------------------------------------------------
-- | Put epoch up to which all LRC data is computed. Caller must ensure
-- that all LRC data for this epoch has been put already.
putEpoch :: MonadDB m => EpochIndex -> m ()
putEpoch = putBi epochKey
----------------------------------------------------------------------------
-- Common initialization
----------------------------------------------------------------------------
-- | Put missing initial common data into LRC DB.
prepareLrcCommon :: (MonadDB m) => m ()
prepareLrcCommon =
whenNothingM_ getEpochMaybe $
putEpoch 0
----------------------------------------------------------------------------
-- Keys
----------------------------------------------------------------------------
epochKey :: ByteString
epochKey = "c/epoch"
----------------------------------------------------------------------------
-- Details
----------------------------------------------------------------------------
getEpochMaybe :: MonadDBRead m => m (Maybe EpochIndex)
getEpochMaybe = getBi epochKey
|
input-output-hk/pos-haskell-prototype
|
db/src/Pos/DB/Lrc/Common.hs
|
mit
| 3,187 | 0 | 9 | 609 | 607 | 348 | 259 | 54 | 1 |
module System.Build.ManningBook (
module System.Build.ManningBook.Config
, module System.Build.ManningBook.Build
) where
import System.Build.ManningBook.Config
import System.Build.ManningBook.Build
|
tonymorris/manning-book
|
src/System/Build/ManningBook.hs
|
bsd-3-clause
| 201 | 0 | 5 | 17 | 39 | 28 | 11 | 5 | 0 |
-- Enthropy source for dieharder tests.
-- See run-dieharder-test.sh for details
import Control.Monad (forever)
import Data.Word (Word32)
import System.IO (hPutBuf,stdout)
import Foreign.Marshal.Alloc (alloca)
import Foreign.Storable (poke)
import System.Random.PCG
main :: IO ()
main =
create >>= \gen -> forever $ do
alloca $ \p -> do
poke p =<< (uniform gen :: IO Word32)
hPutBuf stdout p 4
|
rrnewton/pcg-random
|
test/diehard-source.hs
|
bsd-3-clause
| 461 | 0 | 16 | 125 | 135 | 74 | 61 | 12 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.