code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE QuasiQuotes, FlexibleContexts #-}
import Control.Monad
import qualified Data.ByteString as B
import Data.Char
import qualified Data.ListLike as LL
import Numeric
import Text.Peggy
data JSON
= JSONString String
| JSONNumber Double
| JSONObject [(String, JSON)]
| JSONArray [JSON]
| JSONBool Bool
| JSONNull
deriving (Show)
[peggy|
jsons :: [JSON]
= json* !.
json :: JSON
= object / array
object :: JSON
= "{" (pair, ",") "}" { JSONObject $1 }
pair :: (String, JSON)
= jsstring ":" value
array :: JSON
= "[" (value, ",") "]" { JSONArray $1 }
value :: JSON
= jsstring { JSONString $1 }
/ number { JSONNumber $1 }
/ object
/ array
/ "true" { JSONBool True }
/ "false" { JSONBool False }
/ "null" { JSONNull }
jsstring ::: String
= '\"' jschar* '\"'
jschar :: Char
= '\\' escChar / [^\"\\\]
escChar :: Char
= '\"' { '\"' }
/ '\\' { '\\' }
/ '/' { '/' }
/ 'b' { '\b' }
/ 'f' { '\f' }
/ 'n' { '\n' }
/ 'r' { '\r' }
/ 't' { '\t' }
/ 'u' hex hex hex hex { chr $ fst $ head $ readHex [$1, $2, $3, $4] }
hex :: Char = [0-9a-zA-Z]
number ::: Double
= [1-9] [0-9]* { read ($1 : $2) }
/ [0] { 0.0 }
|]
main :: IO ()
main =
forever $ do
line <- B.getLine
print . parseString json "<stdin>" $ LL.CS line
|
tanakh/Peggy
|
example/Json.hs
|
bsd-3-clause
| 1,306
| 7
| 11
| 352
| 137
| 79
| 58
| 21
| 1
|
module Foo (foo) where
foo :: a -> a
foo x = x
|
donkopotamus/flycheck
|
test/resources/language/haskell/stack-project-with-renamed-stack-yaml/src/Foo.hs
|
gpl-3.0
| 49
| 0
| 5
| 15
| 26
| 15
| 11
| 3
| 1
|
-- original author:
-- Mirco "MacSlow" Mueller <macslow@bangang.de>
--
-- created:
-- 10.1.2006 (or so)
--
-- http://www.gnu.org/licenses/licenses.html#GPL
--
-- ported to Haskell by:
-- Duncan Coutts <duncan.coutts@worc.ox.ac.uk>
--
import Graphics.Rendering.Cairo
import Graphics.UI.Gtk
import Graphics.UI.Gtk.Gdk.EventM
import System.Time
import Control.Monad (when)
import Data.Maybe (isJust)
import Data.IORef
drawClockBackground :: Bool -> Int -> Int -> Render ()
drawClockBackground quality width height = do
save
scale (fromIntegral width) (fromIntegral height)
save
setOperator OperatorOver
when quality drawDropShadow
drawClockFace quality
restore
translate 0.5 0.5
scale 0.4 0.4
setSourceRGB 0.16 0.18 0.19
setLineWidth (1.5/60)
setLineCap LineCapRound
setLineJoin LineJoinRound
drawHourMarks
restore
drawClockHands :: Bool -> Int -> Int -> Render ()
drawClockHands quality width height = do
save
scale (fromIntegral width) (fromIntegral height)
translate 0.5 0.5
scale 0.4 0.4
setSourceRGB 0.16 0.18 0.19
setLineWidth (1.5/60)
setLineCap LineCapRound
setLineJoin LineJoinRound
time <- liftIO (getClockTime >>= toCalendarTime)
let hours = fromIntegral (if ctHour time >= 12
then ctHour time - 12
else ctHour time)
minutes = fromIntegral (ctMin time)
seconds = fromIntegral (ctSec time)
drawHourHand quality hours minutes seconds
drawMinuteHand quality minutes seconds
drawSecondHand quality seconds
restore
drawClockForeground :: Bool -> Int -> Int -> Render ()
drawClockForeground quality width height = do
scale (fromIntegral width) (fromIntegral height)
save
translate 0.5 0.5
scale 0.4 0.4
setSourceRGB 0.16 0.18 0.19
setLineWidth (1.5/60)
setLineCap LineCapRound
setLineJoin LineJoinRound
when quality drawInnerShadow
when quality drawReflection
drawFrame quality
restore
drawDropShadow =
withRadialPattern 0.55 0.55 0.25 0.5 0.5 0.525 $ \pattern -> do
patternAddColorStopRGBA pattern 0 0 0 0 0.811
patternAddColorStopRGBA pattern 0.64 0.345 0.345 0.345 0.317
patternAddColorStopRGBA pattern 0.84 0.713 0.713 0.713 0.137
patternAddColorStopRGBA pattern 1 1 1 1 0
patternSetFilter pattern FilterFast
setSource pattern
arc 0.5 0.5 (142/150) 0 (pi*2)
fill
drawClockFace True =
withLinearPattern 0.5 0 0.5 1 $ \pattern -> do
patternAddColorStopRGB pattern 0 0.91 0.96 0.93
patternAddColorStopRGB pattern 1 0.65 0.68 0.68
patternSetFilter pattern FilterFast
setSource pattern
translate 0.5 0.5
arc 0 0 (60/150) 0 (pi*2)
fill
drawClockFace False = do
setSourceRGB 0.78 0.82 0.805
translate 0.5 0.5
arc 0 0 (60/150) 0 (pi*2)
fill
drawHourMarks = do
save
forM_ [1..12] $ \_ -> do
rotate (pi/6)
moveTo (4.5/6) 0
lineTo (5.0/6) 0
stroke
restore
forM_ = flip mapM_
drawHourHand quality hours minutes seconds = do
save
rotate (-pi/2)
setLineCap LineCapSquare
setLineJoin LineJoinMiter
rotate ( (pi/6) * hours
+ (pi/360) * minutes
+ (pi/21600) * seconds)
-- hour hand's shadow
when quality $ do
setLineWidth (1.75/60)
setOperator OperatorAtop
setSourceRGBA 0.16 0.18 0.19 0.125
moveTo (-2/15 + 0.025) 0.025
lineTo (7/15 + 0.025) 0.025
stroke
-- the hand itself
setLineWidth (1/60)
setOperator OperatorOver
setSourceRGB 0.16 0.18 0.19
moveTo (-2/15) 0
lineTo (7/15) 0
stroke
restore
drawMinuteHand quality minutes seconds = do
save
rotate (-pi/2)
setLineCap LineCapSquare
setLineJoin LineJoinMiter
rotate ( (pi/30) * minutes
+ (pi/1800) * seconds)
-- minute hand's shadow
when quality $ do
setLineWidth (1.75/60)
setOperator OperatorAtop
setSourceRGBA 0.16 0.18 0.19 0.125
moveTo (-16/75 - 0.025) (-0.025)
lineTo (2/3 - 0.025) (-0.025)
stroke
-- the minute hand itself
setLineWidth (1/60)
setOperator OperatorOver
setSourceRGB 0.16 0.18 0.19
moveTo (-16/75) 0
lineTo (2/3) 0
stroke
restore
drawSecondHand quality seconds = do
save
rotate (-pi/2)
setLineCap LineCapSquare
setLineJoin LineJoinMiter
rotate (seconds * pi/30);
-- shadow of second hand-part
when quality $ do
setOperator OperatorAtop
setSourceRGBA 0.16 0.18 0.19 0.125
setLineWidth (1.3125 / 60)
moveTo (-1.5/5 + 0.025) 0.025
lineTo (3/5 + 0.025) 0.025
stroke
-- second hand
setOperator OperatorOver
setSourceRGB 0.39 0.58 0.77
setLineWidth (0.75/60)
moveTo (-1.5/5) 0
lineTo (3/5) 0
stroke
arc 0 0 (1/20) 0 (pi*2)
fill
arc (63/100) 0 (1/35) 0 (pi*2)
stroke
setLineWidth (1/100)
moveTo (10/15) 0
lineTo (12/15) 0
stroke
setSourceRGB 0.31 0.31 0.31
arc 0 0 (1/25) 0 (pi*2)
fill
restore
drawInnerShadow = do
save
setOperator OperatorOver
arc 0 0 (142/150) 0 (pi*2)
clip
withRadialPattern 0.3 0.3 0.1 0 0 0.95 $ \pattern -> do
patternAddColorStopRGBA pattern 0 1 1 1 0
patternAddColorStopRGBA pattern 0.64 0.713 0.713 0.713 0.137
patternAddColorStopRGBA pattern 0.84 0.345 0.345 0.345 0.317
patternAddColorStopRGBA pattern 1 0 0 0 0.811
patternSetFilter pattern FilterFast
setSource pattern
arc 0 0 (142/150) 0 (pi*2)
fill
restore
drawReflection = do
save
arc 0 0 (142/150) 0 (pi*2)
clip
rotate (-75 * pi/180)
setSourceRGBA 0.87 0.9 0.95 0.25
moveTo (-1) (-1)
lineTo 1 (-1)
lineTo 1 1
curveTo 1 0.15 (-0.15) (-1) (-1) (-1)
fill
moveTo (-1) (-1)
lineTo (-1) 1
lineTo 1 1
curveTo (-0.5) 1 (-1) 0.5 (-1) (-1)
fill
restore
drawFrame True = do
save
withRadialPattern (-0.1) (-0.1) 0.8 0 0 1.5 $ \pattern -> do
patternAddColorStopRGB pattern 0 0.4 0.4 0.4
patternAddColorStopRGB pattern 0.2 0.95 0.95 0.95
patternSetFilter pattern FilterFast
setSource pattern
setLineWidth (10/75)
arc 0 0 (142/150) 0 (pi*2)
stroke
withRadialPattern (-0.1) (-0.1) 0.8 0 0 1.5 $ \pattern -> do
patternAddColorStopRGB pattern 0 0.9 0.9 0.9
patternAddColorStopRGB pattern 0.2 0.35 0.35 0.35
patternSetFilter pattern FilterFast
setSource pattern
setLineWidth (10/75)
arc 0 0 (150/150) 0 (pi*2)
stroke
restore
drawFrame False = do
save
setSourceRGB 0 0 0
setLineWidth (10/75)
arc 0 0 1 0 (pi*2)
stroke
restore
initialSize :: Int
initialSize = 256
main = do
initGUI
window <- windowNew
windowSetDecorated window False
windowSetResizable window True
windowSetPosition window WinPosCenterAlways
widgetSetAppPaintable window True
windowSetIconFromFile window "cairo-clock-icon.png"
windowSetTitle window "Gtk2Hs Cairo Clock"
windowSetDefaultSize window initialSize initialSize
windowSetGeometryHints window (Just window)
(Just (32, 32)) (Just (512, 512))
Nothing Nothing (Just (1,1))
let setAlpha widget = do
screen <- widgetGetScreen widget
colormap <- screenGetRGBAColormap screen
maybe (return ()) (widgetSetColormap widget) colormap
setAlpha window --TODO: also call setAlpha on alpha screen change
window `on` keyPressEvent $ tryEvent $ do
"Escape" <- eventKeyName
liftIO mainQuit
window `on` buttonPressEvent $ tryEvent $ do
LeftButton <- eventButton
time <- eventTime
(x,y) <- eventRootCoordinates
liftIO $ windowBeginMoveDrag window LeftButton (round x) (round y) time
window `on` buttonPressEvent $ tryEvent $ do
MiddleButton <- eventButton
time <- eventTime
(x,y) <- eventRootCoordinates
liftIO $ windowBeginResizeDrag window WindowEdgeSouthEast MiddleButton
(round x) (round y) time
timeoutAdd (widgetQueueDraw window >> return True) 1000
backgroundRef <- newIORef (Just undefined)
foregroundRef <- newIORef (Just undefined)
let redrawStaticLayers = do
(width, height) <- widgetGetSize window
drawWin <- widgetGetDrawWindow window
background <- createImageSurface FormatARGB32 width height
foreground <- createImageSurface FormatARGB32 width height
let clear = do
save
setOperator OperatorClear
paint
restore
renderWith background $ do
clear
drawClockBackground True width height
renderWith foreground $ do
clear
drawClockForeground True width height
writeIORef backgroundRef (Just background)
writeIORef foregroundRef (Just foreground)
onRealize window redrawStaticLayers
sizeRef <- newIORef (initialSize, initialSize)
timeoutHandlerRef <- newIORef Nothing
window `on` configureEvent $ do
(w,h) <- eventSize
liftIO $ do
size <- readIORef sizeRef
writeIORef sizeRef (w,h)
when (size /= (w,h)) $ do
background <- readIORef backgroundRef
foreground <- readIORef foregroundRef
maybe (return ()) surfaceFinish background
maybe (return ()) surfaceFinish foreground
writeIORef backgroundRef Nothing
writeIORef foregroundRef Nothing
timeoutHandler <- readIORef timeoutHandlerRef
maybe (return ()) timeoutRemove timeoutHandler
handler <- timeoutAddFull (do
writeIORef timeoutHandlerRef Nothing
redrawStaticLayers
widgetQueueDraw window
return False
) priorityDefaultIdle 300
writeIORef timeoutHandlerRef (Just handler)
return False
window `on` exposeEvent $ do
drawWin <- eventWindow
exposeRegion <- eventRegion
liftIO $ do
(width, height) <- drawableGetSize drawWin
background <- readIORef backgroundRef
foreground <- readIORef foregroundRef
renderWithDrawable drawWin $ do
region exposeRegion
clip
save
setOperator OperatorSource
setSourceRGBA 0 0 0 0
paint
restore
case background of
Nothing -> drawClockBackground False width height
Just background -> do
setSourceSurface background 0 0
paint
drawClockHands (isJust background) width height
case foreground of
Nothing -> drawClockForeground False width height
Just foreground -> do
setSourceSurface foreground 0 0
paint
return True
widgetShowAll window
mainGUI
|
phischu/gtk2hs
|
cairo/demo/Clock.hs
|
lgpl-3.0
| 10,422
| 0
| 21
| 2,601
| 3,633
| 1,651
| 1,982
| -1
| -1
|
{-# LANGUAGE TypeFamilies, DataKinds, PolyKinds, GADTs #-}
module Dep3 where
import Data.Kind
import GHC.Exts ( Constraint )
type Star1 = Type
data Id1 (a :: Star1) where
Id1 :: a -> Id1 a
data Id1' :: Star1 -> Type where
Id1' :: a -> Id1' a
type family Star2 x where
Star2 x = Type
data Id2a (a :: Star2 Constraint) = Id2a a
data Id2 (a :: Star2 Constraint) where
Id2 :: a -> Id2 a
data Id2' :: Star2 Constraint -> Type where
Id2' :: a -> Id2' a
|
sdiehl/ghc
|
testsuite/tests/dependent/should_compile/Dep3.hs
|
bsd-3-clause
| 467
| 0
| 7
| 111
| 158
| 93
| 65
| 16
| 0
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE DeriveGeneric, NoImplicitPrelude, MagicHash,
ExistentialQuantification, ImplicitParams #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.IO.Exception
-- Copyright : (c) The University of Glasgow, 2009
-- License : see libraries/base/LICENSE
--
-- Maintainer : libraries@haskell.org
-- Stability : internal
-- Portability : non-portable
--
-- IO-related Exception types and functions
--
-----------------------------------------------------------------------------
module GHC.IO.Exception (
BlockedIndefinitelyOnMVar(..), blockedIndefinitelyOnMVar,
BlockedIndefinitelyOnSTM(..), blockedIndefinitelyOnSTM,
Deadlock(..),
AllocationLimitExceeded(..), allocationLimitExceeded,
AssertionFailed(..),
SomeAsyncException(..),
asyncExceptionToException, asyncExceptionFromException,
AsyncException(..), stackOverflow, heapOverflow,
ArrayException(..),
ExitCode(..),
ioException,
ioError,
IOError,
IOException(..),
IOErrorType(..),
userError,
assertError,
unsupportedOperation,
untangle,
) where
import GHC.Base
import GHC.Generics
import GHC.List
import GHC.IO
import GHC.Show
import GHC.Read
import GHC.Exception
import GHC.IO.Handle.Types
import GHC.OldList ( intercalate )
import {-# SOURCE #-} GHC.Stack.CCS
import Foreign.C.Types
import Data.Typeable ( cast )
-- ------------------------------------------------------------------------
-- Exception datatypes and operations
-- |The thread is blocked on an @MVar@, but there are no other references
-- to the @MVar@ so it can't ever continue.
data BlockedIndefinitelyOnMVar = BlockedIndefinitelyOnMVar
instance Exception BlockedIndefinitelyOnMVar
instance Show BlockedIndefinitelyOnMVar where
showsPrec _ BlockedIndefinitelyOnMVar = showString "thread blocked indefinitely in an MVar operation"
blockedIndefinitelyOnMVar :: SomeException -- for the RTS
blockedIndefinitelyOnMVar = toException BlockedIndefinitelyOnMVar
-----
-- |The thread is waiting to retry an STM transaction, but there are no
-- other references to any @TVar@s involved, so it can't ever continue.
data BlockedIndefinitelyOnSTM = BlockedIndefinitelyOnSTM
instance Exception BlockedIndefinitelyOnSTM
instance Show BlockedIndefinitelyOnSTM where
showsPrec _ BlockedIndefinitelyOnSTM = showString "thread blocked indefinitely in an STM transaction"
blockedIndefinitelyOnSTM :: SomeException -- for the RTS
blockedIndefinitelyOnSTM = toException BlockedIndefinitelyOnSTM
-----
-- |There are no runnable threads, so the program is deadlocked.
-- The @Deadlock@ exception is raised in the main thread only.
data Deadlock = Deadlock
instance Exception Deadlock
instance Show Deadlock where
showsPrec _ Deadlock = showString "<<deadlock>>"
-----
-- |This thread has exceeded its allocation limit. See
-- 'System.Mem.setAllocationCounter' and
-- 'System.Mem.enableAllocationLimit'.
--
-- @since 4.8.0.0
data AllocationLimitExceeded = AllocationLimitExceeded
instance Exception AllocationLimitExceeded where
toException = asyncExceptionToException
fromException = asyncExceptionFromException
instance Show AllocationLimitExceeded where
showsPrec _ AllocationLimitExceeded =
showString "allocation limit exceeded"
allocationLimitExceeded :: SomeException -- for the RTS
allocationLimitExceeded = toException AllocationLimitExceeded
-----
-- |'assert' was applied to 'False'.
newtype AssertionFailed = AssertionFailed String
instance Exception AssertionFailed
instance Show AssertionFailed where
showsPrec _ (AssertionFailed err) = showString err
-----
-- |Superclass for asynchronous exceptions.
--
-- @since 4.7.0.0
data SomeAsyncException = forall e . Exception e => SomeAsyncException e
instance Show SomeAsyncException where
show (SomeAsyncException e) = show e
instance Exception SomeAsyncException
-- |@since 4.7.0.0
asyncExceptionToException :: Exception e => e -> SomeException
asyncExceptionToException = toException . SomeAsyncException
-- |@since 4.7.0.0
asyncExceptionFromException :: Exception e => SomeException -> Maybe e
asyncExceptionFromException x = do
SomeAsyncException a <- fromException x
cast a
-- |Asynchronous exceptions.
data AsyncException
= StackOverflow
-- ^The current thread\'s stack exceeded its limit.
-- Since an exception has been raised, the thread\'s stack
-- will certainly be below its limit again, but the
-- programmer should take remedial action
-- immediately.
| HeapOverflow
-- ^The program\'s heap is reaching its limit, and
-- the program should take action to reduce the amount of
-- live data it has. Notes:
--
-- * It is undefined which thread receives this exception.
--
-- * GHC currently does not throw 'HeapOverflow' exceptions.
| ThreadKilled
-- ^This exception is raised by another thread
-- calling 'Control.Concurrent.killThread', or by the system
-- if it needs to terminate the thread for some
-- reason.
| UserInterrupt
-- ^This exception is raised by default in the main thread of
-- the program when the user requests to terminate the program
-- via the usual mechanism(s) (e.g. Control-C in the console).
deriving (Eq, Ord)
instance Exception AsyncException where
toException = asyncExceptionToException
fromException = asyncExceptionFromException
-- | Exceptions generated by array operations
data ArrayException
= IndexOutOfBounds String
-- ^An attempt was made to index an array outside
-- its declared bounds.
| UndefinedElement String
-- ^An attempt was made to evaluate an element of an
-- array that had not been initialized.
deriving (Eq, Ord)
instance Exception ArrayException
-- for the RTS
stackOverflow, heapOverflow :: SomeException
stackOverflow = toException StackOverflow
heapOverflow = toException HeapOverflow
instance Show AsyncException where
showsPrec _ StackOverflow = showString "stack overflow"
showsPrec _ HeapOverflow = showString "heap overflow"
showsPrec _ ThreadKilled = showString "thread killed"
showsPrec _ UserInterrupt = showString "user interrupt"
instance Show ArrayException where
showsPrec _ (IndexOutOfBounds s)
= showString "array index out of range"
. (if not (null s) then showString ": " . showString s
else id)
showsPrec _ (UndefinedElement s)
= showString "undefined array element"
. (if not (null s) then showString ": " . showString s
else id)
-- -----------------------------------------------------------------------------
-- The ExitCode type
-- We need it here because it is used in ExitException in the
-- Exception datatype (above).
-- | Defines the exit codes that a program can return.
data ExitCode
= ExitSuccess -- ^ indicates successful termination;
| ExitFailure Int
-- ^ indicates program failure with an exit code.
-- The exact interpretation of the code is
-- operating-system dependent. In particular, some values
-- may be prohibited (e.g. 0 on a POSIX-compliant system).
deriving (Eq, Ord, Read, Show, Generic)
instance Exception ExitCode
ioException :: IOException -> IO a
ioException err = throwIO err
-- | Raise an 'IOError' in the 'IO' monad.
ioError :: IOError -> IO a
ioError = ioException
-- ---------------------------------------------------------------------------
-- IOError type
-- | The Haskell 2010 type for exceptions in the 'IO' monad.
-- Any I\/O operation may raise an 'IOError' instead of returning a result.
-- For a more general type of exception, including also those that arise
-- in pure code, see 'Control.Exception.Exception'.
--
-- In Haskell 2010, this is an opaque type.
type IOError = IOException
-- |Exceptions that occur in the @IO@ monad.
-- An @IOException@ records a more specific error type, a descriptive
-- string and maybe the handle that was used when the error was
-- flagged.
data IOException
= IOError {
ioe_handle :: Maybe Handle, -- the handle used by the action flagging
-- the error.
ioe_type :: IOErrorType, -- what it was.
ioe_location :: String, -- location.
ioe_description :: String, -- error type specific information.
ioe_errno :: Maybe CInt, -- errno leading to this error, if any.
ioe_filename :: Maybe FilePath -- filename the error is related to.
}
instance Exception IOException
instance Eq IOException where
(IOError h1 e1 loc1 str1 en1 fn1) == (IOError h2 e2 loc2 str2 en2 fn2) =
e1==e2 && str1==str2 && h1==h2 && loc1==loc2 && en1==en2 && fn1==fn2
-- | An abstract type that contains a value for each variant of 'IOError'.
data IOErrorType
-- Haskell 2010:
= AlreadyExists
| NoSuchThing
| ResourceBusy
| ResourceExhausted
| EOF
| IllegalOperation
| PermissionDenied
| UserError
-- GHC only:
| UnsatisfiedConstraints
| SystemError
| ProtocolError
| OtherError
| InvalidArgument
| InappropriateType
| HardwareFault
| UnsupportedOperation
| TimeExpired
| ResourceVanished
| Interrupted
instance Eq IOErrorType where
x == y = isTrue# (getTag x ==# getTag y)
instance Show IOErrorType where
showsPrec _ e =
showString $
case e of
AlreadyExists -> "already exists"
NoSuchThing -> "does not exist"
ResourceBusy -> "resource busy"
ResourceExhausted -> "resource exhausted"
EOF -> "end of file"
IllegalOperation -> "illegal operation"
PermissionDenied -> "permission denied"
UserError -> "user error"
HardwareFault -> "hardware fault"
InappropriateType -> "inappropriate type"
Interrupted -> "interrupted"
InvalidArgument -> "invalid argument"
OtherError -> "failed"
ProtocolError -> "protocol error"
ResourceVanished -> "resource vanished"
SystemError -> "system error"
TimeExpired -> "timeout"
UnsatisfiedConstraints -> "unsatisfied constraints" -- ultra-precise!
UnsupportedOperation -> "unsupported operation"
-- | Construct an 'IOError' value with a string describing the error.
-- The 'fail' method of the 'IO' instance of the 'Monad' class raises a
-- 'userError', thus:
--
-- > instance Monad IO where
-- > ...
-- > fail s = ioError (userError s)
--
userError :: String -> IOError
userError str = IOError Nothing UserError "" str Nothing Nothing
-- ---------------------------------------------------------------------------
-- Showing IOErrors
instance Show IOException where
showsPrec p (IOError hdl iot loc s _ fn) =
(case fn of
Nothing -> case hdl of
Nothing -> id
Just h -> showsPrec p h . showString ": "
Just name -> showString name . showString ": ") .
(case loc of
"" -> id
_ -> showString loc . showString ": ") .
showsPrec p iot .
(case s of
"" -> id
_ -> showString " (" . showString s . showString ")")
-- Note the use of "lazy". This means that
-- assert False (throw e)
-- will throw the assertion failure rather than e. See trac #5561.
assertError :: (?callStack :: CallStack) => Bool -> a -> a
assertError predicate v
| predicate = lazy v
| otherwise = unsafeDupablePerformIO $ do
ccsStack <- currentCallStack
let
implicitParamCallStack = prettyCallStackLines ?callStack
ccsCallStack = showCCSStack ccsStack
stack = intercalate "\n" $ implicitParamCallStack ++ ccsCallStack
throwIO (AssertionFailed ("Assertion failed\n" ++ stack))
unsupportedOperation :: IOError
unsupportedOperation =
(IOError Nothing UnsupportedOperation ""
"Operation is not supported" Nothing Nothing)
{-
(untangle coded message) expects "coded" to be of the form
"location|details"
It prints
location message details
-}
untangle :: Addr# -> String -> String
untangle coded message
= location
++ ": "
++ message
++ details
++ "\n"
where
coded_str = unpackCStringUtf8# coded
(location, details)
= case (span not_bar coded_str) of { (loc, rest) ->
case rest of
('|':det) -> (loc, ' ' : det)
_ -> (loc, "")
}
not_bar c = c /= '|'
|
tolysz/prepare-ghcjs
|
spec-lts8/base/GHC/IO/Exception.hs
|
bsd-3-clause
| 12,712
| 0
| 17
| 2,799
| 1,921
| 1,070
| 851
| 218
| 2
|
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
Utilities for desugaring
This module exports some utility functions of no great interest.
-}
{-# LANGUAGE CPP #-}
-- | Utility functions for constructing Core syntax, principally for desugaring
module DsUtils (
EquationInfo(..),
firstPat, shiftEqns,
MatchResult(..), CanItFail(..), CaseAlt(..),
cantFailMatchResult, alwaysFailMatchResult,
extractMatchResult, combineMatchResults,
adjustMatchResult, adjustMatchResultDs,
mkCoLetMatchResult, mkViewMatchResult, mkGuardedMatchResult,
matchCanFail, mkEvalMatchResult,
mkCoPrimCaseMatchResult, mkCoAlgCaseMatchResult, mkCoSynCaseMatchResult,
wrapBind, wrapBinds,
mkErrorAppDs, mkCoreAppDs, mkCoreAppsDs,
seqVar,
-- LHs tuples
mkLHsVarPatTup, mkLHsPatTup, mkVanillaTuplePat,
mkBigLHsVarTup, mkBigLHsTup, mkBigLHsVarPatTup, mkBigLHsPatTup,
mkSelectorBinds,
selectSimpleMatchVarL, selectMatchVars, selectMatchVar,
mkOptTickBox, mkBinaryTickBox
) where
#include "HsVersions.h"
import {-# SOURCE #-} Match ( matchSimply )
import HsSyn
import TcHsSyn
import TcType( tcSplitTyConApp )
import CoreSyn
import DsMonad
import {-# SOURCE #-} DsExpr ( dsLExpr )
import CoreUtils
import MkCore
import MkId
import Id
import Literal
import TyCon
import ConLike
import DataCon
import PatSyn
import Type
import TysPrim
import TysWiredIn
import BasicTypes
import UniqSet
import UniqSupply
import Module
import PrelNames
import Outputable
import SrcLoc
import Util
import DynFlags
import FastString
import TcEvidence
import Control.Monad ( zipWithM )
{-
************************************************************************
* *
\subsection{ Selecting match variables}
* *
************************************************************************
We're about to match against some patterns. We want to make some
@Ids@ to use as match variables. If a pattern has an @Id@ readily at
hand, which should indeed be bound to the pattern as a whole, then use it;
otherwise, make one up.
-}
selectSimpleMatchVarL :: LPat Id -> DsM Id
selectSimpleMatchVarL pat = selectMatchVar (unLoc pat)
-- (selectMatchVars ps tys) chooses variables of type tys
-- to use for matching ps against. If the pattern is a variable,
-- we try to use that, to save inventing lots of fresh variables.
--
-- OLD, but interesting note:
-- But even if it is a variable, its type might not match. Consider
-- data T a where
-- T1 :: Int -> T Int
-- T2 :: a -> T a
--
-- f :: T a -> a -> Int
-- f (T1 i) (x::Int) = x
-- f (T2 i) (y::a) = 0
-- Then we must not choose (x::Int) as the matching variable!
-- And nowadays we won't, because the (x::Int) will be wrapped in a CoPat
selectMatchVars :: [Pat Id] -> DsM [Id]
selectMatchVars ps = mapM selectMatchVar ps
selectMatchVar :: Pat Id -> DsM Id
selectMatchVar (BangPat pat) = selectMatchVar (unLoc pat)
selectMatchVar (LazyPat pat) = selectMatchVar (unLoc pat)
selectMatchVar (ParPat pat) = selectMatchVar (unLoc pat)
selectMatchVar (VarPat var) = return (localiseId var) -- Note [Localise pattern binders]
selectMatchVar (AsPat var _) = return (unLoc var)
selectMatchVar other_pat = newSysLocalDs (hsPatType other_pat)
-- OK, better make up one...
{-
Note [Localise pattern binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider module M where
[Just a] = e
After renaming it looks like
module M where
[Just M.a] = e
We don't generalise, since it's a pattern binding, monomorphic, etc,
so after desugaring we may get something like
M.a = case e of (v:_) ->
case v of Just M.a -> M.a
Notice the "M.a" in the pattern; after all, it was in the original
pattern. However, after optimisation those pattern binders can become
let-binders, and then end up floated to top level. They have a
different *unique* by then (the simplifier is good about maintaining
proper scoping), but it's BAD to have two top-level bindings with the
External Name M.a, because that turns into two linker symbols for M.a.
It's quite rare for this to actually *happen* -- the only case I know
of is tc003 compiled with the 'hpc' way -- but that only makes it
all the more annoying.
To avoid this, we craftily call 'localiseId' in the desugarer, which
simply turns the External Name for the Id into an Internal one, but
doesn't change the unique. So the desugarer produces this:
M.a{r8} = case e of (v:_) ->
case v of Just a{r8} -> M.a{r8}
The unique is still 'r8', but the binding site in the pattern
is now an Internal Name. Now the simplifier's usual mechanisms
will propagate that Name to all the occurrence sites, as well as
un-shadowing it, so we'll get
M.a{r8} = case e of (v:_) ->
case v of Just a{s77} -> a{s77}
In fact, even CoreSubst.simplOptExpr will do this, and simpleOptExpr
runs on the output of the desugarer, so all is well by the end of
the desugaring pass.
************************************************************************
* *
* type synonym EquationInfo and access functions for its pieces *
* *
************************************************************************
\subsection[EquationInfo-synonym]{@EquationInfo@: a useful synonym}
The ``equation info'' used by @match@ is relatively complicated and
worthy of a type synonym and a few handy functions.
-}
firstPat :: EquationInfo -> Pat Id
firstPat eqn = ASSERT( notNull (eqn_pats eqn) ) head (eqn_pats eqn)
shiftEqns :: [EquationInfo] -> [EquationInfo]
-- Drop the first pattern in each equation
shiftEqns eqns = [ eqn { eqn_pats = tail (eqn_pats eqn) } | eqn <- eqns ]
-- Functions on MatchResults
matchCanFail :: MatchResult -> Bool
matchCanFail (MatchResult CanFail _) = True
matchCanFail (MatchResult CantFail _) = False
alwaysFailMatchResult :: MatchResult
alwaysFailMatchResult = MatchResult CanFail (\fail -> return fail)
cantFailMatchResult :: CoreExpr -> MatchResult
cantFailMatchResult expr = MatchResult CantFail (\_ -> return expr)
extractMatchResult :: MatchResult -> CoreExpr -> DsM CoreExpr
extractMatchResult (MatchResult CantFail match_fn) _
= match_fn (error "It can't fail!")
extractMatchResult (MatchResult CanFail match_fn) fail_expr = do
(fail_bind, if_it_fails) <- mkFailurePair fail_expr
body <- match_fn if_it_fails
return (mkCoreLet fail_bind body)
combineMatchResults :: MatchResult -> MatchResult -> MatchResult
combineMatchResults (MatchResult CanFail body_fn1)
(MatchResult can_it_fail2 body_fn2)
= MatchResult can_it_fail2 body_fn
where
body_fn fail = do body2 <- body_fn2 fail
(fail_bind, duplicatable_expr) <- mkFailurePair body2
body1 <- body_fn1 duplicatable_expr
return (Let fail_bind body1)
combineMatchResults match_result1@(MatchResult CantFail _) _
= match_result1
adjustMatchResult :: DsWrapper -> MatchResult -> MatchResult
adjustMatchResult encl_fn (MatchResult can_it_fail body_fn)
= MatchResult can_it_fail (\fail -> encl_fn <$> body_fn fail)
adjustMatchResultDs :: (CoreExpr -> DsM CoreExpr) -> MatchResult -> MatchResult
adjustMatchResultDs encl_fn (MatchResult can_it_fail body_fn)
= MatchResult can_it_fail (\fail -> encl_fn =<< body_fn fail)
wrapBinds :: [(Var,Var)] -> CoreExpr -> CoreExpr
wrapBinds [] e = e
wrapBinds ((new,old):prs) e = wrapBind new old (wrapBinds prs e)
wrapBind :: Var -> Var -> CoreExpr -> CoreExpr
wrapBind new old body -- NB: this function must deal with term
| new==old = body -- variables, type variables or coercion variables
| otherwise = Let (NonRec new (varToCoreExpr old)) body
seqVar :: Var -> CoreExpr -> CoreExpr
seqVar var body = Case (Var var) var (exprType body)
[(DEFAULT, [], body)]
mkCoLetMatchResult :: CoreBind -> MatchResult -> MatchResult
mkCoLetMatchResult bind = adjustMatchResult (mkCoreLet bind)
-- (mkViewMatchResult var' viewExpr var mr) makes the expression
-- let var' = viewExpr var in mr
mkViewMatchResult :: Id -> CoreExpr -> Id -> MatchResult -> MatchResult
mkViewMatchResult var' viewExpr var =
adjustMatchResult (mkCoreLet (NonRec var' (mkCoreAppDs viewExpr (Var var))))
mkEvalMatchResult :: Id -> Type -> MatchResult -> MatchResult
mkEvalMatchResult var ty
= adjustMatchResult (\e -> Case (Var var) var ty [(DEFAULT, [], e)])
mkGuardedMatchResult :: CoreExpr -> MatchResult -> MatchResult
mkGuardedMatchResult pred_expr (MatchResult _ body_fn)
= MatchResult CanFail (\fail -> do body <- body_fn fail
return (mkIfThenElse pred_expr body fail))
mkCoPrimCaseMatchResult :: Id -- Scrutinee
-> Type -- Type of the case
-> [(Literal, MatchResult)] -- Alternatives
-> MatchResult -- Literals are all unlifted
mkCoPrimCaseMatchResult var ty match_alts
= MatchResult CanFail mk_case
where
mk_case fail = do
alts <- mapM (mk_alt fail) sorted_alts
return (Case (Var var) var ty ((DEFAULT, [], fail) : alts))
sorted_alts = sortWith fst match_alts -- Right order for a Case
mk_alt fail (lit, MatchResult _ body_fn)
= ASSERT( not (litIsLifted lit) )
do body <- body_fn fail
return (LitAlt lit, [], body)
data CaseAlt a = MkCaseAlt{ alt_pat :: a,
alt_bndrs :: [CoreBndr],
alt_wrapper :: HsWrapper,
alt_result :: MatchResult }
mkCoAlgCaseMatchResult
:: DynFlags
-> Id -- Scrutinee
-> Type -- Type of exp
-> [CaseAlt DataCon] -- Alternatives (bndrs *include* tyvars, dicts)
-> MatchResult
mkCoAlgCaseMatchResult dflags var ty match_alts
| isNewtype -- Newtype case; use a let
= ASSERT( null (tail match_alts) && null (tail arg_ids1) )
mkCoLetMatchResult (NonRec arg_id1 newtype_rhs) match_result1
| isPArrFakeAlts match_alts
= MatchResult CanFail $ mkPArrCase dflags var ty (sort_alts match_alts)
| otherwise
= mkDataConCase var ty match_alts
where
isNewtype = isNewTyCon (dataConTyCon (alt_pat alt1))
-- [Interesting: because of GADTs, we can't rely on the type of
-- the scrutinised Id to be sufficiently refined to have a TyCon in it]
alt1@MkCaseAlt{ alt_bndrs = arg_ids1, alt_result = match_result1 }
= ASSERT( notNull match_alts ) head match_alts
-- Stuff for newtype
arg_id1 = ASSERT( notNull arg_ids1 ) head arg_ids1
var_ty = idType var
(tc, ty_args) = tcSplitTyConApp var_ty -- Don't look through newtypes
-- (not that splitTyConApp does, these days)
newtype_rhs = unwrapNewTypeBody tc ty_args (Var var)
--- Stuff for parallel arrays
--
-- Concerning `isPArrFakeAlts':
--
-- * it is *not* sufficient to just check the type of the type
-- constructor, as we have to be careful not to confuse the real
-- representation of parallel arrays with the fake constructors;
-- moreover, a list of alternatives must not mix fake and real
-- constructors (this is checked earlier on)
--
-- FIXME: We actually go through the whole list and make sure that
-- either all or none of the constructors are fake parallel
-- array constructors. This is to spot equations that mix fake
-- constructors with the real representation defined in
-- `PrelPArr'. It would be nicer to spot this situation
-- earlier and raise a proper error message, but it can really
-- only happen in `PrelPArr' anyway.
--
isPArrFakeAlts :: [CaseAlt DataCon] -> Bool
isPArrFakeAlts [alt] = isPArrFakeCon (alt_pat alt)
isPArrFakeAlts (alt:alts) =
case (isPArrFakeCon (alt_pat alt), isPArrFakeAlts alts) of
(True , True ) -> True
(False, False) -> False
_ -> panic "DsUtils: you may not mix `[:...:]' with `PArr' patterns"
isPArrFakeAlts [] = panic "DsUtils: unexpectedly found an empty list of PArr fake alternatives"
mkCoSynCaseMatchResult :: Id -> Type -> CaseAlt PatSyn -> MatchResult
mkCoSynCaseMatchResult var ty alt = MatchResult CanFail $ mkPatSynCase var ty alt
sort_alts :: [CaseAlt DataCon] -> [CaseAlt DataCon]
sort_alts = sortWith (dataConTag . alt_pat)
mkPatSynCase :: Id -> Type -> CaseAlt PatSyn -> CoreExpr -> DsM CoreExpr
mkPatSynCase var ty alt fail = do
matcher <- dsLExpr $ mkLHsWrap wrapper $ nlHsTyApp matcher [ty]
let MatchResult _ mkCont = match_result
cont <- mkCoreLams bndrs <$> mkCont fail
return $ mkCoreAppsDs matcher [Var var, ensure_unstrict cont, Lam voidArgId fail]
where
MkCaseAlt{ alt_pat = psyn,
alt_bndrs = bndrs,
alt_wrapper = wrapper,
alt_result = match_result} = alt
(matcher, needs_void_lam) = patSynMatcher psyn
-- See Note [Matchers and builders for pattern synonyms] in PatSyns
-- on these extra Void# arguments
ensure_unstrict cont | needs_void_lam = Lam voidArgId cont
| otherwise = cont
mkDataConCase :: Id -> Type -> [CaseAlt DataCon] -> MatchResult
mkDataConCase _ _ [] = panic "mkDataConCase: no alternatives"
mkDataConCase var ty alts@(alt1:_) = MatchResult fail_flag mk_case
where
con1 = alt_pat alt1
tycon = dataConTyCon con1
data_cons = tyConDataCons tycon
match_results = map alt_result alts
sorted_alts :: [CaseAlt DataCon]
sorted_alts = sort_alts alts
var_ty = idType var
(_, ty_args) = tcSplitTyConApp var_ty -- Don't look through newtypes
-- (not that splitTyConApp does, these days)
mk_case :: CoreExpr -> DsM CoreExpr
mk_case fail = do
alts <- mapM (mk_alt fail) sorted_alts
return $ mkWildCase (Var var) (idType var) ty (mk_default fail ++ alts)
mk_alt :: CoreExpr -> CaseAlt DataCon -> DsM CoreAlt
mk_alt fail MkCaseAlt{ alt_pat = con,
alt_bndrs = args,
alt_result = MatchResult _ body_fn }
= do { body <- body_fn fail
; case dataConBoxer con of {
Nothing -> return (DataAlt con, args, body) ;
Just (DCB boxer) ->
do { us <- newUniqueSupply
; let (rep_ids, binds) = initUs_ us (boxer ty_args args)
; return (DataAlt con, rep_ids, mkLets binds body) } } }
mk_default :: CoreExpr -> [CoreAlt]
mk_default fail | exhaustive_case = []
| otherwise = [(DEFAULT, [], fail)]
fail_flag :: CanItFail
fail_flag | exhaustive_case
= foldr orFail CantFail [can_it_fail | MatchResult can_it_fail _ <- match_results]
| otherwise
= CanFail
mentioned_constructors = mkUniqSet $ map alt_pat alts
un_mentioned_constructors
= mkUniqSet data_cons `minusUniqSet` mentioned_constructors
exhaustive_case = isEmptyUniqSet un_mentioned_constructors
--- Stuff for parallel arrays
--
-- * the following is to desugar cases over fake constructors for
-- parallel arrays, which are introduced by `tidy1' in the `PArrPat'
-- case
--
mkPArrCase :: DynFlags -> Id -> Type -> [CaseAlt DataCon] -> CoreExpr -> DsM CoreExpr
mkPArrCase dflags var ty sorted_alts fail = do
lengthP <- dsDPHBuiltin lengthPVar
alt <- unboxAlt
return (mkWildCase (len lengthP) intTy ty [alt])
where
elemTy = case splitTyConApp (idType var) of
(_, [elemTy]) -> elemTy
_ -> panic panicMsg
panicMsg = "DsUtils.mkCoAlgCaseMatchResult: not a parallel array?"
len lengthP = mkApps (Var lengthP) [Type elemTy, Var var]
--
unboxAlt = do
l <- newSysLocalDs intPrimTy
indexP <- dsDPHBuiltin indexPVar
alts <- mapM (mkAlt indexP) sorted_alts
return (DataAlt intDataCon, [l], mkWildCase (Var l) intPrimTy ty (dft : alts))
where
dft = (DEFAULT, [], fail)
--
-- each alternative matches one array length (corresponding to one
-- fake array constructor), so the match is on a literal; each
-- alternative's body is extended by a local binding for each
-- constructor argument, which are bound to array elements starting
-- with the first
--
mkAlt indexP alt@MkCaseAlt{alt_result = MatchResult _ bodyFun} = do
body <- bodyFun fail
return (LitAlt lit, [], mkCoreLets binds body)
where
lit = MachInt $ toInteger (dataConSourceArity (alt_pat alt))
binds = [NonRec arg (indexExpr i) | (i, arg) <- zip [1..] (alt_bndrs alt)]
--
indexExpr i = mkApps (Var indexP) [Type elemTy, Var var, mkIntExpr dflags i]
{-
************************************************************************
* *
\subsection{Desugarer's versions of some Core functions}
* *
************************************************************************
-}
mkErrorAppDs :: Id -- The error function
-> Type -- Type to which it should be applied
-> SDoc -- The error message string to pass
-> DsM CoreExpr
mkErrorAppDs err_id ty msg = do
src_loc <- getSrcSpanDs
dflags <- getDynFlags
let
full_msg = showSDoc dflags (hcat [ppr src_loc, text "|", msg])
core_msg = Lit (mkMachString full_msg)
-- mkMachString returns a result of type String#
return (mkApps (Var err_id) [Type ty, core_msg])
{-
'mkCoreAppDs' and 'mkCoreAppsDs' hand the special-case desugaring of 'seq'.
Note [Desugaring seq (1)] cf Trac #1031
~~~~~~~~~~~~~~~~~~~~~~~~~
f x y = x `seq` (y `seq` (# x,y #))
The [CoreSyn let/app invariant] means that, other things being equal, because
the argument to the outer 'seq' has an unlifted type, we'll use call-by-value thus:
f x y = case (y `seq` (# x,y #)) of v -> x `seq` v
But that is bad for two reasons:
(a) we now evaluate y before x, and
(b) we can't bind v to an unboxed pair
Seq is very, very special! So we recognise it right here, and desugar to
case x of _ -> case y of _ -> (# x,y #)
Note [Desugaring seq (2)] cf Trac #2273
~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
let chp = case b of { True -> fst x; False -> 0 }
in chp `seq` ...chp...
Here the seq is designed to plug the space leak of retaining (snd x)
for too long.
If we rely on the ordinary inlining of seq, we'll get
let chp = case b of { True -> fst x; False -> 0 }
case chp of _ { I# -> ...chp... }
But since chp is cheap, and the case is an alluring contet, we'll
inline chp into the case scrutinee. Now there is only one use of chp,
so we'll inline a second copy. Alas, we've now ruined the purpose of
the seq, by re-introducing the space leak:
case (case b of {True -> fst x; False -> 0}) of
I# _ -> ...case b of {True -> fst x; False -> 0}...
We can try to avoid doing this by ensuring that the binder-swap in the
case happens, so we get his at an early stage:
case chp of chp2 { I# -> ...chp2... }
But this is fragile. The real culprit is the source program. Perhaps we
should have said explicitly
let !chp2 = chp in ...chp2...
But that's painful. So the code here does a little hack to make seq
more robust: a saturated application of 'seq' is turned *directly* into
the case expression, thus:
x `seq` e2 ==> case x of x -> e2 -- Note shadowing!
e1 `seq` e2 ==> case x of _ -> e2
So we desugar our example to:
let chp = case b of { True -> fst x; False -> 0 }
case chp of chp { I# -> ...chp... }
And now all is well.
The reason it's a hack is because if you define mySeq=seq, the hack
won't work on mySeq.
Note [Desugaring seq (3)] cf Trac #2409
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The isLocalId ensures that we don't turn
True `seq` e
into
case True of True { ... }
which stupidly tries to bind the datacon 'True'.
-}
mkCoreAppDs :: CoreExpr -> CoreExpr -> CoreExpr
mkCoreAppDs (Var f `App` Type ty1 `App` Type ty2 `App` arg1) arg2
| f `hasKey` seqIdKey -- Note [Desugaring seq (1), (2)]
= Case arg1 case_bndr ty2 [(DEFAULT,[],arg2)]
where
case_bndr = case arg1 of
Var v1 | isLocalId v1 -> v1 -- Note [Desugaring seq (2) and (3)]
_ -> mkWildValBinder ty1
mkCoreAppDs fun arg = mkCoreApp fun arg -- The rest is done in MkCore
mkCoreAppsDs :: CoreExpr -> [CoreExpr] -> CoreExpr
mkCoreAppsDs fun args = foldl mkCoreAppDs fun args
{-
************************************************************************
* *
\subsection[mkSelectorBind]{Make a selector bind}
* *
************************************************************************
This is used in various places to do with lazy patterns.
For each binder $b$ in the pattern, we create a binding:
\begin{verbatim}
b = case v of pat' -> b'
\end{verbatim}
where @pat'@ is @pat@ with each binder @b@ cloned into @b'@.
ToDo: making these bindings should really depend on whether there's
much work to be done per binding. If the pattern is complex, it
should be de-mangled once, into a tuple (and then selected from).
Otherwise the demangling can be in-line in the bindings (as here).
Boring! Boring! One error message per binder. The above ToDo is
even more helpful. Something very similar happens for pattern-bound
expressions.
Note [mkSelectorBinds]
~~~~~~~~~~~~~~~~~~~~~~
Given p = e, where p binds x,y
we are going to make EITHER
EITHER (A) v = e (where v is fresh)
x = case v of p -> x
y = case v of p -> y
OR (B) t = case e of p -> (x,y)
x = case t of (x,_) -> x
y = case t of (_,y) -> y
We do (A) when
* Matching the pattern is cheap so we don't mind
doing it twice.
* Or if the pattern binds only one variable (so we'll only
match once)
* AND the pattern can't fail (else we tiresomely get two inexhaustive
pattern warning messages)
Otherwise we do (B). Really (A) is just an optimisation for very common
cases like
Just x = e
(p,q) = e
-}
mkSelectorBinds :: [[Tickish Id]] -- ticks to add, possibly
-> LPat Id -- The pattern
-> CoreExpr -- Expression to which the pattern is bound
-> DsM [(Id,CoreExpr)]
mkSelectorBinds ticks (L _ (VarPat v)) val_expr
= return [(v, case ticks of
[t] -> mkOptTickBox t val_expr
_ -> val_expr)]
mkSelectorBinds ticks pat val_expr
| null binders
= return []
| isSingleton binders || is_simple_lpat pat
-- See Note [mkSelectorBinds]
= do { val_var <- newSysLocalDs (hsLPatType pat)
-- Make up 'v' in Note [mkSelectorBinds]
-- NB: give it the type of *pattern* p, not the type of the *rhs* e.
-- This does not matter after desugaring, but there's a subtle
-- issue with implicit parameters. Consider
-- (x,y) = ?i
-- Then, ?i is given type {?i :: Int}, a PredType, which is opaque
-- to the desugarer. (Why opaque? Because newtypes have to be. Why
-- does it get that type? So that when we abstract over it we get the
-- right top-level type (?i::Int) => ...)
--
-- So to get the type of 'v', use the pattern not the rhs. Often more
-- efficient too.
-- For the error message we make one error-app, to avoid duplication.
-- But we need it at different types, so we make it polymorphic:
-- err_var = /\a. iRREFUT_PAT_ERR a "blah blah blah"
; err_app <- mkErrorAppDs iRREFUT_PAT_ERROR_ID alphaTy (ppr pat)
; err_var <- newSysLocalDs (mkForAllTy alphaTyVar alphaTy)
; binds <- zipWithM (mk_bind val_var err_var) ticks' binders
; return ( (val_var, val_expr) :
(err_var, Lam alphaTyVar err_app) :
binds ) }
| otherwise
= do { error_expr <- mkErrorAppDs iRREFUT_PAT_ERROR_ID tuple_ty (ppr pat)
; tuple_expr <- matchSimply val_expr PatBindRhs pat local_tuple error_expr
; tuple_var <- newSysLocalDs tuple_ty
; let mk_tup_bind tick binder
= (binder, mkOptTickBox tick $
mkTupleSelector local_binders binder
tuple_var (Var tuple_var))
; return ( (tuple_var, tuple_expr) : zipWith mk_tup_bind ticks' binders ) }
where
binders = collectPatBinders pat
ticks' = ticks ++ repeat []
local_binders = map localiseId binders -- See Note [Localise pattern binders]
local_tuple = mkBigCoreVarTup binders
tuple_ty = exprType local_tuple
mk_bind scrut_var err_var tick bndr_var = do
-- (mk_bind sv err_var) generates
-- bv = case sv of { pat -> bv; other -> err_var @ type-of-bv }
-- Remember, pat binds bv
rhs_expr <- matchSimply (Var scrut_var) PatBindRhs pat
(Var bndr_var) error_expr
return (bndr_var, mkOptTickBox tick rhs_expr)
where
error_expr = Var err_var `App` Type (idType bndr_var)
is_simple_lpat p = is_simple_pat (unLoc p)
is_simple_pat (TuplePat ps Boxed _) = all is_triv_lpat ps
is_simple_pat pat@(ConPatOut{}) = case unLoc (pat_con pat) of
RealDataCon con -> isProductTyCon (dataConTyCon con)
&& all is_triv_lpat (hsConPatArgs (pat_args pat))
PatSynCon _ -> False
is_simple_pat (VarPat _) = True
is_simple_pat (ParPat p) = is_simple_lpat p
is_simple_pat _ = False
is_triv_lpat p = is_triv_pat (unLoc p)
is_triv_pat (VarPat _) = True
is_triv_pat (WildPat _) = True
is_triv_pat (ParPat p) = is_triv_lpat p
is_triv_pat _ = False
{-
Creating big tuples and their types for full Haskell expressions.
They work over *Ids*, and create tuples replete with their types,
which is whey they are not in HsUtils.
-}
mkLHsPatTup :: [LPat Id] -> LPat Id
mkLHsPatTup [] = noLoc $ mkVanillaTuplePat [] Boxed
mkLHsPatTup [lpat] = lpat
mkLHsPatTup lpats = L (getLoc (head lpats)) $
mkVanillaTuplePat lpats Boxed
mkLHsVarPatTup :: [Id] -> LPat Id
mkLHsVarPatTup bs = mkLHsPatTup (map nlVarPat bs)
mkVanillaTuplePat :: [OutPat Id] -> Boxity -> Pat Id
-- A vanilla tuple pattern simply gets its type from its sub-patterns
mkVanillaTuplePat pats box = TuplePat pats box (map hsLPatType pats)
-- The Big equivalents for the source tuple expressions
mkBigLHsVarTup :: [Id] -> LHsExpr Id
mkBigLHsVarTup ids = mkBigLHsTup (map nlHsVar ids)
mkBigLHsTup :: [LHsExpr Id] -> LHsExpr Id
mkBigLHsTup = mkChunkified mkLHsTupleExpr
-- The Big equivalents for the source tuple patterns
mkBigLHsVarPatTup :: [Id] -> LPat Id
mkBigLHsVarPatTup bs = mkBigLHsPatTup (map nlVarPat bs)
mkBigLHsPatTup :: [LPat Id] -> LPat Id
mkBigLHsPatTup = mkChunkified mkLHsPatTup
{-
************************************************************************
* *
\subsection[mkFailurePair]{Code for pattern-matching and other failures}
* *
************************************************************************
Generally, we handle pattern matching failure like this: let-bind a
fail-variable, and use that variable if the thing fails:
\begin{verbatim}
let fail.33 = error "Help"
in
case x of
p1 -> ...
p2 -> fail.33
p3 -> fail.33
p4 -> ...
\end{verbatim}
Then
\begin{itemize}
\item
If the case can't fail, then there'll be no mention of @fail.33@, and the
simplifier will later discard it.
\item
If it can fail in only one way, then the simplifier will inline it.
\item
Only if it is used more than once will the let-binding remain.
\end{itemize}
There's a problem when the result of the case expression is of
unboxed type. Then the type of @fail.33@ is unboxed too, and
there is every chance that someone will change the let into a case:
\begin{verbatim}
case error "Help" of
fail.33 -> case ....
\end{verbatim}
which is of course utterly wrong. Rather than drop the condition that
only boxed types can be let-bound, we just turn the fail into a function
for the primitive case:
\begin{verbatim}
let fail.33 :: Void -> Int#
fail.33 = \_ -> error "Help"
in
case x of
p1 -> ...
p2 -> fail.33 void
p3 -> fail.33 void
p4 -> ...
\end{verbatim}
Now @fail.33@ is a function, so it can be let-bound.
-}
mkFailurePair :: CoreExpr -- Result type of the whole case expression
-> DsM (CoreBind, -- Binds the newly-created fail variable
-- to \ _ -> expression
CoreExpr) -- Fail variable applied to realWorld#
-- See Note [Failure thunks and CPR]
mkFailurePair expr
= do { fail_fun_var <- newFailLocalDs (voidPrimTy `mkFunTy` ty)
; fail_fun_arg <- newSysLocalDs voidPrimTy
; let real_arg = setOneShotLambda fail_fun_arg
; return (NonRec fail_fun_var (Lam real_arg expr),
App (Var fail_fun_var) (Var voidPrimId)) }
where
ty = exprType expr
{-
Note [Failure thunks and CPR]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we make a failure point we ensure that it
does not look like a thunk. Example:
let fail = \rw -> error "urk"
in case x of
[] -> fail realWorld#
(y:ys) -> case ys of
[] -> fail realWorld#
(z:zs) -> (y,z)
Reason: we know that a failure point is always a "join point" and is
entered at most once. Adding a dummy 'realWorld' token argument makes
it clear that sharing is not an issue. And that in turn makes it more
CPR-friendly. This matters a lot: if you don't get it right, you lose
the tail call property. For example, see Trac #3403.
-}
mkOptTickBox :: [Tickish Id] -> CoreExpr -> CoreExpr
mkOptTickBox = flip (foldr Tick)
mkBinaryTickBox :: Int -> Int -> CoreExpr -> DsM CoreExpr
mkBinaryTickBox ixT ixF e = do
uq <- newUnique
this_mod <- getModule
let bndr1 = mkSysLocal (fsLit "t1") uq boolTy
let
falseBox = Tick (HpcTick this_mod ixF) (Var falseDataConId)
trueBox = Tick (HpcTick this_mod ixT) (Var trueDataConId)
--
return $ Case e bndr1 boolTy
[ (DataAlt falseDataCon, [], falseBox)
, (DataAlt trueDataCon, [], trueBox)
]
|
green-haskell/ghc
|
compiler/deSugar/DsUtils.hs
|
bsd-3-clause
| 31,776
| 0
| 19
| 8,857
| 5,108
| 2,657
| 2,451
| -1
| -1
|
module A1 where
import D1
sumSq xs ys = (sum (map sq xs)) + (sumSquares xs)
main = sumSq [1 .. 4]
|
kmate/HaRe
|
old/testing/rmOneParameter/A1_AstOut.hs
|
bsd-3-clause
| 101
| 0
| 9
| 25
| 55
| 30
| 25
| 4
| 1
|
module Golf where
-----------
-- Skips --
-----------
every :: Int -> [a] -> [a]
every n xs = case drop (n-1) xs of
(y:ys) -> y : every n ys
[] -> []
skips :: [a] -> [[a]]
skips xs = map (\n -> every n xs) [1..length xs]
------------------
-- Local Maxima --
------------------
take3 n xs = take 3 (drop n xs)
triads xs = map (\n -> take3 n xs) [0..length xs - 3]
findLocalMaxima :: [Integer] -> [Integer]
findLocalMaxima (x1:x2:x3:[]) = if x2 > x1 && x2 > x3 then [x2] else []
findLocalMaxima [] = []
localMaxima :: [Integer] -> [Integer]
localMaxima xs = concat $ map findLocalMaxima (triads xs)
localMaxima' :: [Int] -> [Int]
localMaxima' (x:y:z:rest)
| y > x && y > z = y : localMaxima' (y:z:rest)
| otherwise = localMaxima' (y:z:rest)
localMaxima' _ = []
-----------------
-- Histogram --
-----------------
select :: Int -> [Int] -> [Int]
select n xs = filter (\x -> x == n) xs
selectCount :: Int -> [Int] -> Int
selectCount n xs = length $ select n xs
hist :: [Int] -> [Int]
hist xs = map (\n -> selectCount n xs) [0..9]
writeHist :: [Int] -> [String]
writeHist xs = case zeroes xs of
True -> []
False -> (writeLine xs ++ "\n") : (writeHist (map decrementToZero xs))
decrementToZero :: Int -> Int
decrementToZero 0 = 0
decrementToZero x = x - 1
zeroes :: [Int] -> Bool
zeroes [0] = True
zeroes (0:xs) = zeroes xs
zeroes (_:xs) = False
writeLine :: [Int] -> String
writeLine (x:xs)
| x > 0 = "*" ++ writeLine xs
| otherwise = " " ++ writeLine xs
writeLine [] = []
histogram :: [Int] -> String
histogram xs = (concat . reverse . writeHist . hist $ xs)
++ "==========\n"
++ "0123456789\n"
l :: [Int]
l = [1,4,5,4,6,6,3,4,2,4,9]
|
dzeban/haskell-exercises
|
hw3/Golf.hs
|
mit
| 1,704
| 0
| 12
| 386
| 874
| 466
| 408
| 47
| 2
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Facebook
import Network.HTTP.Conduit (withManager)
import Control.Monad.IO.Class (liftIO)
import Data.Text (pack, Text(..))
import Control.Applicative ((<$>), (*>))
printUser :: Text -> IO ()
printUser x = withManager . flip runNoAuthFacebookT
$ getUser (Id { idCode = x }) [] Nothing
>>= liftIO . (\(Just s) -> print s) . userName
main :: IO ()
main = (pack <$> getLine >>= printUser) *> main
|
Fresheyeball/facebook-haskell-sandbox
|
Main.hs
|
mit
| 480
| 0
| 12
| 95
| 177
| 102
| 75
| 13
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE UndecidableInstances #-}
module AI.Funn.TypeLits (withNat, CLog, Max) where
import Data.Constraint
import Data.Ord
import Data.Proxy
import GHC.TypeLits
import GHC.TypeLits.KnownNat
import Test.QuickCheck
withNat :: Integer -> (forall n. (KnownNat n) => Proxy n -> r) -> r
withNat n f = case someNatVal n of
Just (SomeNat proxy) -> f proxy
Nothing -> error ("withNat: negative value (" ++ show n ++ ")")
type family RunOrdering (o :: Ordering) (a :: k) (b :: k) (c :: k) :: k where
RunOrdering LT a _ _ = a
RunOrdering EQ _ b _ = b
RunOrdering GT _ _ c = c
-- Max: Maximum of two nats
-- instance (KnownNat a, KnownNat b) => KnownNat (Max a b)
type family Max (a :: Nat) (b :: Nat) :: Nat where
Max 0 b = b
Max a 0 = a
Max a b = RunOrdering (CmpNat a b)
b a a
instance (KnownNat a, KnownNat b) => KnownNat2 "AI.Funn.TypeLits.Max" a b where
natSing2 = let x = natVal (Proxy :: Proxy a)
y = natVal (Proxy :: Proxy b)
z = max x y
in SNatKn (fromIntegral z)
-- CLog x: exact integer equivalent of ceiling (logBase 2 x)
-- instance (KnownNat a) => KnownNat (CLog a)
type family CLog n where
CLog 0 = 0
CLog n = CLog32 n
type CLog1 n = RunOrdering (CmpNat (2^1) n) 2 1 0
type CLog2 n = RunOrdering (CmpNat (2^2) n) 3 2 (CLog1 n)
type CLog3 n = RunOrdering (CmpNat (2^3) n) 4 3 (CLog2 n)
type CLog4 n = RunOrdering (CmpNat (2^4) n) 5 4 (CLog3 n)
type CLog5 n = RunOrdering (CmpNat (2^5) n) 6 5 (CLog4 n)
type CLog6 n = RunOrdering (CmpNat (2^6) n) 7 6 (CLog5 n)
type CLog7 n = RunOrdering (CmpNat (2^7) n) 8 7 (CLog6 n)
type CLog8 n = RunOrdering (CmpNat (2^8) n) 9 8 (CLog7 n)
type CLog9 n = RunOrdering (CmpNat (2^9) n) 10 9 (CLog8 n)
type CLog10 n = RunOrdering (CmpNat (2^10) n) 11 10 (CLog9 n)
type CLog11 n = RunOrdering (CmpNat (2^11) n) 12 11 (CLog10 n)
type CLog12 n = RunOrdering (CmpNat (2^12) n) 13 12 (CLog11 n)
type CLog13 n = RunOrdering (CmpNat (2^13) n) 14 13 (CLog12 n)
type CLog14 n = RunOrdering (CmpNat (2^14) n) 15 14 (CLog13 n)
type CLog15 n = RunOrdering (CmpNat (2^15) n) 16 15 (CLog14 n)
type CLog16 n = RunOrdering (CmpNat (2^16) n) 17 16 (CLog15 n)
type CLog17 n = RunOrdering (CmpNat (2^17) n) 18 17 (CLog16 n)
type CLog18 n = RunOrdering (CmpNat (2^18) n) 19 18 (CLog17 n)
type CLog19 n = RunOrdering (CmpNat (2^19) n) 20 19 (CLog18 n)
type CLog20 n = RunOrdering (CmpNat (2^20) n) 21 20 (CLog19 n)
type CLog21 n = RunOrdering (CmpNat (2^21) n) 22 21 (CLog20 n)
type CLog22 n = RunOrdering (CmpNat (2^22) n) 23 22 (CLog21 n)
type CLog23 n = RunOrdering (CmpNat (2^23) n) 24 23 (CLog22 n)
type CLog24 n = RunOrdering (CmpNat (2^24) n) 25 24 (CLog23 n)
type CLog25 n = RunOrdering (CmpNat (2^25) n) 26 25 (CLog24 n)
type CLog26 n = RunOrdering (CmpNat (2^26) n) 27 26 (CLog25 n)
type CLog27 n = RunOrdering (CmpNat (2^27) n) 28 27 (CLog26 n)
type CLog28 n = RunOrdering (CmpNat (2^28) n) 29 28 (CLog27 n)
type CLog29 n = RunOrdering (CmpNat (2^29) n) 30 29 (CLog28 n)
type CLog30 n = RunOrdering (CmpNat (2^30) n) 31 30 (CLog29 n)
type CLog31 n = RunOrdering (CmpNat (2^31) n) 32 31 (CLog30 n)
type CLog32 n = RunOrdering (CmpNat (2^32) n) 33 32 (CLog31 n)
cLog :: Integer -> Integer
cLog n = go 32
where
go 0 = 0
go s = case compare (2^s) n of
LT -> s + 1
EQ -> s
GT -> go (s - 1)
instance (KnownNat a) => KnownNat1 "AI.Funn.TypeLits.CLog" a where
natSing1 = let x = natVal (Proxy :: Proxy a)
in SNatKn (fromIntegral $ cLog x)
-- cLogTest :: Integer -> Integer
-- cLogTest n = withNat n $ \(Proxy :: Proxy n) ->
-- natVal (Proxy :: Proxy (CLog n))
-- prop_cLogTypeLevel :: Property
-- prop_cLogTypeLevel = property $ \n -> n >= 0 ==> cLog n == cLogTest n
-- prop_cLogDefinition :: Property
-- prop_cLogDefinition = property $ \n -> n >= 0 ==> 2^(cLog n) >= n
-- prop_cLogDefinition' :: Property
-- prop_cLogDefinition' = property $ \n -> n >= 2 ==> 2^(cLog n - 1) < n
|
nshepperd/funn
|
AI/Funn/TypeLits.hs
|
mit
| 4,311
| 0
| 12
| 1,013
| 1,757
| 957
| 800
| 80
| 4
|
-- This is a sample config file
import Haystack.Lib
main = haystackConfig $ defaultConfig { message = "HELLO WORLD" }
|
ajnsit/haystack
|
haystack.hs
|
mit
| 119
| 0
| 7
| 21
| 24
| 14
| 10
| 2
| 1
|
{-
Pattern match compilation + exhaustiveness check
Ideas came mainly from the following sources:
- "GADTs meet their match"
- "The implementation of functional programming languages", Chapter 5, "Efficient compilation of pattern matching"
-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
import Data.List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Data.Either
import Control.Arrow ((***))
import Control.Monad.Identity
import Control.Monad.State
import Control.Monad.Writer hiding (Alt)
import Text.Show.Pretty (ppShow)
-------------------------------------------------------------------------------- Name generator monad
type NewName = StateT Int
newName :: Monad m => NewName m String
newName = state $ \i -> ("v" ++ show i, i + 1)
-------------------------------------------------------------------------------- data types
type Loc = Int -- location info
type VarName = String
type ConName = String
------------------------------- source data structure
{-
match a b c with
(x:y) (f x -> Just ((>3) -> True)) v@(_:_)@v'@(g -> True)
| x > 4 -> ...
| Just (z: v) <- h y, Nothing <- h' z, h'' v -> ...
| ...
where
...
...
-}
{-
match a with
x: y | [] <- a -> ... x ... y ... z ... v ...
-}
data Match = Match [VarName] [Clause] -- match expression (generalized case expression)
data Clause = Clause Loc [ParPat] GuardTree
type ParPat = [Pat] -- parallel patterns like v@(f -> [])@(Just x)
data Pat
= PVar VarName
| Con ConName [ParPat]
| ViewPat Exp ParPat
deriving Show
data GuardTree
= GuardNode Loc Exp ConName [ParPat] GuardTree
| Where Binds GuardTree
| Alts [GuardTree]
| GuardLeaf Loc Exp
deriving Show
type Binds = [(VarName, Exp)]
unWhereAlts :: GuardTree -> Maybe (Binds, [GuardTree])
unWhereAlts = f [] where
f acc = \case
Where bs t -> f (acc ++ bs) t
Alts xs -> g acc xs
x -> Just (acc, [x])
g acc [] = Nothing
g acc (x: xs) = case unWhereAlts x of
Nothing -> g acc xs
Just (wh, ts) -> Just (acc ++ wh, ts ++ xs)
guardNode :: Loc -> Exp -> ParPat -> GuardTree -> GuardTree
guardNode i v [] e = e
guardNode i v (w: ws) e = case w of
PVar x -> guardNode i v (subst x v ws) $ subst x v e -- don't use let instead
ViewPat f p -> guardNode i (ViewApp f v) p $ guardNode i v ws e
Con s ps' -> GuardNode i v s ps' $ guardNode i v ws e
guardNodes :: Loc -> [(Exp, ParPat)] -> GuardTree -> GuardTree
guardNodes _ [] l = l
guardNodes i ((v, ws): vs) e = guardNode i v ws $ guardNodes i vs e
type CasesInfo = [(Exp, Either (String, [String]) (Exp, Exp))]
type InfoWriter = Writer ([Loc], [Loc], [CasesInfo])
------------------------------- target data structures
data Exp
= IdExp (Map VarName Exp) Loc -- arbitrary expression
| Undefined
| Otherwise
| Case Exp [Alt]
| Var VarName
| ViewApp Exp Exp
| Let Binds Exp
deriving (Show, Eq)
where_ [] = id
where_ bs = Let bs
data Alt = Alt ConName [VarName] Exp
deriving (Show, Eq)
getId = \case
IdExp _ i -> i
data Info
= Uncovered [ParPat]
| Inaccessible Int
| Removable Int
| Shared Int Int
deriving Show
-------------------------------------------------------------------------------- conversions between data structures
matchToGuardTree :: Match -> GuardTree
matchToGuardTree (Match vs cs)
= Alts $ flip map cs $ \(Clause i ps rhs) ->
guardNodes i (zip (map Var vs) ps) rhs
guardTreeToCases :: CasesInfo -> GuardTree -> NewName InfoWriter Exp
guardTreeToCases seq t = case unWhereAlts t of
Nothing -> tell ([], [], [seq]) >> return Undefined
Just (wh, GuardLeaf i e: _) -> tell ([i], [], []) >> return (where_ wh e)
Just (wh, cs@(GuardNode i f s _ _: _)) -> do
tell ([], [i], [])
where_ wh . Case f <$> sequence
[ do
ns <- replicateM cv newName
fmap (Alt cn ns) $ guardTreeToCases ((f, Left (cn, ns)): appAdd f seq) $ Alts $ map (filterGuardTree f cn ns) cs
| (cn, cv) <- fromJust $ find ((s `elem`) . map fst) contable
]
e -> error $ "gtc: " ++ show e
where
appAdd (ViewApp f v) x = (v, Right (f, ViewApp f v)): appAdd v x
appAdd _ x = x
filterGuardTree :: Exp -> ConName -> [VarName] -> GuardTree -> GuardTree
filterGuardTree f s ns = \case
Where bs t -> Where bs $ filterGuardTree f s ns t -- TODO: shadowing
Alts ts -> Alts $ map (filterGuardTree f s ns) ts
GuardLeaf i e -> GuardLeaf i e
GuardNode i f' s' ps gs
| f /= f' -> GuardNode i f' s' ps $ filterGuardTree f s ns gs
| s == s' -> filterGuardTree f s ns $ guardNodes i (zip (map Var ns) ps) gs
| otherwise -> Alts []
mkInfo :: Int -> InfoWriter ([VarName], Exp) -> (Exp, [Info])
mkInfo i (runWriter -> ((ns, e'), (is, nub -> js, us)))
= ( e'
, [ (if n > 1 then Shared n else if j `elem` js then Inaccessible else Removable) j
| j <- [1..i], let n = length $ filter (==j) is, n /= 1
] ++ map (Uncovered . mkPat (map Var ns)) us
)
where
mkPat :: [Exp] -> CasesInfo -> [ParPat]
mkPat ns ls = map f ns
where
f v' = mconcat [either (\(s, vs) -> [Con s $ map (f . Var) vs]) (\(s, v) -> [ViewPat s $ f v]) ps | (v, ps) <- ls, v == v']
tester :: [[ParPat]] -> IO ()
tester cs@(ps: _) = putStrLn . ppShow . mkInfo (length cs) . flip evalStateT 1 $ do
vs <- replicateM (length ps) newName
let gs = matchToGuardTree $ Match vs $ zipWith (\a i -> Clause i a $ GuardLeaf i $ IdExp mempty i) cs [1..]
(,) vs <$> guardTreeToCases [] gs
-------------------------------------------------------------------------------- substitution
class Subst a where subst :: VarName -> Exp -> a -> a
substs :: (Subst b) => Binds -> b -> b
substs rs g = foldr (uncurry subst) g rs
instance Subst a => Subst [a] where subst a b = map (subst a b)
instance (Subst a, Subst b) => Subst (a, b) where subst a b (c, d) = (subst a b c, subst a b d)
instance Subst Exp where
subst a b = \case
Var v | v == a -> b
| otherwise -> Var v
ViewApp f x -> ViewApp (subst a b f) (subst a b x)
IdExp m i -> IdExp (Map.insert a b $ subst a b <$> m) i
instance Subst Pat where
subst as v = \case
Con s ps -> Con s $ map (subst as v) ps
ViewPat f p -> ViewPat (subst as v f) $ subst as v p
PVar x -> PVar x
instance Subst GuardTree where
subst a b = \case
Alts ts -> Alts $ subst a b ts
Where bs e -> Where (map (id *** subst a b) bs) $ subst a b e
GuardNode i e y z x -> GuardNode i (subst a b e) y (subst a b z) $ subst a b x
GuardLeaf i e -> GuardLeaf i (subst a b e)
-------------------------------------------------------------------------------- constructors
contable =
[ ["Nil" # 0, "Cons" # 2]
, ["False" # 0, "True" # 0]
, ["Nothing" # 0, "Just" # 1]
] where (#) = (,)
pattern Nil = Con' "Nil" []
pattern Cons a b = Con' "Cons" [a, b]
pattern T = Con' "True" []
pattern F = Con' "False" []
pattern No = Con' "Nothing" []
pattern Ju a = Con' "Just" [a]
pattern W = []
pattern V v = [PVar v]
pattern Con' s ps = [Con s ps]
pattern Vi f p = [ViewPat (Var f) p]
pattern Guard e = (e, T)
-------------------------------------------------------------------------------- test cases
diagonal_test = tester
[ [W, T, F]
, [F, W, T]
, [T, F, W]
]
seq_test = tester
[ [W, F]
, [T, F]
, [W, W]
]
reverseTwo_test = tester
[ [Cons (V "x") (Cons (V "y") Nil)]
, [V "xs"]
]
xor_test = tester
[ [V "x", F]
, [F, T]
, [T, T]
]
unwieldy_test = tester
[ [Nil, Nil]
, [V "xs", V "ys"]
]
last_test = tester
[ [Cons (V "x") Nil]
, [Cons (V "y") (V "xs")]
]
last_test' = tester
[ [Cons (V "x") Nil]
, [Cons (V "y") (Cons (V "x") (V "xs"))]
]
zipWith_test = tester
[ [V "g", Nil, W]
, [V "f", W, Nil]
, [V "f", Cons (V "x") (V "xs"), Cons (V "y") (V "ys")]
]
zipWith_test' = tester
[ [V "f", Cons (V "x") (V "xs"), Cons (V "y") (V "ys")]
, [V "g", W, W]
]
zipWith_test'' = tester
[ [V "f", Cons (V "x") (V "xs"), Cons (V "y") (V "ys")]
, [V "g", Nil, Nil]
]
uncovered_test = tester
[ [Cons (V "x") $ Cons (V "y") $ Cons (V "z") (V "v")] ]
view_test = tester
[ [Vi "f" (Cons (V "y") (V "s"))] ]
view_test' = tester
[ [Vi "f" (Cons (Vi "g" $ Ju (V "y")) (V "s"))]
, [Vi "h" T]
]
view_test'' = tester
[ [V "x", [ViewPat (ViewApp (Var "f") (Var "x")) (T `mappend` V "q")] `mappend` V "z"] ] -- TODO: prevent V "q" expansion
guard_test = tester
[ [V "x" `mappend` Vi "graterThan5" T]
, [V "x"]
]
|
BP-HUG/presentations
|
2016_april/pattern-match-compilation/PatCompile.hs
|
mit
| 9,177
| 0
| 23
| 2,675
| 3,802
| 1,991
| 1,811
| 203
| 5
|
{-# Language FlexibleInstances, GeneralizedNewtypeDeriving #-}
{- |
Module : Language.Egison.Desugar
Copyright : Satoshi Egi
Licence : MIT
This module provide desugar functions.
-}
module Language.Egison.Desugar
(
DesugarM
, runDesugarM
, desugarTopExpr
, desugarExpr
, desugar
) where
import Control.Applicative (Applicative)
import Control.Applicative ((<$>), (<*>), (<*), (*>), pure)
import qualified Data.Sequence as Sq
import Data.Sequence (ViewL(..), (<|))
import qualified Data.Set as S
import Data.Set (Set)
import Data.Char (toUpper)
import Control.Monad.Error
import Control.Monad.Reader
import Language.Egison.Types
type Subst = [(String, EgisonExpr)]
newtype DesugarM a = DesugarM { unDesugarM :: ReaderT Subst (ErrorT EgisonError Fresh) a }
deriving (Functor, Applicative, Monad, MonadError EgisonError, MonadFresh, MonadReader Subst)
runDesugarM :: DesugarM a -> Fresh (Either EgisonError a)
runDesugarM = runErrorT . flip runReaderT [] . unDesugarM
desugarTopExpr :: EgisonTopExpr -> EgisonM EgisonTopExpr
desugarTopExpr (Define name expr) = do
expr' <- liftEgisonM $ runDesugarM $ desugar expr
return (Define name expr')
desugarTopExpr (Test expr) = do
expr' <- liftEgisonM $ runDesugarM $ desugar expr
return (Test expr')
desugarTopExpr (Execute expr) = do
expr' <- liftEgisonM $ runDesugarM $ desugar expr
return (Execute expr')
desugarTopExpr expr = return expr
desugarExpr :: EgisonExpr -> EgisonM EgisonExpr
desugarExpr expr = liftEgisonM $ runDesugarM $ desugar expr
desugar :: EgisonExpr -> DesugarM EgisonExpr
desugar (AlgebraicDataMatcherExpr patterns) = do
matcherName <- fresh
matcherRef <- return $ VarExpr matcherName
matcher <- genMatcherClauses patterns matcherRef
return $ LetRecExpr [([matcherName], matcher)] matcherRef
where
genMatcherClauses :: [(String, [EgisonExpr])] -> EgisonExpr -> DesugarM EgisonExpr
genMatcherClauses patterns matcher = do
main <- genMainClause patterns matcher
body <- mapM genMatcherClause patterns
footer <- genSomethingClause
clauses <- return $ [main] ++ body ++ [footer]
return $ MatcherDFSExpr clauses
genMainClause :: [(String, [EgisonExpr])] -> EgisonExpr -> DesugarM (PrimitivePatPattern, EgisonExpr, [(PrimitiveDataPattern, EgisonExpr)])
genMainClause patterns matcher = do
clauses <- genClauses patterns
return (PPValuePat "val", TupleExpr []
,[(PDPatVar "tgt", (MatchExpr (TupleExpr [(VarExpr "val"), (VarExpr "tgt")])
(TupleExpr [matcher, matcher])
clauses))])
where
genClauses :: [(String, [EgisonExpr])] -> DesugarM [MatchClause]
genClauses patterns = (++) <$> mapM genClause patterns
<*> pure [((TuplePat [WildCard, WildCard]), matchingFailure)]
genClause :: (String, [EgisonExpr]) -> DesugarM MatchClause
genClause pattern = do
(pat0, pat1) <- genMatchingPattern pattern
return (TuplePat [pat0, pat1], matchingSuccess)
genMatchingPattern :: (String, [EgisonExpr]) -> DesugarM (EgisonPattern, EgisonPattern)
genMatchingPattern (name, patterns) = do
names <- mapM (const fresh) patterns
return $ ((InductivePat name (map PatVar names))
,(InductivePat name (map (ValuePat . VarExpr) names)))
genMatcherClause :: (String, [EgisonExpr]) -> DesugarM (PrimitivePatPattern, EgisonExpr, [(PrimitiveDataPattern, EgisonExpr)])
genMatcherClause pattern = do
(ppat, matchers) <- genPrimitivePatPat pattern
(dpat, body) <- genPrimitiveDataPat pattern
return (ppat, TupleExpr matchers, [(dpat, CollectionExpr [ElementExpr . TupleExpr $ body]), (PDWildCard, matchingFailure)])
where
genPrimitivePatPat :: (String, [EgisonExpr]) -> DesugarM (PrimitivePatPattern, [EgisonExpr])
genPrimitivePatPat (name, matchers) = do
patterns' <- mapM (const $ return PPPatVar) matchers
return (PPInductivePat name patterns', matchers)
genPrimitiveDataPat :: (String, [EgisonExpr]) -> DesugarM (PrimitiveDataPattern, [EgisonExpr])
genPrimitiveDataPat (name, patterns) = do
patterns' <- mapM (const fresh) patterns
return (PDInductivePat (capitalize name) $ map PDPatVar patterns', map VarExpr patterns')
capitalize :: String -> String
capitalize (x:xs) = toUpper x : xs
genSomethingClause :: DesugarM (PrimitivePatPattern, EgisonExpr, [(PrimitiveDataPattern, EgisonExpr)])
genSomethingClause =
return (PPPatVar, (TupleExpr [SomethingExpr]), [(PDPatVar "tgt", CollectionExpr [ElementExpr (VarExpr "tgt")])])
matchingSuccess :: EgisonExpr
matchingSuccess = CollectionExpr [ElementExpr $ TupleExpr []]
matchingFailure :: EgisonExpr
matchingFailure = CollectionExpr []
desugar (MatchAllLambdaExpr matcher clause) = do
name <- fresh
matcher' <- desugar matcher
clause' <- desugarMatchClause clause
return $ LambdaExpr [name] (MatchAllExpr (VarExpr name) matcher' clause')
desugar (MatchLambdaExpr matcher clauses) = do
name <- fresh
matcher' <- desugar matcher
clauses' <- desugarMatchClauses clauses
return $ LambdaExpr [name] (MatchExpr (VarExpr name) matcher' clauses')
desugar (ArrayRefExpr expr nums) =
case nums of
(TupleExpr nums') -> desugar $ IndexedExpr expr nums'
_ -> desugar $ IndexedExpr expr [nums]
desugar (IndexedExpr expr indices) =
IndexedExpr <$> desugar expr <*> (mapM desugar indices)
desugar (ArraySizeExpr expr) = do
expr' <- desugar expr
return $ ArraySizeExpr expr'
desugar (InductiveDataExpr name exprs) = do
exprs' <- mapM desugar exprs
return $ InductiveDataExpr name exprs'
desugar (TupleExpr exprs) = do
exprs' <- mapM desugar exprs
return $ TupleExpr exprs'
desugar expr@(CollectionExpr []) = return expr
desugar (CollectionExpr ((ElementExpr elm):inners)) = do
elm' <- desugar elm
(CollectionExpr inners') <- desugar (CollectionExpr inners)
return $ CollectionExpr (ElementExpr elm':inners')
desugar (CollectionExpr ((SubCollectionExpr sub):inners)) = do
sub' <- desugar sub
(CollectionExpr inners') <- desugar (CollectionExpr inners)
return $ CollectionExpr (SubCollectionExpr sub':inners')
desugar (LambdaExpr names expr) = do
expr' <- desugar expr
return $ LambdaExpr names expr'
desugar (MemoizedLambdaExpr names expr) = do
expr' <- desugar expr
return $ MemoizedLambdaExpr names expr'
desugar (MemoizeExpr memoizeBindings expr) = do
memoizeBindings' <- mapM (\(x,y,z) -> do x' <- desugar x
y' <- desugar y
z' <- desugar z
return (x',y',z'))
memoizeBindings
expr' <- desugar expr
return $ MemoizeExpr memoizeBindings' expr'
desugar (PatternFunctionExpr names pattern) = do
pattern' <- desugarPattern pattern
return $ PatternFunctionExpr names pattern'
desugar (IfExpr expr0 expr1 expr2) = do
expr0' <- desugar expr0
expr1' <- desugar expr1
expr2' <- desugar expr2
return $ IfExpr expr0' expr1' expr2'
desugar (LetRecExpr binds expr) = do
binds' <- desugarBindings binds
expr' <- desugar expr
return $ LetRecExpr binds' expr'
desugar (LetExpr binds expr) = do
binds' <- desugarBindings binds
expr' <- desugar expr
return $ LetExpr binds' expr'
desugar (LetStarExpr binds expr) = do
binds' <- desugarBindings binds
expr' <- desugar expr
return $ foldr (\bind ret -> LetExpr [bind] ret) expr' binds'
desugar (MatchExpr expr0 expr1 clauses) = do
expr0' <- desugar expr0
expr1' <- desugar expr1
clauses' <- desugarMatchClauses clauses
return (MatchExpr expr0' expr1' clauses')
desugar (MatchAllExpr expr0 expr1 clause) = do
expr0' <- desugar expr0
expr1' <- desugar expr1
clause' <- desugarMatchClause clause
return $ MatchAllExpr expr0' expr1' clause'
desugar (DoExpr binds expr) = do
binds' <- desugarBindings binds
expr' <- desugar expr
return $ DoExpr binds' expr'
desugar (IoExpr expr) = do
expr' <- desugar expr
return $ IoExpr expr'
desugar (SeqExpr expr0 expr1) = do
expr0' <- desugar expr0
expr1' <- desugar expr1
return $ SeqExpr expr0' expr1'
desugar (ApplyExpr (VarExpr "+") expr) = do
expr' <- desugar expr
case expr' of
args@(TupleExpr (_:_:[])) -> return $ ApplyExpr (VarExpr "+") args
(TupleExpr (x:args)) -> return $ ApplyExpr (VarExpr "foldl") (TupleExpr [(VarExpr "+"), x, (CollectionExpr (map ElementExpr args))])
desugar (ApplyExpr (VarExpr "-") expr) = do
expr' <- desugar expr
case expr' of
args@(TupleExpr (_:_:[])) -> return $ ApplyExpr (VarExpr "-") args
(TupleExpr (x:args)) -> return $ ApplyExpr (VarExpr "foldl") (TupleExpr [(VarExpr "-"), x, (CollectionExpr (map ElementExpr args))])
desugar (ApplyExpr (VarExpr "*") expr) = do
expr' <- desugar expr
case expr' of
args@(TupleExpr (_:_:[])) -> return $ ApplyExpr (VarExpr "*") args
(TupleExpr (x:args)) -> return $ ApplyExpr (VarExpr "foldl") (TupleExpr [(VarExpr "*"), x, (CollectionExpr (map ElementExpr args))])
desugar (ApplyExpr expr0 expr1) = do
expr0' <- desugar expr0
expr1' <- desugar expr1
return $ ApplyExpr expr0' expr1'
desugar (VarExpr name) = do
asks $ maybe (VarExpr name) id . lookup name
desugar (MatcherBFSExpr matcherInfo) = do
matcherInfo' <- desugarMatcherInfo matcherInfo
return $ MatcherBFSExpr matcherInfo'
desugar (MatcherDFSExpr matcherInfo) = do
matcherInfo' <- desugarMatcherInfo matcherInfo
return $ MatcherDFSExpr matcherInfo'
desugar (PartialVarExpr n) = return $ VarExpr $ "::" ++ show n
desugar RecVarExpr = return $ VarExpr "::"
desugar (PartialExpr n expr) = do
expr' <- desugar expr
if n == 0
then return $ LetRecExpr [(["::"], LambdaExpr [] expr')] (LambdaExpr [] expr')
else return $ LetRecExpr [(["::"], LambdaExpr (annonVars (fromIntegral n)) expr')] (LambdaExpr (annonVars (fromIntegral n)) expr')
where
annonVars n = take n $ map (((++) "::") . show) [1..]
desugar expr = return expr
desugarPattern :: EgisonPattern -> DesugarM EgisonPattern
desugarPattern pattern = LetPat (map makeBinding $ S.elems $ collectName pattern) <$> desugarPattern' pattern
where
collectNames :: [EgisonPattern] -> Set String
collectNames patterns = S.unions $ map collectName patterns
collectName :: EgisonPattern -> Set String
collectName (NotPat pattern) = collectName pattern
collectName (AndPat patterns) = collectNames patterns
collectName (TuplePat patterns) = collectNames patterns
collectName (InductivePat _ patterns) = collectNames patterns
collectName (ApplyPat _ patterns) = collectNames patterns
collectName (LoopPat _ (LoopRange _ _ endNumPat) pattern1 pattern2) = collectName endNumPat `S.union` collectName pattern1 `S.union` collectName pattern2
-- collectName (LoopPat _ (LoopRange _ _ endNumPat) pattern1 pattern2) = collectName pattern1 `S.union` collectName pattern2
collectName (LetPat _ pattern) = collectName pattern
collectName (IndexedPat (PatVar name) _) = S.singleton name
collectName (OrPat patterns) = collectNames patterns
collectName _ = S.empty
makeBinding :: String -> BindingExpr
makeBinding name = ([name], HashExpr [])
desugarPattern' :: EgisonPattern -> DesugarM EgisonPattern
desugarPattern' (ValuePat expr) = ValuePat <$> desugar expr
desugarPattern' (PredPat expr) = PredPat <$> desugar expr
desugarPattern' (NotPat pattern) = NotPat <$> desugarPattern' pattern
desugarPattern' (AndPat patterns) = AndPat <$> mapM desugarPattern' patterns
desugarPattern' (OrPat patterns) = OrPat <$> mapM desugarPattern' patterns
desugarPattern' (OrderedOrPat []) = return (NotPat WildCard)
desugarPattern' (OrderedOrPat (pattern:patterns)) = do
pattern' <- desugarPattern' pattern
pattern'' <- desugarPattern' (OrderedOrPat patterns)
return $ OrPat [pattern', AndPat [(NotPat pattern'), pattern'']]
desugarPattern' (TuplePat patterns) = TuplePat <$> mapM desugarPattern' patterns
desugarPattern' (InductivePat name patterns) = InductivePat name <$> mapM desugarPattern' patterns
desugarPattern' (IndexedPat pattern exprs) = IndexedPat <$> desugarPattern' pattern <*> mapM desugar exprs
desugarPattern' (ApplyPat expr patterns) = ApplyPat <$> desugar expr <*> mapM desugarPattern' patterns
desugarPattern' (LoopPat name range pattern1 pattern2) = LoopPat name <$> desugarLoopRange range <*> desugarPattern' pattern1 <*> desugarPattern' pattern2
desugarPattern' (LetPat binds pattern) = LetPat <$> desugarBindings binds <*> desugarPattern' pattern
desugarPattern' pattern = return pattern
desugarLoopRange :: LoopRange -> DesugarM LoopRange
desugarLoopRange (LoopRange sExpr eExpr pattern) = do
sExpr' <- desugar sExpr
eExpr' <- desugar eExpr
pattern' <- desugarPattern' pattern
return $ LoopRange sExpr' eExpr' pattern'
desugarBinding :: BindingExpr -> DesugarM BindingExpr
desugarBinding (name, expr) = do
expr' <- desugar expr
return $ (name, expr')
desugarBindings :: [BindingExpr] -> DesugarM [BindingExpr]
desugarBindings (bind:rest) = do
bind' <- desugarBinding bind
rest' <- desugarBindings rest
return $ bind' : rest'
desugarBindings [] = return []
desugarMatchClause :: MatchClause -> DesugarM MatchClause
desugarMatchClause (pattern, expr) = do
pattern' <- desugarPattern pattern
expr' <- desugar expr
return $ (pattern', expr')
desugarMatchClauses :: [MatchClause] -> DesugarM [MatchClause]
desugarMatchClauses (clause:rest) = do
clause' <- desugarMatchClause clause
rest' <- desugarMatchClauses rest
return $ clause' : rest'
desugarMatchClauses [] = return []
desugarMatcherInfo :: MatcherInfo -> DesugarM MatcherInfo
desugarMatcherInfo [] = return []
desugarMatcherInfo ((pp, matcher, pds):matcherInfo) = do
matcher' <- desugar matcher
pds' <- desugarPrimitiveDataMatchClauses pds
matcherInfo' <- desugarMatcherInfo matcherInfo
return $ (pp, matcher', pds'):matcherInfo'
desugarPrimitiveDataMatchClauses :: [(PrimitiveDataPattern, EgisonExpr)] -> DesugarM [(PrimitiveDataPattern, EgisonExpr)]
desugarPrimitiveDataMatchClauses [] = return []
desugarPrimitiveDataMatchClauses ((pd, expr):pds) = do
expr' <- desugar expr
pds' <- desugarPrimitiveDataMatchClauses pds
return $ (pd, expr'):pds'
|
beni55/egison
|
hs-src/Language/Egison/Desugar.hs
|
mit
| 14,718
| 0
| 19
| 3,037
| 4,891
| 2,422
| 2,469
| 290
| 10
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Prelude
import Text.Earley
import Engine.Recognizer
main :: IO ()
main = undefined
-- let p = allParses (parser imperative) . words
-- print $ p "refuel ship"
-- print $ p "move ship to mongo"
-- print $ p "buy 100 finest_green"
-- print $ p "buy shizzle"
|
mlitchard/cosmos
|
executable/Main.hs
|
mit
| 329
| 0
| 6
| 69
| 38
| 25
| 13
| 7
| 1
|
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Control.Applicative
import Control.Monad (forM, forM_, void)
import CStack
import Foreign hiding (void)
import Foreign.C.Types
import System.IO.Unsafe (unsafePerformIO)
import Test.QuickCheck
import Test.QuickCheck.All ()
import Test.QuickCheck.Monadic
newtype StackPtr = StackPtr (Ptr Stack)
instance Show StackPtr where
show (StackPtr s) = show $ stackToList s
data StackWithIdx = StackWithIdx (Ptr Stack) CSize CSize deriving Show
instance Arbitrary CInt where
arbitrary = choose (minBound, maxBound)
instance Arbitrary StackPtr where
arbitrary = StackPtr <$> unsafePerformIO <$> listToStack' <$> arbitrary
instance Arbitrary StackWithIdx where
arbitrary = sized $ \n -> do
k <- choose (1, n `max` 1)
list <- vector k
let stack = listToStack list
idx <- choose (0, k-1)
return $ StackWithIdx stack (fromIntegral idx) (fromIntegral k)
stackToList :: Ptr Stack -> [CInt]
stackToList = unsafePerformIO . stackToList'
listToStack :: [CInt] -> Ptr Stack
listToStack = unsafePerformIO . listToStack'
stackToList' :: Ptr Stack -> IO [CInt]
stackToList' s = do
sz <- c_stack_size s
if sz == 0 then return [] else
forM [0..sz-1] (c_stack_get s)
listToStack' :: [CInt] -> IO (Ptr Stack)
listToStack' xs = do
s <- c_stack_alloc
forM_ xs (c_stack_push s)
return s
prop_to_from_list :: [CInt] -> Property
prop_to_from_list xs = monadicIO $ do
s <- run $ listToStack' xs
xs' <- run $ stackToList' s
run $ c_stack_free s
assert (xs == xs')
prop_set_get :: StackWithIdx -> CInt -> Property
prop_set_get (StackWithIdx s ix _) x = monadicIO $ do
run $ c_stack_set s ix x
y <- run $ c_stack_get s ix
run $ c_stack_free s
assert (x == y)
prop_set_push_get :: StackWithIdx -> CInt -> [CInt] -> Property
prop_set_push_get (StackWithIdx s ix _) x xs = monadicIO $ do
run $ c_stack_set s ix x
run $ forM_ xs (c_stack_push s)
y <- run $ c_stack_get s ix
run $ c_stack_free s
assert (x == y)
prop_set_push_pop_get :: StackWithIdx -> CInt -> [CInt] -> Property
prop_set_push_pop_get (StackWithIdx s ix _) x xs = monadicIO $ do
run $ c_stack_set s ix x
run $ forM_ xs (c_stack_push s)
run $ forM_ xs (\_ -> c_stack_pop s)
y <- run $ c_stack_get s ix
run $ c_stack_free s
assert (x == y)
prop_set_pop_get :: StackWithIdx -> CInt -> Property
prop_set_pop_get (StackWithIdx s ix l) x = monadicIO $ do
run $ c_stack_set s ix x
-- Pop off everything except y
run $ forM_ [1..l - ix - 1] (\_ -> c_stack_pop s)
y <- run $ c_stack_pop s
run $ c_stack_free s
assert (x == y)
prop_push_pop :: StackPtr -> CInt -> Property
prop_push_pop (StackPtr s) x = monadicIO $ do
run $ c_stack_push s x
y <- run $ c_stack_pop s
run $ c_stack_free s
assert (x == y)
prop_push_preserves_input :: [CInt] -> Property
prop_push_preserves_input xs = monadicIO $ do
s <- run c_stack_alloc
forM_ xs (run . c_stack_push s)
xs' <- run $ stackToList' s
run $ c_stack_free s
assert (xs == xs')
prop_fifo_stack :: [CInt] -> Property
prop_fifo_stack xs = monadicIO $ do
s <- run c_stack_alloc
run $ forM_ xs (c_stack_push s)
xs' <- run $ forM xs (\_ -> c_stack_pop s)
run $ c_stack_free s
assert (xs == reverse xs')
prop_degenerate_to_array :: StackPtr -> Property
prop_degenerate_to_array (StackPtr s) = monadicIO $ do
sz <- run malloc
xs <- run $ stackToList' s
int_ptr <- run $ c_stack_degenerate_to_array s sz
sz' <- run $ peek sz
xs' <- run $ peekArray (fromIntegral sz') int_ptr
run $ free sz
run $ free int_ptr
assert (xs == xs')
return []
runTests :: IO Bool
runTests = $quickCheckAll
runDeepTests :: IO Bool
runDeepTests = $forAllProperties $ quickCheckWithResult
(stdArgs { maxSuccess = 1000, maxSize = 1000})
main :: IO ()
main = void runDeepTests
|
andreasfrom/realtime_dynamic_int_stack
|
Main.hs
|
mit
| 3,957
| 0
| 13
| 916
| 1,516
| 739
| 777
| 112
| 2
|
module Main where
import List
group5 :: (Ord a) => [a] -> [[a]]
group5 [] = []
group5 xs = (take 5 xs) : group5 (drop 5 xs)
median :: (Ord a) => [a] -> a
median xs =
let
s = sort xs
sz = length xs
in
s !! (sz `div` 2)
momPivot :: (Ord a) => [a] -> a
momPivot [x] = x
momPivot xs =
let
groups = group5 xs
medians = map median groups
in
momPivot medians
kSmallest :: (Ord a) => Int -> [a] -> [a]
kSmallest k xs =
let
pivot = momPivot xs
(s1,l1) = partition (<=pivot) (take k xs)
(s2,l2) = partition (<pivot) (drop k xs)
(s,l) = (s1++s2, l1++l2)
slen = length s
in
if slen == k
then s
else
if slen < k
then s ++ (kSmallest (k-slen) l)
else (kSmallest k s)
|
wks/algorithmic-junks
|
select/mom-select.hs
|
mit
| 830
| 0
| 13
| 322
| 403
| 216
| 187
| 31
| 3
|
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE UndecidableInstances #-}
module Supply where
import Control.Monad.Trans
import Control.Monad.State
import Control.Monad.Reader
import Control.Monad.Writer
import Control.Monad.Except
import ListT
class Monad m => MonadSupply a m | m -> a where
supply :: m a
peek :: m a
exhausted :: m Bool
newtype SupplyT s m a = SupplyT { runSupplyT :: StateT (ListT m s) m a }
deriving (Functor, Applicative, Monad)
instance MonadTrans (SupplyT s) where
lift = SupplyT . lift
-- lucky that MonadState doesn't have monadic values in negative positions
instance MonadReader r m => MonadReader r (SupplyT s m) where
ask = SupplyT ask
reader = SupplyT . reader
local f = SupplyT . (local f) . runSupplyT
instance MonadError e m => MonadError e (SupplyT s m) where
throwError = SupplyT . throwError
catchError (SupplyT error) handler = SupplyT $ catchError error (runSupplyT . handler)
instance MonadState s m => MonadState s (SupplyT s' m) where
get = lift get
put = lift . put
state = lift . state
instance Monad m => MonadSupply s (SupplyT s m) where
supply = SupplyT $ do
ListT l <- get
Cons a ml <- lift l
put (ListT ml)
return a
peek = SupplyT $ do
ListT l <- get
Cons a ml <- lift l
return a
exhausted = SupplyT $ do
ListT ml <- get
l <- lift ml
case l of
Nil -> return True
Cons _ _ -> return False
|
vladfi1/hs-misc
|
Supply.hs
|
mit
| 1,528
| 0
| 12
| 351
| 521
| 263
| 258
| 45
| 0
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE OverloadedStrings #-}
module FP.Extra where
import ClassyPrelude.Yesod (mconcat, (++), toBuilder, (=$), toStrict, builderToLazy, intersperse)
import Control.Exception.Lifted
import Control.Monad
import Control.Monad.IO.Class (MonadIO)
import Control.Monad.Trans.Control (MonadBaseControl)
import Control.Monad.Trans.Reader (ask)
import Data.Acquire (with)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Conduit (($$))
import qualified Data.Conduit.List as CL
import Database.Persist.Sql (rawExecute, rawQueryRes, PersistValue (PersistText), SqlPersistT, connEscapeName, DBName (DBName))
import Prelude hiding ((++))
import System.Posix.Files (setFileMode)
import qualified System.Posix.IO as POSIX (fdWrite, closeFd, createFile)
writePrivateKey :: FilePath -- ^ Path to write the private key
-> FilePath -- ^ Path to write the ssh wrapper script
-> ByteString -- ^ Contents of the private key
-> IO ()
writePrivateKey keyFile sshCmd privateKey = do
B.writeFile keyFile privateKey
setFileMode keyFile 0o600
void $ bracket
(POSIX.createFile sshCmd 0o700)
POSIX.closeFd
$ \fd -> POSIX.fdWrite fd $
concat [ "#!/bin/sh\nssh -i "
, keyFile
, " -o UserKnownHostsFile=/dev/null "
, "-o StrictHostKeyChecking=no "
, " \"$@\"\n" ]
-- | Wipe out all tables in a PostgreSQL database. Obviously this is a very
-- dangerous action!
truncatePostgresqlTables :: (MonadIO m, MonadBaseControl IO m) => SqlPersistT m ()
truncatePostgresqlTables = do
conn <- ask
srcRes <- rawQueryRes "select tablename from pg_tables where schemaname='public'" []
names <- with srcRes
($$ CL.mapMaybe getName
=$ CL.map (toBuilder . connEscapeName conn . DBName)
=$ CL.consume)
unless (null names) $ do
let sql = toStrict $ builderToLazy $
"TRUNCATE TABLE " ++
mconcat (intersperse ", " names) ++
" CASCADE"
rawExecute sql []
where
getName [PersistText name] = Just name
getName _ = Nothing
|
fpco/schoolofhaskell.com
|
src/FP/Extra.hs
|
mit
| 2,464
| 0
| 17
| 718
| 525
| 298
| 227
| 52
| 2
|
{-# LANGUAGE BangPatterns #-}
module Crypto.RNCryptor.V3.Encrypt
( encrypt
, encryptBlock
, encryptStream
, encryptStreamWithContext
) where
import Crypto.Cipher.AES (AES256)
import Crypto.Cipher.Types (makeIV, IV, BlockCipher, cbcEncrypt)
import Crypto.MAC.HMAC (update, finalize)
import Crypto.RNCryptor.Padding
import Crypto.RNCryptor.Types
import Crypto.RNCryptor.V3.Stream
import Data.ByteArray (convert)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Maybe (fromMaybe)
import Data.Monoid
import qualified System.IO.Streams as S
encryptBytes :: AES256 -> ByteString -> ByteString -> ByteString
encryptBytes a iv = cbcEncrypt a iv'
where
iv' = fromMaybe (error $ "encryptBytes: makeIV failed (iv was: " <> show (B.unpack iv) <> ")") $ makeIV iv
--------------------------------------------------------------------------------
-- | Encrypt a raw Bytestring block. The function returns the encrypt text block
-- plus a new 'RNCryptorContext', which is needed because the IV needs to be
-- set to the last 16 bytes of the previous cipher text. (Thanks to Rob Napier
-- for the insight).
encryptBlock :: RNCryptorContext
-> ByteString
-> (RNCryptorContext, ByteString)
encryptBlock ctx clearText =
let cipherText = encryptBytes (ctxCipher ctx) (rncIV . ctxHeader $ ctx) clearText
!newHmacCtx = update (ctxHMACCtx ctx) cipherText
!sz = B.length clearText
!newHeader = (ctxHeader ctx) { rncIV = B.drop (sz - 16) cipherText }
in (ctx { ctxHeader = newHeader, ctxHMACCtx = newHmacCtx }, cipherText)
--------------------------------------------------------------------------------
-- | Encrypt a message. Please be aware that this is a user-friendly
-- but dangerous function, in the sense that it will load the *ENTIRE* input in
-- memory. It's mostly suitable for small inputs like passwords. For large
-- inputs, where size exceeds the available memory, please use 'encryptStream'.
encrypt :: RNCryptorContext -> ByteString -> ByteString
encrypt ctx input =
let msgHdr = renderRNCryptorHeader $ ctxHeader ctx
ctx' = ctx { ctxHMACCtx = update (ctxHMACCtx ctx) msgHdr }
(ctx'', cipherText) = encryptBlock ctx' (input <> pkcs7Padding blockSize (B.length input))
msgHMAC = convert $ finalize (ctxHMACCtx ctx'')
in msgHdr <> cipherText <> msgHMAC
--------------------------------------------------------------------------------
-- | Efficiently encrypt an incoming stream of bytes.
encryptStreamWithContext :: RNCryptorContext
-- ^ The RNCryptorContext
-> S.InputStream ByteString
-- ^ The input source (mostly likely stdin)
-> S.OutputStream ByteString
-- ^ The output source (mostly likely stdout)
-> IO ()
encryptStreamWithContext ctx inS outS = do
S.write (Just (renderRNCryptorHeader $ ctxHeader ctx)) outS
processStream ctx inS outS encryptBlock finaliseEncryption
where
finaliseEncryption lastBlock lastCtx = do
let (ctx', cipherText) = encryptBlock lastCtx (lastBlock <> pkcs7Padding blockSize (B.length lastBlock))
S.write (Just cipherText) outS
S.write (Just (convert $ finalize (ctxHMACCtx ctx'))) outS
--------------------------------------------------------------------------------
-- | Efficiently encrypt an incoming stream of bytes.
encryptStream :: Password
-- ^ The user key (e.g. password)
-> S.InputStream ByteString
-- ^ The input source (mostly likely stdin)
-> S.OutputStream ByteString
-- ^ The output source (mostly likely stdout)
-> IO ()
encryptStream userKey inS outS = do
hdr <- newRNCryptorHeader
let ctx = newRNCryptorContext userKey hdr
msgHdr = renderRNCryptorHeader hdr
ctx' = ctx { ctxHMACCtx = update (ctxHMACCtx ctx) msgHdr }
encryptStreamWithContext ctx' inS outS
|
RNCryptor/rncryptor-hs
|
src/Crypto/RNCryptor/V3/Encrypt.hs
|
mit
| 4,197
| 0
| 18
| 1,038
| 803
| 429
| 374
| 58
| 1
|
module Acme.StrTok (
-- * The StrTokT monad transformer
StrTokT,
runStrTokT,
-- * The StrTok monad
StrTok,
runStrTok,
-- * The strTok function
strTok
) where
import Control.Applicative
import Control.Monad
import Control.Monad.Identity
import Control.Arrow
import Control.Monad.Trans
-- | The @StrTokT@ monad, parametrised with:
--
-- * @s@ - The type of list elements (e.g. @Char@ if the input to @strTok@ is a @String@).
--
-- * @m@ - The inner monad.
newtype StrTokT s m a = StrTokT { runStrTokT' :: [s] -> m (a, [s]) }
instance Functor m => Functor (StrTokT s m) where
fmap f (StrTokT g) = StrTokT $ fmap (first f) . g
instance (Functor m, Monad m) => Applicative (StrTokT s m) where
pure = return
(<*>) = ap
instance (Functor m, MonadPlus m) => Alternative (StrTokT s m) where
empty = mzero
(<|>) = mplus
instance (MonadPlus m) => MonadPlus (StrTokT s m) where
mzero = StrTokT $ const mzero
m `mplus` n = StrTokT $ \s -> runStrTokT' m s `mplus` runStrTokT' n s
instance (MonadFix m) => MonadFix (StrTokT s m) where
mfix f = StrTokT $ \s -> mfix $ \ ~(a, _) -> runStrTokT' (f a) s
instance Monad m => Monad (StrTokT s m) where
return x = StrTokT $ \s -> return (x,s)
StrTokT f >>= g = StrTokT $ \s -> do {(x,s) <- f s; runStrTokT' (g x) s}
instance MonadTrans (StrTokT s) where
lift m = StrTokT $ \s -> do {x <- m; return (x,s)}
instance (MonadIO m) => MonadIO (StrTokT s m) where
liftIO = lift . liftIO
-- | Executes a @strTok@ computation in the state transformer monad @StrTokT@
runStrTokT :: Functor m => StrTokT s m a -> m a
runStrTokT (StrTokT f) = fmap fst (f [])
-- | The @StrTok@ monad
type StrTok s = StrTokT s Identity
-- | Executes a @strTok@ computation in the state monad @StrTok@
runStrTok :: StrTok s a -> a
runStrTok = runIdentity . runStrTokT
-- | A Haskell variant of the @strtok@ function from C and PHP. This function splits a string into tokens which are
-- delimited by a given set of characters. A call with @Just s@ and the delimiting characters @ds@ will yield
-- the first token in @s@ that is delimited by characters from @ds@. Every subsequent call of @strTok@ with @Nothing@
-- will yield the next token. If the string contains no more tokens, an empty list is returned.
--
-- @strTok@ returns a stateful computation of type @StrTokT a m [a]@ (or @StrTok a [a]@).
-- Several invocations of @strTok@ and computations with the results can be chained in the @StrTokT@ (resp. @StrTok@)
-- monad and then executed with @runStrTokT@ (resp. @runStrTok@).
--
-- Example:
--
-- >runStrTokT $
-- > do a <- strTok (Just "- This, a sample string.") " ,.-"
-- > b <- strTok Nothing " ,.-"
-- > c <- strTok Nothing ",.-"
-- > return (a, b, c)
--
-- evaluates to
--
-- >("This","a"," sample string")
strTok :: (Eq a, Monad m) => Maybe [a] -> [a] -> StrTokT a m [a]
strTok s delims = StrTokT $ maybe strTok' (const . strTok') s
where strTok' = return . break (`elem` delims) . dropWhile (`elem` delims)
|
3of8/haskell_playground
|
strtok/Acme/StrTok.hs
|
gpl-2.0
| 3,062
| 0
| 12
| 689
| 790
| 438
| 352
| 40
| 1
|
module WAM.Instruction where
import Prolog (VarId)
type WamAddress = Int
-- WAM Operator
data WamOp =
PutVariable
| PutValue
| PutUnsafeValue
| PutStructure WamLabel
| PutConstant String
| GetStructure WamLabel
| GetConstant String
| GetValue
| GetVariable
| UnifyConstant String
| UnifyValue
| UnifyVariable
| Call WamLabel
| Execute WamLabel
| Proceed
| Allocate Int
| Deallocate
| TryMeElse WamAddress
| RetryMeElse WamAddress
| TrustMe
| Backtrack
| CallVariable
| ExecuteVariable
deriving Show
type WamArg = WamRegister
-- WAM Instruction
type WamInstr = (WamOp, [WamArg])
getOp (op, _) = op
getReg (_, regs) = regs
data WamRegister =
Perm Int
| Temp Int
deriving Show
type WamInstrSeq = [WamInstr]
type WamLabel = (String, Int)
type WamIndex = [(WamLabel, WamAddress)]
type WamGoal = ([VarId], WamInstrSeq)
-- WAM Program
data WamProgram =
DB { wamIndex :: WamIndex
, wamCode :: WamInstrSeq
}
mkDB :: [(WamLabel, WamInstrSeq)] -> WamProgram
mkDB lst = DB { wamIndex = idx, wamCode = code }
where
(idx, code) = foldl aux ([],[]) lst
aux (idx, code) (lbl, instr) = (idx ++ [(lbl, length code + 1)], code ++ instr)
|
acharal/wam
|
src/WAM/Instruction.hs
|
gpl-2.0
| 1,271
| 0
| 12
| 335
| 380
| 234
| 146
| 47
| 1
|
module Flowskell.InputActions (
keyboardMouseHandler,
mouseHandler,
motionHandler,
actionReloadSource) where
import Control.Monad (when)
import Data.Maybe (isJust, fromJust)
import Graphics.Rendering.OpenGL.GL.FramebufferObjects
import Graphics.UI.GLUT hiding (Bool, Float)
import Language.Scheme.Core (evalString)
import Flowskell.State
import qualified Flowskell.InputLine as IL
import Flowskell.TextureUtils (writeTextureToFile)
-- |Reload scheme source by initialising a new environment and storing it in
-- envRef.
actionReloadSource state = do
Just env <- get $ environment state
Just initFunc' <- get $ initFunc state
putStrLn $ "Notice: Reloading " ++ (source state)
newEnv <- initFunc' (source state)
environment state $= Just newEnv
lastEnvironment state $= Just env
-- |Save last rendered screen texture to PNG file
actionScreenshot state = do
let shotFilename = "flowskell-shot.png"
Just fbTexture <- get $ lastRenderTexture state
writeTextureToFile fbTexture shotFilename
putStrLn $ "Notice: Saved screenshot to " ++ shotFilename
-- |Reset top level rotation (still incorrect)
actionResetView state = do
matrixMode $= Projection
s@(Size w h) <- get $ currentResolution state
-- TODO: This is redundant to reshapeHandler in Flowskell.Display
viewport $= (Position 0 0, s)
matrixMode $= Projection
loadIdentity
let fov = 60
near = 0.01
far = 100
aspect = (fromIntegral w) / (fromIntegral h)
perspective fov aspect near far
translate $ Vector3 0 0 (-1::GLfloat)
actionModifyInputLine fnc state = do
(get $ replInputLine state) >>= \x -> replInputLine state $= fnc x
actionToggle stateVar state = do
(get $ stateVar state) >>= \x -> stateVar state $= not x
actionEvalInputLine state = do
il <- get $ replInputLine state
env <- (get $ environment state) >>= return . fromJust
lines <- get $ replLines state
let inputString = IL.getInput il
result <- evalString env inputString
replLines state $= [result, ">>> " ++ inputString] ++ lines
replInputLine state $= IL.newInputLine
-- Input line bindings
keyboardAct (Char '\b') = actionModifyInputLine IL.backspace
keyboardAct (Char '\DEL') = actionModifyInputLine IL.del
keyboardAct (Char '\r') = actionEvalInputLine
keyboardAct (Char c) = actionModifyInputLine (IL.input c)
keyboardAct (SpecialKey KeyLeft) = actionModifyInputLine IL.left
keyboardAct (SpecialKey KeyRight) = actionModifyInputLine IL.right
keyboardAct (SpecialKey KeyHome) = actionModifyInputLine IL.pos1
keyboardAct (SpecialKey KeyEnd) = actionModifyInputLine IL.end
-- Function key bindings
keyboardAct (SpecialKey KeyF1) = actionToggle showHelp
keyboardAct (SpecialKey KeyF2) = actionToggle showREPL
keyboardAct (SpecialKey KeyF3) = actionToggle showFramesPerSecond
keyboardAct (SpecialKey KeyF5) = actionReloadSource
keyboardAct (SpecialKey KeyF6) = actionResetView
keyboardAct (SpecialKey KeyF7) = actionScreenshot
keyboardAct _ = \_ -> return ()
keyboardMouseHandler state (MouseButton WheelDown) Down _ _ = do
let s = 0.9 :: GLfloat
matrixMode $= Projection
scale s s s
keyboardMouseHandler state (MouseButton WheelUp) Down _ _ = do
let s = 1.1 :: GLfloat
matrixMode $= Projection
scale s s s
keyboardMouseHandler state (MouseButton _) Down mod position =
lastPosition state $= (Position (-1) (-1))
keyboardMouseHandler state key st mod position =
when (st == Down) $ keyboardAct key state
mouseHandler state keystate mod pos@(Position x y) =
lastPosition state $= (Position (-1) (-1))
motionHandler :: State -> MotionCallback
motionHandler state pos@(Position x y) = do
postRedisplay Nothing
Position xt yt <- get (lastPosition state)
lastPosition state $= pos
when (xt /= -1 || yt /= -1) $ do
let Vector3 xl yl _ = Vector3 (fromIntegral (x - xt)) (fromIntegral (y - yt)) 0
matrixMode $= Projection
rotate (yl / 10.0) (Vector3 (-1) 0 (0 :: GLfloat))
rotate (xl / 10.0) (Vector3 0 (-1) (0 :: GLfloat))
|
lordi/flowskell
|
src/Flowskell/InputActions.hs
|
gpl-2.0
| 3,983
| 0
| 17
| 690
| 1,333
| 655
| 678
| 88
| 1
|
{-# LANGUAGE DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
module Exp.Smaller where
-- $Id$
import Inter.Types
import Inter.Quiz
import Autolib.ToDoc
import Autolib.Hash
import Autolib.Util.Seed
import qualified Challenger as C
import Data.Typeable
import Autolib.Reporter
import Autolib.Exp.Example
import Autolib.NFA.Eq
import Autolib.Exp
import Autolib.Exp.Inter
import Autolib.Exp.Sanity
import Autolib.Size
import Autolib.Dot ( peng )
import Exp.Property
import Exp.Test
import Exp.Quiz
import NFA.Roll
import Convert.Input
import Autolib.Set
import Autolib.Informed
data Exp_Smaller = Exp_Smaller
deriving ( Eq, Ord, Show, Read, Typeable )
instance OrderScore Exp_Smaller where
scoringOrder _ = Increasing
instance C.Partial Exp_Smaller
( RX Char , [ Property Char ] )
( RX Char )
where
report Exp_Smaller ( rx, props ) = do
inform $ vcat
[ text "Gesucht ist ein regulärer Ausdruck,"
, text "der die selbe Sprache wie der Ausdruck"
, nest 4 $ toDoc rx
, text "der Größe"
, nest 4 $ toDoc $ size rx
, text "erzeugt und die Eigenschaften"
, nest 4 $ toDoc props
, text "hat."
]
initial Exp_Smaller ( rx, props ) =
let [ alpha ] = do Alphabet a <- props ; return a
in Autolib.Exp.Example.example alpha
partial Exp_Smaller ( rx, props ) exp = do
-- als property definiert
-- sanity_keys ( mkSet [ "Eps", "Empty" ] ) exp
inform $ text "Sind alle Eigenschaften erfüllt?"
nested 4 $ mapM_ ( flip test exp ) props
inform $ text "Ja."
total Exp_Smaller ( rx, props ) exp = do
inform $ text "Erzeugt Ihr Ausdruck die richtige Sprache?"
let [ alpha ] = do Alphabet a <- props ; return a
flag <- nested 4
$ equ ( informed ( text "Sprache der Aufgabenstellung" )
$ inter (std_sigma $ setToList alpha) rx
)
( informed ( text "Sprache Ihres Ausdrucks" )
$ inter (std_sigma $ setToList alpha) exp
)
when (not flag) $ reject $ text ""
instance C.Measure Exp_Smaller
( RX Char , [ Property Char ] )
( RX Char )
where
measure _ _ exp = fromIntegral $ size exp
make :: Make
make = direct Exp_Smaller
( read "(a+b+ab+ba)^*" :: RX Char
, [ Exp.Property.Simple , Exp.Property.Alphabet (mkSet "ab") ] :: [ Property Char ]
)
|
Erdwolf/autotool-bonn
|
src/Exp/Smaller.hs
|
gpl-2.0
| 2,461
| 8
| 16
| 688
| 711
| 368
| 343
| 65
| 1
|
module PokerII where
import Data.List
data Rank = Two|Three|Four|Five|Six|Seven|Eight|Nine|Ten|J|Q|K|A
deriving (Eq, Ord, Enum, Show, Read)
data Suit = Spades|Hearts|Diamonds|Clubs
deriving (Eq, Show, Read) -- no ordering for poker
data Card = Card Rank Suit
deriving (Show, Read)
data Hand = Hd [Card]
instance Eq Card where
(Card rank1 _) == (Card rank2 _) = rank1 == rank2
instance Ord Card where
compare (Card rank1 _ ) (Card rank2 _)
| rank1 < rank2 = LT
| rank1 > rank2 = GT
| otherwise = EQ
isFlush [_] = True
isFlush ((Card _ suit1):(Card r suit2):cards)
| suit1 == suit2 = isFlush ((Card r suit2):cards)
| otherwise = False
isStraight cards = xs == [0,1,2,3,12] || inSequence xs
where xs = (sort [fromEnum rank | (Card rank _) <- cards])
inSequence [_] = True
inSequence (x:y:xs)
| (y-x) == 1 = inSequence (y:xs)
| otherwise = False
isStraightFlush cards = isStraight cards && isFlush cards
isRoyalFlush cards = isFlush cards && (sort [rank | (Card rank _) <- cards]) == [Ten .. A]
|
collective/ECSpooler
|
backends/haskell/haskell_libs/PokerII.hs
|
gpl-2.0
| 1,219
| 0
| 13
| 400
| 532
| 279
| 253
| 28
| 1
|
-- Copyright (c) 2014 Contributors as noted in the AUTHORS file
--
-- This file is part of frp-arduino.
--
-- frp-arduino 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.
--
-- frp-arduino 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 frp-arduino. If not, see <http://www.gnu.org/licenses/>.
module Arduino.Internal.DAG where
import Control.Monad.State
import Data.Maybe (fromJust)
import qualified Data.Map as M
type Streams = M.Map Identifier Stream
data Stream = Stream
{ name :: Identifier
, inputs :: [Identifier]
, body :: Body
, outputs :: [Identifier]
}
data Body = Transform Expression
| Driver LLI LLI
data LLI = WriteBit String String Bit LLI
| WriteByte String LLI LLI
| WriteWord String LLI LLI
| ReadBit String String
| ReadWord String LLI
| WaitBit String String Bit LLI
| Switch LLI LLI LLI LLI
| Const String
| InputValue
| End
data Bit = High | Low
data Expression = Input Int
| FoldState
| Many [Expression]
-- Stream transformations
| Fold Expression Expression
| Filter Expression Expression
-- Expression transformations
| If Expression Expression Expression
-- Unary operations
| Not Expression
| Even Expression
| IsHigh Expression
-- Binary operations
| Add Expression Expression
| Sub Expression Expression
| Greater Expression Expression
-- Conversion
| BoolToBit Expression
-- Constants
| CharConstant Char
| BitConstant Bit
| NumberConstant Int
type Identifier = String
emptyStreams :: Streams
emptyStreams = M.empty
addStream :: Streams -> Stream -> Streams
addStream streams stream = M.insert (name stream) stream streams
addDependency :: Identifier -> Identifier -> Streams -> Streams
addDependency source destination =
(M.adjust (\x -> x { outputs = outputs x ++ [destination] }) source) .
(M.adjust (\x -> x { inputs = inputs x ++ [source] }) destination)
hasStream :: Streams -> Identifier -> Bool
hasStream streams name = M.member name streams
streamsInTree :: Streams -> [Stream]
streamsInTree = M.elems
streamFromId :: Streams -> Identifier -> Stream
streamFromId tree id = fromJust $ M.lookup id tree
|
rickardlindberg/frp-arduino-old
|
src/Arduino/Internal/DAG.hs
|
gpl-3.0
| 2,995
| 0
| 13
| 903
| 552
| 322
| 230
| 54
| 1
|
{-# LANGUAGE CPP #-}
module Hkl.XRD.Calibration
( NptExt(..)
, XRDCalibrationEntry(..)
, XRDCalibration(..)
, calibrate
) where
import Control.Monad.IO.Class (liftIO)
import Data.ByteString.Char8 (pack)
import Data.List (foldl')
import Data.Text (Text)
import Data.Vector.Storable
( Vector
, head
, concat
, fromList
, slice
, toList
)
import Numeric.LinearAlgebra
( Matrix
, (<>)
, atIndex
, ident
)
import Numeric.GSL.Minimization
( MinimizeMethod(NMSimplex2)
, minimizeV
)
import Numeric.Units.Dimensional.Prelude (meter, radian, nano, (/~), (*~))
import Pipes.Safe (MonadSafe(..), runSafeT, bracket)
import Prelude hiding (head, concat, lookup, readFile, writeFile, unlines)
import Hkl.C
import Hkl.Detector
import Hkl.H5
import Hkl.PyFAI
import Hkl.MyMatrix
import Hkl.PyFAI.PoniExt
import Hkl.Types
import Hkl.XRD
#if !MIN_VERSION_hmatrix(0, 17, 0)
(#>) :: Matrix Double -> Vector Double -> Vector Double
(#>) = (<>)
#else
import Numeric.LinearAlgebra ((#>))
#endif
-- | Calibration
data NptExt a = NptExt { nptExtNpt :: Npt
, nptExtMyMatrix :: MyMatrix Double
, nptExtDetector :: Detector a
}
deriving (Show)
data XRDCalibrationEntry = XRDCalibrationEntryNxs { xrdCalibrationEntryNxs'Nxs :: Nxs
, xrdCalibrationEntryNxs'Idx :: Int
, xrdCalibrationEntryNxs'NptPath :: FilePath
}
| XRDCalibrationEntryEdf { xrdCalibrationEntryEdf'Edf :: FilePath
, xrdCalibrationEntryEdf'NptPath :: FilePath
}
deriving (Show)
data XRDCalibration = XRDCalibration { xrdCalibrationName :: Text
, xrdCalibrationOutputDir :: FilePath
, xrdCalibrationEntries :: [XRDCalibrationEntry]
}
deriving (Show)
withDataItem :: MonadSafe m => File -> DataItem -> (Dataset -> m r) -> m r
withDataItem hid (DataItem name _) = bracket (liftIO acquire') (liftIO . release')
where
acquire' :: IO Dataset
acquire' = openDataset hid (pack name) Nothing
release' :: Dataset -> IO ()
release' = closeDataset
getMNxs :: File -> DataFrameH5Path -> Int -> IO (MyMatrix Double) -- TODO move to XRD
getMNxs f p i' = runSafeT $
withDataItem f (h5pGamma p) $ \g' ->
withDataItem f (h5pDelta p) $ \d' ->
withDataItem f (h5pWavelength p) $ \w' -> liftIO $ do
let mu = 0.0
let komega = 0.0
let kappa = 0.0
let kphi = 0.0
gamma <- get_position g' 0
delta <- get_position d' i'
wavelength <- get_position w' 0
let source = Source (head wavelength *~ nano meter)
let positions = concat [mu, komega, kappa, kphi, gamma, delta]
let geometry = Geometry K6c source positions Nothing
let detector = ZeroD
m <- geometryDetectorRotationGet geometry detector
return (MyMatrix HklB m)
readXRDCalibrationEntry :: Detector a -> XRDCalibrationEntry -> IO (NptExt a)
readXRDCalibrationEntry d e@(XRDCalibrationEntryNxs _ _ _) =
withH5File f $ \h5file -> do
m <- getMNxs h5file p idx
npt <- nptFromFile (xrdCalibrationEntryNxs'NptPath e)
return (NptExt npt m d)
where
idx = xrdCalibrationEntryNxs'Idx e
(Nxs f _ p) = xrdCalibrationEntryNxs'Nxs e
readXRDCalibrationEntry d e@(XRDCalibrationEntryEdf _ _) = do
m <- getMEdf (xrdCalibrationEntryEdf'Edf e)
npt <- nptFromFile (xrdCalibrationEntryEdf'NptPath e)
return (NptExt npt m d)
-- | Poni Calibration
-- The minimized function is the quadratic difference of the
-- theoretical tth angle and for each pixel, the computed tth angle.
-- synonyme types use in order to improve the calibration performance
type NptEntry' = (Double, [Vector Double]) -- tth, detector pixels coordinates
type Npt' = (Double, [NptEntry']) -- wavelength, [NptEntry']
type NptExt' a = (Npt', Matrix Double, Detector a)
poniEntryFromList :: PoniEntry -> [Double] -> PoniEntry
poniEntryFromList p [rot1, rot2, rot3, poni1, poni2, d] =
p { poniEntryDistance = d *~ meter
, poniEntryPoni1 = poni1 *~ meter
, poniEntryPoni2 = poni2 *~ meter
, poniEntryRot1 = rot1 *~ radian
, poniEntryRot2 = rot2 *~ radian
, poniEntryRot3 = rot3 *~ radian
}
poniEntryFromList _ _ = error "Can not convert to a PoniEntry"
poniEntryToList :: PoniEntry -> [Double]
poniEntryToList p = [ poniEntryRot1 p /~ radian
, poniEntryRot2 p /~ radian
, poniEntryRot3 p /~ radian
, poniEntryPoni1 p /~ meter
, poniEntryPoni2 p /~ meter
, poniEntryDistance p /~ meter
]
calibrate :: XRDCalibration -> PoniExt -> Detector a -> IO PoniExt
calibrate c (PoniExt p _) d = do
let entry = last p
let guess = fromList $ poniEntryToList entry
-- read all the NptExt
npts <- mapM (readXRDCalibrationEntry d) (xrdCalibrationEntries c)
-- in order to improve computation speed, pre-compute the pixel coodinates.
let (solution, _p) = minimizeV NMSimplex2 1E-16 3000 box (f (preCalibrate npts)) guess
-- mplot $ drop 3 (toColumns p)
print _p
return $ PoniExt [poniEntryFromList entry (toList solution)] (MyMatrix HklB (ident 3))
where
preCalibrate''' :: Detector a -> NptEntry -> NptEntry'
preCalibrate''' detector (NptEntry _ tth _ points) = (tth /~ radian, map (coordinates detector) points)
preCalibrate'' :: Npt -> Detector a -> Npt'
preCalibrate'' n detector = (nptWavelength n /~ meter, map (preCalibrate''' detector) (nptEntries n))
preCalibrate' :: NptExt a -> NptExt' a
preCalibrate' (NptExt n m detector) = (preCalibrate'' n detector, m', detector)
where
(MyMatrix _ m') = changeBase m PyFAIB
preCalibrate :: [NptExt a] -> [NptExt' a]
preCalibrate = map preCalibrate'
box :: Vector Double
box = fromList [0.1, 0.1, 0.1, 0.01, 0.01, 0.01]
f :: [NptExt' a] -> Vector Double -> Double
f ns params = foldl' (f' rotation translation) 0 ns
where
rot1 = params `atIndex` 0
rot2 = params `atIndex` 1
rot3 = params `atIndex` 2
rotations = map (uncurry fromAxisAndAngle)
[ (fromList [0, 0, 1], rot3 *~ radian)
, (fromList [0, 1, 0], rot2 *~ radian)
, (fromList [1, 0, 0], rot1 *~ radian)]
rotation = foldl' (<>) (ident 3) rotations
translation :: Vector Double
translation = slice 3 3 params
f' :: Matrix Double -> Vector Double -> Double -> NptExt' a -> Double
f' rotation translation x ((_wavelength, entries), m, _detector) =
foldl' (f'' translation r) x entries
where
r :: Matrix Double
r = m <> rotation
f'' :: Vector Double -> Matrix Double -> Double -> NptEntry'-> Double
{-# INLINE f'' #-}
f'' translation r x (tth, pixels) = foldl' (f''' translation r tth) x pixels
f''' :: Vector Double -> Matrix Double -> Double -> Double -> Vector Double -> Double
{-# INLINE f''' #-}
f''' translation r tth x pixel = x + dtth * dtth
where
kf = r #> (pixel - translation)
x' = kf `atIndex` 0
y' = kf `atIndex` 1
z' = kf `atIndex` 2
dtth = tth - atan2 (sqrt (x'*x' + y'*y')) (-z')
|
picca/hkl
|
contrib/haskell/src/Hkl/XRD/Calibration.hs
|
gpl-3.0
| 7,748
| 0
| 20
| 2,361
| 2,246
| 1,209
| 1,037
| 154
| 1
|
module Miekka.DB.Persist where
import System.IO
import Miekka.DB.Query
import System.IO.Unsafe
import Miekka.DB.Struct
saveDB :: DB -> IO ()
saveDB db = writeFile filepath (show db)
where filepath = tagValue "dbFilepath" $ gTaV db
--Put down your pitchforks! "unsafePerformIO" has no side effects here.
loadDB :: FilePath -> DB
loadDB filepath = read $ unsafePerformIO (readFile filepath)
|
Miekka-Software/OxygenDB
|
Miekka/DB/Persist.hs
|
gpl-3.0
| 394
| 0
| 8
| 60
| 111
| 60
| 51
| 10
| 1
|
{-# LANGUAGE DeriveGeneric #-}
module Src.Model.Credential (Credential(..)) where
import Data.Aeson
import GHC.Generics
data Credential = Credential { email :: String
, password :: String
}
deriving (Eq, Generic)
instance FromJSON Credential
instance ToJSON Credential
instance Show Credential where
show c = "\n\n" ++
"Email address: " ++ (email c) ++
"\nPassword: " ++ (password c) ++
"\n\n"
|
mdipirro/haskell-secure-types
|
app/Src/Model/Credential.hs
|
gpl-3.0
| 533
| 0
| 11
| 196
| 121
| 67
| 54
| 14
| 0
|
-- | This module defines the basic node lifecycle operations and types.
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
module MuPromote.Node.Base (
-- * Node instance
Node(..),
spawnNode,
-- * Node actions
NodeAction(..),
) where
import MuPromote.Common.PromotableItem (PromotableItem)
import MuPromote.Common.Persist
import MuPromote.Node.PromotionProcessorClient
import Data.SafeCopy
import Data.Serialize
-- | The data type of the state of the node.
data Node = Node {
-- | The append-only list of actions that have been performed with the node.
nodeEventStore :: EventStore NodeAction,
-- | A handle to the promotion processor that the node interfaces with.
nodeProcessor :: PromotionProcessorClient
}
instance SafeCopy NodeAction where
version = 0
putCopy (EnrollItemAction witem) = contain $ do
putWord8 0
safePut witem
putCopy ExecutePromoteInitiatedAction = contain $ putWord8 1
putCopy ExecutePromoteCompletedAction = contain $ putWord8 2
getCopy = contain $ do
tag <- getWord8
case tag of
0 -> do
wItem <- safeGet
return $ EnrollItemAction wItem
1 -> return ExecutePromoteInitiatedAction
2 -> return ExecutePromoteCompletedAction
-- | A data type for the state-changing actions that may be performed with a node.
data NodeAction =
-- | Action for enrolling an item.
EnrollItemAction! (PromotableItem, Double)
-- | Action signalling that the node has started communicating with the
-- provider about finalizing the currently enrolled item promotions
| ExecutePromoteInitiatedAction
-- | Action signalling the last 'ExecutePromoteInitiatedAction' completed
-- successfully. Thus, all 'EnrollItemAction's prior to the latest
-- 'ExecutePromoteInitiatedAction' are now considered executed.
| ExecutePromoteCompletedAction
-- | Construct a node instance, given a provider.
spawnNode :: EventStore NodeAction -> PromotionProcessorClient -> Node
spawnNode = Node
|
plcplc/muPromote-code
|
node/src/MuPromote/Node/Base.hs
|
gpl-3.0
| 1,986
| 4
| 16
| 369
| 271
| 155
| 116
| 36
| 1
|
module Heuristics where
import ShrdliteGrammar
import CombinatorParser
import Text.JSON
import Data.List
import Data.Char
import Data.Maybe
import HelpFunctions
-- Heuristics for solving goles
-- Returns (minDepth,(smallerStack,BiggerStack))
heuristics :: World -> PDDL -> (Int,(Int,Int))
heuristics w (PDDL Inside a b) = heuristics w (PDDL Ontop a b)
heuristics w (PDDL Ontop a "") = do
let (s1,h1) = findSAH a w
(h1,(s1,s1))
heuristics w (PDDL Ontop a b)
| checkGoal (convertWorld w) (PDDL Ontop a b) = (0,(0,0))
| b == "floor" = do
let s2 = head . map snd . take 1 . sort $ zip w [0..] -- b is a floor
let h2 = length (w !! s2) -1
let (s1,h1) = findSAH a w
getSuff (s1,h1) (s2,h2)
| otherwise = do
let (s1,h1) = findSAH a w
let (s2,h2) = findSAH b w
getSuff (s1,h1) (s2,h2)
where
getSuff (s1',h1') (s2',h2')
| s1'==s2' = if h1'>h2' then (h1'+1,(s2',s1')) else (h2'+1 ,(s1',s2'))
| otherwise = if h1'>h2' then (h1'+h2'+1,(s2',s1')) else (h1'+h2'+1,(s1',s2'))
heuristics w (PDDL Above a b)
| checkGoal (convertWorld w) (PDDL Above a b) = (0,(0,0))
| otherwise = do
let (s1,h1) = findSAH a w
let (s2,_) = findSAH b w
(h1+1,(s2,s1)) -- Maybe modify the smaller stack
heuristics w (PDDL Under a b) = heuristics w (PDDL Above b a)
heuristics w (PDDL Leftof a b)
| checkGoal (convertWorld w) (PDDL Leftof a b) = (0,(0,0))
| otherwise = do
let (s1,h1) = findSAH a w
let (s2,h2) = findSAH b w
getSuff (s1,h1) (s2,h2)
where
getSuff (s1',h1') (s2',h2')
| s1' == s2' = if h1'> h2' then (h2'+1,(s1',s2')) else (h1'+1, (s1',s2'))
| s2' == 0 && s1' == length w = ((h2'+1)+(h1'+1),(s1',s2'))
| s2' == 0 = (h2'+1,(s2',s2'))
| s1' < s2' = (0,(0,0))
| otherwise = if h1' < h2' then (h1'+1,(s2',s1')) else (h2'+1,(s1',s2'))
heuristics w (PDDL Rightof a b) = heuristics w (PDDL Leftof b a)
heuristics w (PDDL Beside a b)
| checkGoal (convertWorld w) (PDDL Beside a b) = (0,(0,0))
| otherwise = do
let (s1,h1) = findSAH a w
let (s2,h2) = findSAH b w
getSuff (s1,h1) (s2,h2)
where
getSuff (s1',h1') (s2',h2')
| s1' == s2' = if h1'> h2' then (h2'+1,(s1',s2')) else (h1'+1, (s1',s2'))
| s2' == 0 = (h1'+1,(1,s1'))
| s2' == ((length w) - 1) = (h1',((length w -1),s1'))
|otherwise = do
let left = length (w !! (s2'-1))
let right = length (w !! (s2'+1))
if right > left then (h1',(s2' -1,s1')) else (h1',(s2' + 1,s1'))
|
alexandersjosten/AI-shrdlite
|
haskell/Heuristics.hs
|
gpl-3.0
| 2,552
| 0
| 17
| 668
| 1,499
| 796
| 703
| 61
| 7
|
{-# LANGUAGE TypeSynonymInstances #-}
module Types
(RemoteFsEntry(..)
, PathQualification(..)
, isSymlink)
where
import System.Posix.Types
import System.Posix.Files
data RemoteFsEntry = RemoteFsEntry { rfseMode :: FileMode
, rfseSize :: Integer
, rfseName :: String }
deriving (Show, Eq)
instance Monoid FileMode where
mempty = nullFileMode
mappend = unionFileModes
isSymlink :: FileMode -> Bool
isSymlink = (/= nullFileMode) . intersectFileModes symbolicLinkMode
data PathQualification = FsRoot
| Device String
| DeviceFs String
| InDeviceFs String String
deriving (Show, Eq)
|
7ocb/fuse_adb_fs
|
lib/Types.hs
|
gpl-3.0
| 789
| 0
| 8
| 287
| 152
| 92
| 60
| 21
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Freenet (
Freenet, mkFreenet, shutdownFreenet
) where
import Control.Concurrent ( forkIO )
import Control.Concurrent.STM
import Control.Monad ( void )
import qualified Data.Configurator as CFG
import qualified Data.Configurator.Types as CFG
import qualified Data.Text as T
import Freenet.Chk
import Freenet.Companion
import Freenet.Ssk
import Freenet.Store
import Freenet.Types
import Node
data Freenet a = Freenet
{ fnNode :: Node a
, fnCompanion :: Maybe Companion
, fnChkStore :: StoreFile ChkBlock
, fnSskStore :: StoreFile SskBlock
}
mkFreenet
:: Node a
-> Maybe Companion
-> StoreFile ChkBlock
-> StoreFile SskBlock
-> STM (Freenet a)
mkFreenet node comp chk ssk = do
return $ Freenet node comp chk ssk
shutdownFreenet :: Freenet a -> IO ()
shutdownFreenet fn = do
shutdownStore $ fnChkStore fn
shutdownStore $ fnSskStore fn
{-
-- | initializes Freenet subsystem
initFn :: CFG.Config -> IO (Freenet a)
initFn cfg = do
chkIncoming <- newBroadcastTChanIO
sskIncoming <- newBroadcastTChanIO
let fn = FN Nothing chkIncoming sskIncoming
-- companion
let ccfg = CFG.subconfig "companion" cfg
chost <- CFG.lookup ccfg "host" :: IO (Maybe String)
case chost of
Nothing -> return fn
Just _ -> do
comp <- FC.initCompanion ccfg (offerChk fn) (offerSsk fn)
return $ fn { fnCompanion = Just comp }
-}
|
waldheinz/ads
|
src/lib/Freenet.hs
|
gpl-3.0
| 1,583
| 0
| 11
| 450
| 259
| 143
| 116
| 32
| 1
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ViewPatterns#-}
{-# LANGUAGE FlexibleInstances,UndecidableInstances#-}
{-# LANGUAGE CPP #-}
module Test.QuickFuzz.Derive.Mutation where
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
import Test.QuickCheck
import Control.Monad
import Control.Arrow
import Control.Applicative
import Data.List
import Megadeth.Prim
import Test.QuickFuzz.Derive.Mutators
#if MIN_VERSION_template_haskell(2,11,0)
# define TH211MBKIND _maybe_kind
#else
# define TH211MBKIND
#endif
--import Mutation
--
-- | Mutation Class
class Mutation a where
--mutt' :: Int -> a -> Gen a
mutt :: a -> Gen a -- ^ Given a value, mutate it.
--mutt = mutt' 10
--mut :: Gen a
instance {-#OVERLAPS#-} (Mutation a, Arbitrary a) => Mutation [a] where
mutt xs = frequency $ [(10, mapM mutt xs),
(1, expander xs),
(1, deleter xs),
(1, swaper xs),
(1, repeater xs),
(1, return xs)]
instance {-#OVERLAPS#-} Arbitrary a => Mutation a where
mutt a = frequency $ [ (20, return a), (1,arbitrary)]
howm :: Con -> (Name, Int)
howm (NormalC n xs) = (n,length xs)
howm (RecC n xs) = (n,length xs)
howm (ForallC _ _ t) = howm t
howm (InfixC _ _ _ ) = error "not yet"
as :: [Name]
as = map (\x -> mkName $ 'a':show x) ([1..] :: [Int])
-- TODO: ViewPattern, recursive?
-- + mutt (C a1 a2 .. an) = do
-- a1' <- frequency [(10,return a1), (1,arbitrary), (1, mutt a1)]
-- ...
-- return $ C a1' a2' ...
-- This is extremely expensive, isn't it?
freqE :: Bool -> Name -> ExpQ
freqE _ var =
appE
(varE 'frequency)
(listE
[ tupE [litE $ integerL 20, (appE (varE 'mutt) (varE var))]
, tupE [litE $ integerL 20, (appE (varE 'return) (varE var))]
, tupE [litE $ integerL 1, varE 'arbitrary] -- Here we could use a custom Gen
])
muttC :: Name -> [(Bool,Name)] -> ExpQ
muttC c [] =
appE
(varE 'frequency)
(listE
[
tupE [litE $ integerL 20,
(appE (varE 'return) (conE c)) ]
, tupE [litE $ integerL 1, varE 'arbitrary]
-- , tupE [litE $ integerL 1, varE 'mut] -- Here we could use a custom Gen
])
muttC c vars = doE $ map (\ (b,x) -> bindS (varP x) (freqE b x)) vars
++ [ noBindS $ appE (varE 'return)
$ foldl (\r (_,x) -> appE r (varE x)) (conE c) vars]
isMutInsName = isinsName ''Mutation
ifsymHeadOf :: Name -> Q Name
ifsymHeadOf n = do
inf <- reify n
case inf of
TyConI (TySynD _ _ t) -> return $ headOf t
_ -> return n
devMutation :: Name -> Q [Dec]
devMutation t = do
deps <- prevDev t (\_ -> return False)
nosym <- mapM ifsymHeadOf deps
let deps' = nub $ filter (not . hasArbIns) nosym -- Get rid of all type syn ?
-- Just ignore typesym later... We hope that prevDev get all dependencies
-- all right, if not, we always have Arb => Mutation
--dps <- filterM isMutInsName deps' -- Arbitrary => Mutation :(
ds <- mapM ((flip devMutation') Nothing) deps'
return $ concat ds
devMutation' :: Name -> Maybe Name -> Q [Dec]
devMutation' name customGen = do
def <- reify name
case def of -- We need constructors...
TyConI (TySynD _ _ ty) -> return [] -- devMutation (headOf ty) Nothing
TyConI (DataD _ _ params TH211MBKIND constructors _) -> do
let fnm = mkName $ "mutt" -- ++ (showName name)
let f = funD fnm $ foldl (\ p c ->
let
SimpleCon n rec vs = simpleConView name c
tfs = map (\ ty -> (countCons (== name) ty > 0)) vs
vars = take (length vs) as
vp = map varP vars
in
(clause [conP n vp] (normalB $ muttC n (zip tfs vars)) [])
: p) [] constructors
let ns = map varT $ paramNames params
if length ns > 0 then
case customGen of
Nothing -> do
dec <- instanceD (cxt $ (map (appT (conT ''Arbitrary)) ns) ++ (map (appT (conT ''Mutation)) ns))
( appT (conT ''Mutation) (applyTo (conT name) ns))
[f]
return [dec]
Just g -> do
dec <- instanceD (cxt $ (map (appT (conT ''Arbitrary)) ns) ++ (map (appT (conT ''Mutation)) ns))
( appT (conT ''Mutation) (applyTo (conT name) ns))
[f]
return [dec]
else do
case customGen of
Nothing -> do
dec <- instanceD (cxt []) [t| Mutation $(applyTo (conT name) ns) |] [f]
return $ dec : []
Just g -> do
dec <- instanceD (cxt []) [t| Mutation $(applyTo (conT name) ns) |] [f]
return $ dec : []
a -> return [] --return [f]
-- TyConI (NewtypeD _ _ params con _) -> do
|
CIFASIS/QuickFuzz
|
src/Test/QuickFuzz/Derive/Mutation.hs
|
gpl-3.0
| 5,370
| 26
| 19
| 2,043
| 1,653
| 872
| 781
| 103
| 6
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
-- | This module wraps RSCoin.User.Wallet into ACID state.
module RSCoin.User.AcidState
( UserState
, openState
, openMemState
, closeState
, initState
, initStateBank
, query
, tidyState
, update
-- * Queries
, IsInitialized (..)
, GetSecretKey (..)
, FindUserAddress (..)
, GetUserAddresses (..)
, GetDependentAddresses (..)
, GetOwnedAddresses (..)
, GetOwnedDefaultAddresses (..)
, GetOwnedAddrIds (..)
, GetTransactions (..)
, GetLastBlockId (..)
, GetTxsHistory (..)
, GetAddressStrategy (..)
, ResolveAddressLocally (..)
, GetAllocationStrategies (..)
, GetIgnoredAllocationStrategies (..)
, GetAllocationByIndex (..)
, GetPendingTxs (..)
-- * Updates
, WithBlockchainUpdate (..)
, AddAddress (..)
, DeleteAddress (..)
, AddTemporaryTransaction (..)
, UpdateAllocationStrategies (..)
, BlacklistAllocation (..)
, WhitelistAllocation (..)
, UpdatePendingTxs (..)
, InitWallet (..)
) where
import Control.Exception (throwIO)
import Control.Lens ((^.))
import Control.Monad (replicateM, unless)
import Control.Monad.Trans (MonadIO (liftIO))
import Data.Acid (EventResult, EventState, QueryEvent,
UpdateEvent, makeAcidic)
import Data.SafeCopy (base, deriveSafeCopy)
import Serokell.AcidState (ExtendedState, closeExtendedState,
openLocalExtendedState,
openMemoryExtendedState, queryExtended,
tidyExtendedState, updateExtended)
import qualified RSCoin.Core as C
import RSCoin.Core.Crypto (keyGen)
import RSCoin.User.Logic (getBlockchainHeight)
import RSCoin.User.Wallet (TxHStatus, TxHistoryRecord,
WalletStorage)
import qualified RSCoin.User.Wallet as W
$(deriveSafeCopy 0 'base ''TxHStatus)
$(deriveSafeCopy 0 'base ''TxHistoryRecord)
$(deriveSafeCopy 0 'base ''WalletStorage)
type UserState = ExtendedState WalletStorage
query
:: (EventState event ~ WalletStorage, QueryEvent event, MonadIO m)
=> UserState -> event -> m (EventResult event)
query = queryExtended
update
:: (EventState event ~ WalletStorage, UpdateEvent event, MonadIO m)
=> UserState -> event -> m (EventResult event)
update = updateExtended
-- | Opens ACID state. If not there, it returns unitialized
-- unoperatable storage.
openState :: MonadIO m => Bool -> FilePath -> m UserState
openState deleteIfExists path = do
st <- openLocalExtendedState deleteIfExists path W.emptyWalletStorage
st <$ tidyState st
openMemState :: MonadIO m => m UserState
openMemState = openMemoryExtendedState W.emptyWalletStorage
-- | Closes the ACID state.
closeState :: MonadIO m => UserState -> m ()
closeState st = tidyState st >> closeExtendedState st
-- | Tidies the ACID state.
tidyState :: MonadIO m => UserState -> m ()
tidyState = tidyExtendedState
$(makeAcidic
''WalletStorage
[ 'W.isInitialized
, 'W.getSecretKey
, 'W.findUserAddress
, 'W.getDependentAddresses
, 'W.getUserAddresses
, 'W.getOwnedAddresses
, 'W.getOwnedDefaultAddresses
, 'W.getOwnedAddrIds
, 'W.getTransactions
, 'W.getLastBlockId
, 'W.getTxsHistory
, 'W.getAddressStrategy
, 'W.resolveAddressLocally
, 'W.getAllocationStrategies
, 'W.getIgnoredAllocationStrategies
, 'W.getAllocationByIndex
, 'W.getPendingTxs
, 'W.withBlockchainUpdate
, 'W.addTemporaryTransaction
, 'W.addAddress
, 'W.deleteAddress
, 'W.updateAllocationStrategies
, 'W.blacklistAllocation
, 'W.whitelistAllocation
, 'W.updatePendingTxs
, 'W.initWallet])
-- | This function generates 'n' new addresses ((pk,sk) pairs
-- essentially), and if the boolean flag 'is-bank-mode' is set, it
-- also loads secret bank key from ~/.rscoin/bankPrivateKey and adds
-- it to known addresses (public key is hardcoded in
-- RSCoin.Core.Constants).
initState :: C.WorkMode m => UserState -> Int -> Maybe FilePath -> m ()
initState st n (Just skPath) = do
sk <- liftIO $ C.readSecretKey skPath
initStateBank st n sk
initState st n Nothing = do
height <- pred <$> getBlockchainHeight
liftIO $
do addresses <- replicateM n keyGen
update st $ InitWallet addresses (Just height)
tidyState st
-- | This function is is similar to the previous one, but is intended to
-- be used in tests/benchmark, where bank's secret key is embeded and
-- is not contained in file.
initStateBank :: C.WorkMode m => UserState -> Int -> C.SecretKey -> m ()
initStateBank st n sk = do
genAdr <- (^. C.genesisAddress) <$> C.getNodeContext
liftIO $ do
let bankAddress = (sk, C.getAddress genAdr)
unless (W.validateKeyPair genAdr sk) $
throwIO $
W.BadRequest "Imported bank's secret key doesn't belong to bank."
addresses <- replicateM n keyGen
update st $ InitWallet (bankAddress : addresses) Nothing
tidyState st
|
input-output-hk/rscoin-haskell
|
src/RSCoin/User/AcidState.hs
|
gpl-3.0
| 5,557
| 0
| 15
| 1,532
| 1,198
| 687
| 511
| 128
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.YouTube.I18nRegions.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves a list of resources, possibly filtered.
--
-- /See:/ <https://developers.google.com/youtube/ YouTube Data API v3 Reference> for @youtube.i18nRegions.list@.
module Network.Google.Resource.YouTube.I18nRegions.List
(
-- * REST Resource
I18nRegionsListResource
-- * Creating a Request
, i18nRegionsList
, I18nRegionsList
-- * Request Lenses
, irlXgafv
, irlPart
, irlUploadProtocol
, irlAccessToken
, irlUploadType
, irlHl
, irlCallback
) where
import Network.Google.Prelude
import Network.Google.YouTube.Types
-- | A resource alias for @youtube.i18nRegions.list@ method which the
-- 'I18nRegionsList' request conforms to.
type I18nRegionsListResource =
"youtube" :>
"v3" :>
"i18nRegions" :>
QueryParams "part" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "hl" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] I18nRegionListResponse
-- | Retrieves a list of resources, possibly filtered.
--
-- /See:/ 'i18nRegionsList' smart constructor.
data I18nRegionsList =
I18nRegionsList'
{ _irlXgafv :: !(Maybe Xgafv)
, _irlPart :: ![Text]
, _irlUploadProtocol :: !(Maybe Text)
, _irlAccessToken :: !(Maybe Text)
, _irlUploadType :: !(Maybe Text)
, _irlHl :: !Text
, _irlCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'I18nRegionsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'irlXgafv'
--
-- * 'irlPart'
--
-- * 'irlUploadProtocol'
--
-- * 'irlAccessToken'
--
-- * 'irlUploadType'
--
-- * 'irlHl'
--
-- * 'irlCallback'
i18nRegionsList
:: [Text] -- ^ 'irlPart'
-> I18nRegionsList
i18nRegionsList pIrlPart_ =
I18nRegionsList'
{ _irlXgafv = Nothing
, _irlPart = _Coerce # pIrlPart_
, _irlUploadProtocol = Nothing
, _irlAccessToken = Nothing
, _irlUploadType = Nothing
, _irlHl = "en_US"
, _irlCallback = Nothing
}
-- | V1 error format.
irlXgafv :: Lens' I18nRegionsList (Maybe Xgafv)
irlXgafv = lens _irlXgafv (\ s a -> s{_irlXgafv = a})
-- | The *part* parameter specifies the i18nRegion resource properties that
-- the API response will include. Set the parameter value to snippet.
irlPart :: Lens' I18nRegionsList [Text]
irlPart
= lens _irlPart (\ s a -> s{_irlPart = a}) . _Coerce
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
irlUploadProtocol :: Lens' I18nRegionsList (Maybe Text)
irlUploadProtocol
= lens _irlUploadProtocol
(\ s a -> s{_irlUploadProtocol = a})
-- | OAuth access token.
irlAccessToken :: Lens' I18nRegionsList (Maybe Text)
irlAccessToken
= lens _irlAccessToken
(\ s a -> s{_irlAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
irlUploadType :: Lens' I18nRegionsList (Maybe Text)
irlUploadType
= lens _irlUploadType
(\ s a -> s{_irlUploadType = a})
irlHl :: Lens' I18nRegionsList Text
irlHl = lens _irlHl (\ s a -> s{_irlHl = a})
-- | JSONP
irlCallback :: Lens' I18nRegionsList (Maybe Text)
irlCallback
= lens _irlCallback (\ s a -> s{_irlCallback = a})
instance GoogleRequest I18nRegionsList where
type Rs I18nRegionsList = I18nRegionListResponse
type Scopes I18nRegionsList =
'["https://www.googleapis.com/auth/youtube",
"https://www.googleapis.com/auth/youtube.force-ssl",
"https://www.googleapis.com/auth/youtube.readonly",
"https://www.googleapis.com/auth/youtubepartner"]
requestClient I18nRegionsList'{..}
= go _irlPart _irlXgafv _irlUploadProtocol
_irlAccessToken
_irlUploadType
(Just _irlHl)
_irlCallback
(Just AltJSON)
youTubeService
where go
= buildClient
(Proxy :: Proxy I18nRegionsListResource)
mempty
|
brendanhay/gogol
|
gogol-youtube/gen/Network/Google/Resource/YouTube/I18nRegions/List.hs
|
mpl-2.0
| 5,062
| 0
| 18
| 1,259
| 802
| 467
| 335
| 116
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DFAReporting.Conversions.Batchinsert
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Inserts conversions.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.conversions.batchinsert@.
module Network.Google.Resource.DFAReporting.Conversions.Batchinsert
(
-- * REST Resource
ConversionsBatchinsertResource
-- * Creating a Request
, conversionsBatchinsert
, ConversionsBatchinsert
-- * Request Lenses
, cbProFileId
, cbPayload
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.conversions.batchinsert@ method which the
-- 'ConversionsBatchinsert' request conforms to.
type ConversionsBatchinsertResource =
"dfareporting" :>
"v2.7" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"conversions" :>
"batchinsert" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] ConversionsBatchInsertRequest :>
Post '[JSON] ConversionsBatchInsertResponse
-- | Inserts conversions.
--
-- /See:/ 'conversionsBatchinsert' smart constructor.
data ConversionsBatchinsert = ConversionsBatchinsert'
{ _cbProFileId :: !(Textual Int64)
, _cbPayload :: !ConversionsBatchInsertRequest
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ConversionsBatchinsert' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cbProFileId'
--
-- * 'cbPayload'
conversionsBatchinsert
:: Int64 -- ^ 'cbProFileId'
-> ConversionsBatchInsertRequest -- ^ 'cbPayload'
-> ConversionsBatchinsert
conversionsBatchinsert pCbProFileId_ pCbPayload_ =
ConversionsBatchinsert'
{ _cbProFileId = _Coerce # pCbProFileId_
, _cbPayload = pCbPayload_
}
-- | User profile ID associated with this request.
cbProFileId :: Lens' ConversionsBatchinsert Int64
cbProFileId
= lens _cbProFileId (\ s a -> s{_cbProFileId = a}) .
_Coerce
-- | Multipart request metadata.
cbPayload :: Lens' ConversionsBatchinsert ConversionsBatchInsertRequest
cbPayload
= lens _cbPayload (\ s a -> s{_cbPayload = a})
instance GoogleRequest ConversionsBatchinsert where
type Rs ConversionsBatchinsert =
ConversionsBatchInsertResponse
type Scopes ConversionsBatchinsert =
'["https://www.googleapis.com/auth/ddmconversions"]
requestClient ConversionsBatchinsert'{..}
= go _cbProFileId (Just AltJSON) _cbPayload
dFAReportingService
where go
= buildClient
(Proxy :: Proxy ConversionsBatchinsertResource)
mempty
|
rueshyna/gogol
|
gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/Conversions/Batchinsert.hs
|
mpl-2.0
| 3,557
| 0
| 15
| 790
| 410
| 244
| 166
| 66
| 1
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QStyleOptionTab.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:36
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Enums.Gui.QStyleOptionTab (
QStyleOptionTabStyleOptionType
, QStyleOptionTabStyleOptionVersion
, QStyleOptionTabTabPosition
, QStyleOptionTabSelectedPosition
, CornerWidget, CornerWidgets, eNoCornerWidgets, fNoCornerWidgets, eLeftCornerWidget, fLeftCornerWidget, eRightCornerWidget, fRightCornerWidget
)
where
import Foreign.C.Types
import Qtc.Classes.Base
import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr)
import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int)
import Qtc.Enums.Base
import Qtc.Enums.Classes.Core
data CQStyleOptionTabStyleOptionType a = CQStyleOptionTabStyleOptionType a
type QStyleOptionTabStyleOptionType = QEnum(CQStyleOptionTabStyleOptionType Int)
ieQStyleOptionTabStyleOptionType :: Int -> QStyleOptionTabStyleOptionType
ieQStyleOptionTabStyleOptionType x = QEnum (CQStyleOptionTabStyleOptionType x)
instance QEnumC (CQStyleOptionTabStyleOptionType Int) where
qEnum_toInt (QEnum (CQStyleOptionTabStyleOptionType x)) = x
qEnum_fromInt x = QEnum (CQStyleOptionTabStyleOptionType x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> QStyleOptionTabStyleOptionType -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
instance QeType QStyleOptionTabStyleOptionType where
eType
= ieQStyleOptionTabStyleOptionType $ 3
data CQStyleOptionTabStyleOptionVersion a = CQStyleOptionTabStyleOptionVersion a
type QStyleOptionTabStyleOptionVersion = QEnum(CQStyleOptionTabStyleOptionVersion Int)
ieQStyleOptionTabStyleOptionVersion :: Int -> QStyleOptionTabStyleOptionVersion
ieQStyleOptionTabStyleOptionVersion x = QEnum (CQStyleOptionTabStyleOptionVersion x)
instance QEnumC (CQStyleOptionTabStyleOptionVersion Int) where
qEnum_toInt (QEnum (CQStyleOptionTabStyleOptionVersion x)) = x
qEnum_fromInt x = QEnum (CQStyleOptionTabStyleOptionVersion x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> QStyleOptionTabStyleOptionVersion -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
instance QeVersion QStyleOptionTabStyleOptionVersion where
eVersion
= ieQStyleOptionTabStyleOptionVersion $ 1
data CQStyleOptionTabTabPosition a = CQStyleOptionTabTabPosition a
type QStyleOptionTabTabPosition = QEnum(CQStyleOptionTabTabPosition Int)
ieQStyleOptionTabTabPosition :: Int -> QStyleOptionTabTabPosition
ieQStyleOptionTabTabPosition x = QEnum (CQStyleOptionTabTabPosition x)
instance QEnumC (CQStyleOptionTabTabPosition Int) where
qEnum_toInt (QEnum (CQStyleOptionTabTabPosition x)) = x
qEnum_fromInt x = QEnum (CQStyleOptionTabTabPosition x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> QStyleOptionTabTabPosition -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
instance QeBeginning QStyleOptionTabTabPosition where
eBeginning
= ieQStyleOptionTabTabPosition $ 0
instance QeMiddle QStyleOptionTabTabPosition where
eMiddle
= ieQStyleOptionTabTabPosition $ 1
instance QeEnd QStyleOptionTabTabPosition where
eEnd
= ieQStyleOptionTabTabPosition $ 2
instance QeOnlyOneTab QStyleOptionTabTabPosition where
eOnlyOneTab
= ieQStyleOptionTabTabPosition $ 3
data CQStyleOptionTabSelectedPosition a = CQStyleOptionTabSelectedPosition a
type QStyleOptionTabSelectedPosition = QEnum(CQStyleOptionTabSelectedPosition Int)
ieQStyleOptionTabSelectedPosition :: Int -> QStyleOptionTabSelectedPosition
ieQStyleOptionTabSelectedPosition x = QEnum (CQStyleOptionTabSelectedPosition x)
instance QEnumC (CQStyleOptionTabSelectedPosition Int) where
qEnum_toInt (QEnum (CQStyleOptionTabSelectedPosition x)) = x
qEnum_fromInt x = QEnum (CQStyleOptionTabSelectedPosition x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> QStyleOptionTabSelectedPosition -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
instance QeNotAdjacent QStyleOptionTabSelectedPosition where
eNotAdjacent
= ieQStyleOptionTabSelectedPosition $ 0
instance QeNextIsSelected QStyleOptionTabSelectedPosition where
eNextIsSelected
= ieQStyleOptionTabSelectedPosition $ 1
instance QePreviousIsSelected QStyleOptionTabSelectedPosition where
ePreviousIsSelected
= ieQStyleOptionTabSelectedPosition $ 2
data CCornerWidget a = CCornerWidget a
type CornerWidget = QEnum(CCornerWidget Int)
ieCornerWidget :: Int -> CornerWidget
ieCornerWidget x = QEnum (CCornerWidget x)
instance QEnumC (CCornerWidget Int) where
qEnum_toInt (QEnum (CCornerWidget x)) = x
qEnum_fromInt x = QEnum (CCornerWidget x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> CornerWidget -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
data CCornerWidgets a = CCornerWidgets a
type CornerWidgets = QFlags(CCornerWidgets Int)
ifCornerWidgets :: Int -> CornerWidgets
ifCornerWidgets x = QFlags (CCornerWidgets x)
instance QFlagsC (CCornerWidgets Int) where
qFlags_toInt (QFlags (CCornerWidgets x)) = x
qFlags_fromInt x = QFlags (CCornerWidgets x)
withQFlagsResult x
= do
ti <- x
return $ qFlags_fromInt $ fromIntegral ti
withQFlagsListResult x
= do
til <- x
return $ map qFlags_fromInt til
instance Qcs (QObject c -> CornerWidgets -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qFlags_fromInt hint)
return ()
eNoCornerWidgets :: CornerWidget
eNoCornerWidgets
= ieCornerWidget $ 0
eLeftCornerWidget :: CornerWidget
eLeftCornerWidget
= ieCornerWidget $ 1
eRightCornerWidget :: CornerWidget
eRightCornerWidget
= ieCornerWidget $ 2
fNoCornerWidgets :: CornerWidgets
fNoCornerWidgets
= ifCornerWidgets $ 0
fLeftCornerWidget :: CornerWidgets
fLeftCornerWidget
= ifCornerWidgets $ 1
fRightCornerWidget :: CornerWidgets
fRightCornerWidget
= ifCornerWidgets $ 2
|
keera-studios/hsQt
|
Qtc/Enums/Gui/QStyleOptionTab.hs
|
bsd-2-clause
| 12,545
| 0
| 18
| 2,661
| 3,241
| 1,579
| 1,662
| 280
| 1
|
{-#LANGUAGE MonoLocalBinds #-}
module LambdaF where
import Name
import Value
import Lambda as Lam
-- TODO i is always () maybe remove
data LamTermF i j n a = LambdaF i Name a
| ApplF a a
| VarF j n
| ValF j Value
| LetF j [Def i a] a
deriving (Eq, Show)
instance Functor (LamTermF i j n) where
fmap f (LambdaF i n t) = LambdaF i n $ f t
fmap f (ApplF t1 t2) = ApplF (f t1) (f t2)
fmap _ (VarF i n) = VarF i n
fmap _ (ValF i v) = ValF i v
fmap f (LetF i defs t ) = LetF i (map (fmap f) defs) $ f t
instance Traversable (LamTermF i j n) where
traverse _ (VarF i b) = pure (VarF i b)
traverse _ (ValF i v) = pure (ValF i v)
traverse f (LambdaF i n t) = LambdaF i n <$> f t
traverse f (ApplF t1 t2) = ApplF <$> f t1 <*> f t2
traverse f (LetF i defs tn) = LetF i <$> traverse (traverse f ) defs <*> f tn
instance Foldable (LamTermF i j n) where
foldr _ b VarF {} = b
foldr _ b ValF {} = b
foldr f b (LambdaF _ _ a) = f a b
foldr f b (ApplF a1 a2) = f a1 (f a2 b )
foldr f b (LetF _ defs an) = foldr (flip (foldr f) ) (f an b) defs
-- fold :: (b -> LamTermF i n a-> (a,b)) -> b -> a -> LamTerm i n
--FIXME rename
unfold :: (b -> a -> (LamTermF i j n a,b)) -> b -> a -> LamTerm i j n
unfold f b a = case f b a of
(VarF i n,_) -> Lam.Var i n
(ValF i v,_) -> Lam.Val i v
(LambdaF i n t1, b1) -> Lam.Lambda i n (unfold f b1 t1)
(ApplF t1 t2, b1) -> Lam.Appl (unfold f b1 t1) (unfold f b1 t2)
(LetF i defs t, b1) -> Lam.Let i (map (fmap $ unfold f b1) defs) (unfold f b1 t)
--FIXME rename
unfoldM :: Monad m => (b -> a -> m (LamTermF i j n a,b)) -> b -> a -> m (LamTerm i j n)
unfoldM f b a = do
result <- f b a
case result of
(VarF i n,_) -> return $ Lam.Var i n
(ValF i v,_) -> return $ Lam.Val i v
(LambdaF i n t1, b1) -> Lam.Lambda i n <$> unfoldM f b1 t1
(ApplF t1 t2, b1) -> Lam.Appl <$> unfoldM f b1 t1 <*> unfoldM f b1 t2
(LetF i defs t, b1) -> Lam.Let i <$> mapM (mapM$ unfoldM f b1)defs <*> unfoldM f b1 t
wrap :: LamTerm i j n -> LamTermF i j n (LamTerm i j n)
wrap (Lam.Var i n) = VarF i n
wrap (Lam.Val i v) = ValF i v
wrap (Lam.Lambda i n t) = LambdaF i n t
wrap (Lam.Appl t1 t2) = ApplF t1 t2
wrap (Lam.Let i defs t) = LetF i defs t
bottumUpWithM :: Monad m
=> (context -> LamTerm i j n -> m context)
-> (context -> LamTerm i j n -> LamTermF i j n a -> m a) -- TODO maybe change to LamTerm i n (m a) so you can change orer
-> context
-> LamTerm i j n
-> m a
bottumUpWithM updateContext f context0 ast0 = go context0 ast0
where
-- go :: context -> LamTerm i n -> m a
go context ast = do
newContext <- updateContext context ast
astF <- traverse (go newContext) (wrap ast)
f newContext ast astF
bottumUpWith :: (context -> LamTerm i j n -> context)
-> (context -> LamTerm i j n -> LamTermF i j n a -> a)
-> context
-> LamTerm i j n
-> a
bottumUpWith updateContext f context0 ast0 = go context0 ast0
where
-- go :: context -> LamTerm i n -> a
go context ast = f newContext ast (go newContext <$> wrap ast)
where
newContext = updateContext context ast
|
kwibus/myLang
|
src/LambdaF.hs
|
bsd-3-clause
| 3,274
| 0
| 15
| 1,023
| 1,624
| 801
| 823
| 70
| 5
|
{-
BinarySearchTree
by Russell Bentley
A simple Haskell module that implements a basic binary search tree.
-}
module BinarySearchTree (search, insert, delete, flatten, mergeT, buildTree) where
-- | 'BST' stands for Binary Search Tree.
-- The BST type represents that data structure.
data BST a = Nil | Node a (BST a) (BST a)
instance Show a => Show (BST a) where
show Nil = "Nil"
show (Node x t1 t2) = "Node " ++ show x ++ "(" ++ show t1 ++ ", " ++ show t2 ++ ") "
-- | The `mergeL` function takes two sorted lists and merges them.
mergeL :: Ord a => [a] -> [a] -> [a]
mergeL [] ys = ys
mergeL xs [] = xs
mergeL (x:xs) (y:ys) = case compare x y of
LT -> x : mergeL xs (y:ys)
EQ -> x : mergeL xs ys
GT -> y : mergeL ys (x:xs)
-- | The `search` method returns whether a given element is in a BST
search :: Ord a => a -> BST a -> Bool
search _ Nil = False
search x (Node y t1 t2) = case compare x y of
LT -> search x t1
EQ -> True
GT -> search x t2
-- | The `insert` method puts an element into a BST
insert :: Ord a => a -> BST a -> BST a
insert x Nil = Node x Nil Nil
insert x (Node y t1 t2) = case compare x y of
LT -> Node y (insert x t1) t2
EQ -> Node x t1 t2
GT -> Node y t1 (insert x t2)
-- | The `flatten` function returns a sorted list of elements in the BST.
flatten :: Ord a => BST a -> [a]
flatten Nil = []
flatten (Node x t1 t2) = flatten t1 ++ [x] ++ flatten t2
-- | The `buildTree` function takes a sorted list
buildTree :: Ord a => [a] -> BST a
buildTree [] = Nil
buildTree xs = Node (head rs) (buildTree ls) (buildTree $ tail rs)
where
len = length xs `div` 2
ls = take len xs
rs = drop len xs
-- | The `merge` function returns a BST with all the elements of two
mergeT :: Ord a => BST a -> BST a -> BST a
mergeT Nil t1 = t1
mergeT t2 Nil = t2
mergeT t1 t2 = buildTree $ mergeL (flatten t1) (flatten t2)
-- | The `delete` method removes an element from a tree.
delete :: Ord a => a -> BST a -> BST a
delete _ Nil = Nil
delete x (Node y t1 t2) = case compare x y of
LT -> Node y (delete x t1) t2
GT -> Node y t1 (delete x t2)
EQ -> mergeT t1 t2
|
ThermalSpan/haskell-euler
|
src/BinarySearchTree.hs
|
bsd-3-clause
| 3,007
| 0
| 12
| 1,422
| 875
| 437
| 438
| 43
| 3
|
{-# LANGUAGE TemplateHaskell, TypeOperators, ScopedTypeVariables #-}
--------------------------------------------------------------------
-- |
-- Executable : mbox-iter
-- Copyright : (c) Nicolas Pouillard 2009, 2011
-- License : BSD3
--
-- Maintainer: Nicolas Pouillard <nicolas.pouillard@gmail.com>
-- Stability : provisional
-- Portability:
--
--------------------------------------------------------------------
-- import Control.Arrow
import Control.Lens
import Control.Exception
import Codec.Mbox (Mbox(..),Direction(..),parseMboxFiles,opposite,showMboxMessage)
import System.Environment (getArgs)
import System.Console.GetOpt
import System.Exit
import System.IO
import qualified System.Process as P
import qualified Data.ByteString.Lazy as L
data Settings = Settings { _dir :: Direction
, _help :: Bool
}
$(makeLenses ''Settings)
type Flag = Settings -> Settings
systemWithStdin :: String -> L.ByteString -> IO ExitCode
systemWithStdin shellCmd input = do
(Just stdinHdl, _, _, pHdl) <-
P.createProcess (P.shell shellCmd){ P.std_in = P.CreatePipe }
handle (\(_ :: IOException) -> return ()) $ do
L.hPut stdinHdl input
hClose stdinHdl
P.waitForProcess pHdl
iterMbox :: Settings -> String -> [String] -> IO ()
iterMbox opts cmd mboxfiles =
mapM_ (mapM_ (systemWithStdin cmd . showMboxMessage) . mboxMessages)
=<< parseMboxFiles (opts^.dir) mboxfiles
defaultSettings :: Settings
defaultSettings = Settings { _dir = Forward
, _help = False
}
usage :: String -> a
usage msg = error $ unlines [msg, usageInfo header options]
where header = "Usage: mbox-iter [OPTION] <cmd> <mbox-file>*"
options :: [OptDescr Flag]
options =
[ Option "r" ["reverse"] (NoArg (over dir opposite)) "Reverse the mbox order (latest firsts)"
, Option "?" ["help"] (NoArg (set help True)) "Show this help message"
]
main :: IO ()
main = do
args <- getArgs
let (flags, nonopts, errs) = getOpt Permute options args
let opts = foldr ($) defaultSettings flags
if opts^.help
then usage ""
else
case (nonopts, errs) of
(cmd : mboxfiles, []) -> iterMbox opts cmd mboxfiles
(_, _) -> usage (concat errs)
|
np/mbox-tools
|
mbox-iter.hs
|
bsd-3-clause
| 2,271
| 0
| 13
| 479
| 625
| 341
| 284
| 46
| 3
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Marvin.Adapter.Slack.Internal.Types where
import Control.Concurrent.Chan.Lifted (Chan)
import Control.Concurrent.MVar.Lifted (MVar)
import Data.Aeson hiding (Error)
import Data.Aeson.TH
import Data.Aeson.Types hiding (Error)
import Data.Bool (bool)
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.Foldable (toList)
import Data.Hashable
import Data.HashMap.Strict (HashMap)
import Data.String (IsString(..))
import qualified Data.Text as T
import qualified Data.Text.Lazy as L
import Lens.Micro.Platform hiding ((.=))
import Marvin.Adapter
import Marvin.Types
import Network.URI
import Util
jsonParseURI :: Value -> Parser URI
jsonParseURI = withText "expected text"
$ maybe (fail "string not parseable as uri") return . parseURI . T.unpack
data RTMData = RTMData
{ ok :: Bool
, url :: URI
}
type APIResponse a = Either String a
-- | Identifier for a user (internal and not equal to the username)
newtype SlackUserId = SlackUserId { unwrapSlackUserId :: T.Text }
deriving (IsString, Eq, Hashable)
-- | Identifier for a channel (internal and not equal to the channel name)
newtype SlackChannelId = SlackChannelId { unwrapSlackChannelId :: T.Text }
deriving (IsString, Eq, Show, Hashable)
deriveJSON defaultOptions { unwrapUnaryRecords = True } ''SlackUserId
deriveJSON defaultOptions { unwrapUnaryRecords = True } ''SlackChannelId
class HasTopic s a | s -> a where topic :: Lens' s a
class HasIdValue s a | s -> a where idValue :: Lens' s a
class HasNameResolver s a | s -> a where nameResolver :: Lens' s a
class HasInfoCache s a | s -> a where infoCache :: Lens' s a
class HasCreated s a | s -> a where created :: Lens' s a
class HasChanType s a | s -> a where chanType :: Lens' s a
-- class HasMemberCount s a | s -> a where memberCount :: Lens' s a
data ChannelType
= PublicChannel
| PrivateChannel
| IMChannel
deriving Show
data LimitedChannelInfo = LimitedChannelInfo
{ limitedChannelInfoIdValue :: SlackChannelId
, limitedChannelInfoName :: Maybe L.Text
, limitedChannelInfoTopic :: Maybe L.Text
-- , limitedChannelInfoChanType :: ChannelType
-- , limitedChannelInfoMemberCount :: Int
} deriving Show
data UserInfo = UserInfo
{ userInfoUsername :: L.Text
, userInfoIdValue :: SlackUserId
, userInfoName :: Maybe L.Text
, userInfoFirstName :: Maybe L.Text
, userInfoLastName :: Maybe L.Text
}
data ChannelCache = ChannelCache
{ channelCacheInfoCache :: HashMap SlackChannelId LimitedChannelInfo
, channelCacheNameResolver :: HashMap L.Text LimitedChannelInfo
}
data UserCache = UserCache
{ userCacheInfoCache :: HashMap SlackUserId UserInfo
, userCacheNameResolver :: HashMap L.Text UserInfo
}
-- | Adapter for interacting with Slack API's. Polymorphic over the method for retrieving events.
data SlackAdapter a = SlackAdapter
{ slackAdapterChannelCache :: MVar ChannelCache
, slackAdapterUserInfoCache :: MVar UserCache
, slackAdapterOutChannel :: Chan (SlackChannelId, L.Text)
}
data InternalType a
= SlackEvent SlackUserId SlackChannelId (UserInfo -> LimitedChannelInfo -> Event (SlackAdapter a))
| Error
{ code :: Int
, msg :: String
}
| Unhandeled String
| Ignored
| ChannelArchiveStatusChange SlackChannelId Bool
| ChannelCreated LimitedChannelInfo
| ChannelDeleted SlackChannelId
| ChannelRename LimitedChannelInfo
| UserChange UserInfo
| OkResponseEvent T.Text
data SlackRemoteFile a = SlackRemoteFile
{ slackRemoteFileIdValue :: L.Text
, slackRemoteFileCreationDate :: TimeStamp (SlackAdapter a)
, slackRemoteFileName :: Maybe L.Text
, slackRemoteFileTitle :: Maybe L.Text
, slackRemoteFileFileType :: Maybe L.Text
, slackRemoteFilePublicPermalink :: Maybe L.Text
, slackRemoteFileSize :: Integer
, slackRemoteFileEditable :: Bool
, slackRemoteFilePublic :: Bool
, slackRemoteFileUser :: SlackUserId
, slackRemoteFileUrl :: Maybe L.Text
, slackRemoteFilePrivateUrl :: L.Text
}
data SlackLocalFile = SlackLocalFile
{ slackLocalFileName :: L.Text
, slackLocalFileFileType :: Maybe L.Text
, slackLocalFileTitle :: Maybe L.Text
, slackLocalFileComment :: Maybe L.Text
, slackLocalFileContent :: FileContent
}
makeFields ''LimitedChannelInfo
makeFields ''UserInfo
makeFields ''ChannelCache
makeFields ''UserCache
makeFields ''SlackAdapter
makeFields ''SlackRemoteFile
makeFields ''SlackLocalFile
instance FromJSON (TimeStamp (SlackAdapter a)) where parseJSON = timestampFromNumber
instance FromJSON (SlackRemoteFile a) where
parseJSON = withObject "file must be object" $ \o -> SlackRemoteFile
<$> o .: "id"
<*> o .: "created"
<*> o .:? "name"
<*> o .:? "title"
<*> o .:? "filetype"
<*> o .:? "permalink_public"
<*> o .: "size"
<*> o .: "editable"
<*> o .: "is_public"
<*> o .: "user"
<*> o .:? "permalink_public"
<*> o .: "url_private_download"
-- makeFields ''SlackRemoteFile
-- makeFields ''SlackLocalFile
instance FromJSON RTMData where
parseJSON = withObject "expected object" $ \o ->
RTMData <$> o .: "ok" <*> (o .: "url" >>= jsonParseURI)
rawBS :: BS.ByteString -> String
rawBS bs = "\"" ++ BS.unpack bs ++ "\""
helloParser :: Value -> Parser Bool
helloParser = withObject "expected object" $ \o -> do
t <- o .: "type"
return $ (t :: T.Text) == "hello"
userInfoParser :: Value -> Parser UserInfo
userInfoParser = withObject "expected object" $ \o -> do
o2 <- o .: "profile"
UserInfo
<$> o .: "name"
<*> o .: "id"
<*> o2 .:? "real_name"
<*> o2 .:? "first_name"
<*> o2 .:? "last_name"
userInfoListParser :: Value -> Parser [UserInfo]
userInfoListParser = withArray "expected array" (fmap toList . mapM userInfoParser)
apiResponseParser :: (Object -> Parser a) -> Value -> Parser (APIResponse a)
apiResponseParser f = withObject "expected object" $ \o ->
o .: "ok" >>= bool
(Left <$> o .: "error")
(Right <$> f o)
lciParser :: Value -> Parser LimitedChannelInfo
lciParser = withObject "expected object" $ \o ->
LimitedChannelInfo
<$> o .: "id"
<*> o .:? "name"
<*> (o .:? "topic" >>= maybe (return Nothing) (fmap Just . withObject "object" (.: "value")))
-- <*> parseType o
-- <*> o .: "num_members"
-- where
-- parseType o =
-- ifM (o .: "is_channel")
-- (pure PublicChannel)
-- $ ifM (o .: "is_group")
-- (pure PrivateChannel)
-- $ ifM (o .: "is_im")
-- (pure IMChannel)
-- (fail "Expected one of: [is_channel, is_group, is_im] to be true.")
lciListParser :: Value -> Parser [LimitedChannelInfo]
lciListParser = withArray "array" $ fmap toList . mapM lciParser
|
JustusAdam/marvin
|
src/Marvin/Adapter/Slack/Internal/Types.hs
|
bsd-3-clause
| 7,439
| 0
| 31
| 2,009
| 1,704
| 936
| 768
| -1
| -1
|
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
--------------------------------------------------------------------------------
-- |
--
-- Module : Kiosk.Backend.Data.InvoiceTemplate
-- Description :
-- Copyright :
-- License :
-- Maintainer :
-- Stability :
-- Portability :
--
--------------------------------------------------------------------------------
module Kiosk.Backend.Data.InvoiceTemplate where
import Control.Applicative ((<$>), (<*>))
import Control.Lens
import Data.HashMap.Lazy (HashMap)
import qualified Data.HashMap.Lazy as HM
import qualified Data.Map as M
import Data.Map.Lazy (Map)
import Data.Maybe (fromMaybe)
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Time (UTCTime)
import Kiosk.Backend.Data
import Kiosk.Backend.Data.ReportTemplate
import Kiosk.Backend.Form
import QuickBooks
import ReportTemplate.Report
import Text.Read (readMaybe)
--------------------------------------------------------------------------------
-- $setup
--
--
--------------------------------------------------------------------------------
-- QuickBooks invoice report
--------------------------------------------------------------------------------
-- | Sum type to build various pieces of a Quickbooks
data LineElement = LineElementId LineId
| LineElementNum Double
| LineElementDescription Text
| LineElementAmount Double
| LineElementLinkedTxn [LinkedTxn]
| LineElementCustomField CustomField
| LineElementType LineDetailType
| LineElementError Text
deriving (Eq,Show)
data LineDetailType = LineDetailTypeDescriptionLineDetail DescriptionLineDetail
| LineDetailTypeDiscountLineDetail DiscountLineDetail
| LineDetailTypeSalesItemLineDetail [SalesItemLineDetailElement]
| LineDetailTypeSubTotalLineDetail SubTotalLineDetail
deriving (Eq,Show)
data SalesItemLineDetailElement = SalesItemLineDetailElementItemRef ItemRef
| SalesItemLineDetailElementClassRef ClassRef
| SalesItemLineDetailElementUnitPrice Double
| SalesItemLineDetailElementRatePercent Double
| SalesItemLineDetailElementPriceLevelRef PriceLevelRef
| SalesItemLineDetailElementMarkupInfo Text
| SalesItemLineDetailElementQty Double
| SalesItemLineDetailElementTaxCodeRef TaxCodeRef
| SalesItemLineDetailElementServiceData Text
| SalesItemLineDetailElementTaxInclusiveAmt Double
deriving (Eq,Show)
makePrisms ''LineElement
makePrisms ''LineDetailType
makePrisms ''SalesItemLineDetailElement
-- \ generic element constructor
-- | The Labels given in the [Text] list are
-- used to retrieve Text
-- Then two connection functions are ran to complete the transform
-- from a List of Retrieved Text to a final type
genericDataTemplateRetrieval :: forall intermediate final.
([Maybe Text] -> intermediate) ->
(intermediate -> final )-> [Text] -> DataTemplate -> final
genericDataTemplateRetrieval templateFcn ouputConstructor txts dte = ouputConstructor . templateFcn $ targetTextList
where
inputTextLens = _InputTypeText.getInputText
targetTextList :: [Maybe Text]
targetTextList = getInputTypeByLabel inputTextLens <$>
txts <*> [dte]
assembleSalesLineFromList :: [LineElement] -> Either Text Line
assembleSalesLineFromList elementList = buildAmountUp =<<
splitSalesLineDetailAndConstruct elementList =<<
constructMinLine elementList
where
initialSalesItemLine :: Line
initialSalesItemLine = Line Nothing Nothing Nothing Nothing Nothing "SalesItemLineDetail" Nothing Nothing Nothing Nothing Nothing
buildAmountUp :: Line -> Either Text Line
buildAmountUp almostFinalLine = do
sild <- maybe (Left "detail not found") Right (lineSalesItemLineDetail almostFinalLine)
amt <- calculateAmount sild
return $ almostFinalLine {lineAmount = Just amt}
splitSalesLineDetailAndConstruct :: [LineElement] -> Line -> Either Text Line
splitSalesLineDetailAndConstruct elementList' initialLineElement = foldr foldrOverFilteredList (Right initialLineElement) elementList'
constructMinLine :: [LineElement] -> Either Text Line
constructMinLine elementList' = (\salesLineList customFieldList -> initialSalesItemLine {lineSalesItemLineDetail = Just salesLineList
, lineCustomField = Just customFieldList}) <$>
(assembleSalesItemLineDetailFromList .
toListOf (folded._LineElementType._LineDetailTypeSalesItemLineDetail.folded) $ elementList') <*>
(Right . toListOf (folded._LineElementCustomField) $ elementList' )
foldrOverFilteredList :: LineElement -> Either Text Line -> Either Text Line
foldrOverFilteredList (LineElementId e) eitherLine = (\line -> line {lineId = Just e}) <$> eitherLine
foldrOverFilteredList (LineElementNum e) eitherLine = (\line -> line {lineLineNum = Just e}) <$> eitherLine
foldrOverFilteredList (LineElementDescription e) eitherLine = (\line ->line {lineDescription = Just e}) <$> eitherLine
foldrOverFilteredList (LineElementAmount _) lineReturnedThisHasToBeCalculated = lineReturnedThisHasToBeCalculated
foldrOverFilteredList (LineElementLinkedTxn e) eitherLine = (\line -> line {lineLinkedTxn = Just e}) <$> eitherLine
foldrOverFilteredList (LineElementCustomField _) lineNotUsedBecauseCustomFieldsAreFilledElsewhere =
lineNotUsedBecauseCustomFieldsAreFilledElsewhere
foldrOverFilteredList (LineElementType _) lineWhichShouldntBeCalled =
lineWhichShouldntBeCalled -- This is dealt with elsewhere
foldrOverFilteredList (LineElementError t) _ = Left t
-- | None of the fields are marked as required in a sales Item line detail soooo the easiest fold element is an empty one
-- ItemRef is actually requered by the standard however so its existence is checked at the last step
-- Items later in the list have precedence over items earlier in it.
calculateAmount :: SalesItemLineDetail -> Either Text Double
calculateAmount sild = calculatePrice
where
calculatePrice = maybe errMsg Right maybeCalculatePrice
errMsg = Left $ "Price or Qty missing Price:" <>
(Text.pack.show . salesItemLineDetailUnitPrice $ sild) <>
" Qty:" <> (Text.pack . show . salesItemLineDetailQty $ sild)
maybeCalculatePrice = (*) <$> salesItemLineDetailQty sild
<*> salesItemLineDetailUnitPrice sild
assembleSalesItemLineDetailFromList :: [SalesItemLineDetailElement] -> Either Text SalesItemLineDetail
assembleSalesItemLineDetailFromList salesItemLineDetailElementList = makeSureItemRefExists .
foldrSalesItemLineDetail $ salesItemLineDetailElementList
where
makeSureItemRefExists :: SalesItemLineDetail -> Either Text SalesItemLineDetail
makeSureItemRefExists salesItemLineDetail' = maybe errNoItemRef (const $ Right salesItemLineDetail') .
salesItemLineDetailItemRef $ salesItemLineDetail'
errNoItemRef = Left "Missing 'LineDetailItemRef' in SalesItemLineDetail"
initialSalesItemLineDetail :: SalesItemLineDetail
initialSalesItemLineDetail = SalesItemLineDetail Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
foldrSalesItemLineDetail :: [SalesItemLineDetailElement] -> SalesItemLineDetail
foldrSalesItemLineDetail = foldr constructSalesItemLineDetailInFoldr initialSalesItemLineDetail
-- | Pattern Matcher for
constructSalesItemLineDetailInFoldr :: SalesItemLineDetailElement -> SalesItemLineDetail -> SalesItemLineDetail
constructSalesItemLineDetailInFoldr (SalesItemLineDetailElementItemRef e) sild = sild{salesItemLineDetailItemRef = Just e}
constructSalesItemLineDetailInFoldr (SalesItemLineDetailElementClassRef e) sild = sild{salesItemLineDetailClassRef = Just e}
constructSalesItemLineDetailInFoldr (SalesItemLineDetailElementUnitPrice e) sild = sild{salesItemLineDetailUnitPrice = Just e}
constructSalesItemLineDetailInFoldr (SalesItemLineDetailElementRatePercent e) sild = sild{salesItemLineDetailRatePercent = Just e}
constructSalesItemLineDetailInFoldr (SalesItemLineDetailElementPriceLevelRef e) sild = sild{salesItemLineDetailPriceLevelRef = Just e}
constructSalesItemLineDetailInFoldr (SalesItemLineDetailElementMarkupInfo e) sild = sild{salesItemLineDetailMarkupInfo = Just e}
constructSalesItemLineDetailInFoldr (SalesItemLineDetailElementQty e) sild = sild{salesItemLineDetailQty = Just e}
constructSalesItemLineDetailInFoldr (SalesItemLineDetailElementTaxCodeRef e) sild = sild{salesItemLineDetailTaxCodeRef = Just e}
constructSalesItemLineDetailInFoldr (SalesItemLineDetailElementServiceData e) sild = sild{salesItemLineDetailServiceData = Just e}
constructSalesItemLineDetailInFoldr (SalesItemLineDetailElementTaxInclusiveAmt e) sild = sild{salesItemLineDetailTaxInclusiveAmt = Just e}
-- | A QuickBooks invoice report.
type InvoiceReport =
Report Invoice LineElement
-- | A QuickBooks invoice report template.
type InvoiceReportTemplate =
ReportTemplate InvoiceContext Form Invoice DataTemplateEntry LineElement
--------------------------------------------------------------------------------
-- * QuickBooks invoice report context
--------------------------------------------------------------------------------
-- | A QuickBooks invoice report context.
data InvoiceContext = InvoiceContext
{ invoiceContextTime :: UTCTime
,invoiceCompanyRefMap :: HashMap Text CustomerRef
,invoiceItemRefMap :: HashMap Text ItemRef
-- , invoiceTemplate :: InvoiceTemplate
-- , invoiceLineTemplate :: InvoiceLineTemplate
}
--------------------------------------------------------------------------------
-- * Create a QuickBooks invoice
-- create Lines and Invoices from the Report
--------------------------------------------------------------------------------
-- There are lots of errors from which I want to recover. For this reason, I wanted to return partial errors up the chain.
-- That is why the type ends up being kind of crazy at the top. It might be simpler but it isn't now so oh well
reportToInvoice ::
Report Invoice LineElement -> (Text, Maybe Invoice)
reportToInvoice r = maybe (topLevelErrorMessage, Nothing) (\invoice'-> (errorsFromReport, Just invoice')) $
(\invoiceFromReport -> invoiceFromReport {invoiceLine=linesFromReport}) <$>
maybeInvoiceFromReport
where
topLevelErrorMessage = "unableToretrieveInvoice, line errors: " <> errorsFromReport
maybeInvoiceFromReport :: Maybe Invoice
maybeInvoiceFromReport = r ^? reportPreamble.preambleValue.folded._2
lineElementsFromReport :: Maybe (ReportTableRowStyle LineElement)
lineElementsFromReport = r ^? (reportRows. _ReportTableRowIndex._2)
(errorsFromReport,linesFromReport) = fromMaybe ("Missing Report Rows", []) $ makeReportLines <$>
lineElementsFromReport
-- |1. the errors in lines 2. the Values that are correct
makeReportLines :: ReportTableRowStyle LineElement
-> (Text,[Line])
makeReportLines = convertLineElementMapToLineMap . reportRowLineFoldr
where
groupErrorsAssembleLines :: [LineElement] -> (Text,[Line]) -> (Text,[Line])
groupErrorsAssembleLines leLst (errs,vals) = either (\err -> (err<> " " <> " " <>errs, vals))
(\val -> (errs,val:vals)) . assembleSalesLineFromList $ leLst
convertLineElementMapToLineMap :: Map RowNumber [LineElement] -> (Text, [Line])
convertLineElementMapToLineMap = M.foldr groupErrorsAssembleLines ("",[])
reportRowLineFoldr :: ReportTableRowStyle LineElement -> Map RowNumber [LineElement]
reportRowLineFoldr = foldrTableByRowWithIndex lineListMapConstructor M.empty
lineListMapConstructor (r,_) i map' = M.insertWith (\nv ov -> nv ++ ov) r [i] map'
--------------------------------------------------------------------------------
-- * Utility functions
--------------------------------------------------------------------------------
-- |
dataTemplateItems
:: DataTemplate
-> [(Text,InputType)]
dataTemplateItems DataTemplate{templateItems} =
fmap (\TemplateItem{..} -> (label,templateValue)) templateItems
-- |
defaultLookupInDataTemplate
:: DataTemplate
-> Text
-> Maybe InputType
defaultLookupInDataTemplate dataTemplate =
flip lookup (dataTemplateItems dataTemplate)
-- |
defaultLookupDoubleInDataTemplate
:: DataTemplate
-> Text
-> Maybe Double
defaultLookupDoubleInDataTemplate dataTemplate label =
let
maybeTextValue =
defaultLookupTextInDataTemplate dataTemplate label
in
fmap Text.unpack maybeTextValue >>= readMaybe
-- |
defaultLookupTextInDataTemplate
:: DataTemplate
-> Text
-> Maybe Text
defaultLookupTextInDataTemplate dataTemplate label =
case defaultLookupInDataTemplate dataTemplate label of
Just (InputTypeText textValue) ->
Just (_getInputText textValue)
_ ->
Nothing
-- |
--
-- "02/03/2015 Barrels of fresh water disposed of. Ticket #A-1183"
defaultDataTemplateToLineDescription :: DataTemplate -> Text
defaultDataTemplateToLineDescription dataTemplate =
Text.intercalate
" "
[ dateDescription
, waterDescription
, ticketDescription
]
where
dateDescription :: Text
dateDescription =
fromMaybe
""
(defaultLookupTextInDataTemplate dataTemplate "Date")
ticketDescription :: Text
ticketDescription =
Text.append "Ticket #" ticketNumber
ticketNumber :: Text
ticketNumber =
fromMaybe
""
(defaultLookupTextInDataTemplate dataTemplate "Customer_Ticket_#")
water :: Text
water =
fromMaybe
""
(defaultLookupTextInDataTemplate dataTemplate "Type_of_Water_Hauled")
waterDescription :: Text
waterDescription =
Text.concat ["Barrels of ", Text.toLower water, " disposed of."]
|
plow-technologies/cobalt-kiosk-data-template
|
src/Kiosk/Backend/Data/InvoiceTemplate.hs
|
bsd-3-clause
| 15,326
| 0
| 16
| 3,564
| 2,452
| 1,343
| 1,109
| -1
| -1
|
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE TypeFamilies #-}
module Game.MetaGame.Types.Board
( BoardC (..)
, MachineState (..), MachineStateId (..)
) where
import Data.Text (Text)
import Control.Monad.Trans.Except (Except)
import Game.MetaGame.Types.Core
import Game.MetaGame.Types.Inquiry
data MachineState
= Prepare -- ^ the game has not yet been started and only 'Admin' should take actions
| WaitForTurn -- ^ last turn was done completly and current player should choose his action
| forall a.
(Show a) =>
WaitForChoice (Inquiry a) -- ^ current turn requires more imput, which needs to be provided by some user
| GameOver UserId -- ^ there was already an game ending situation and mentioned user has won, nothing should be able to change the current board
instance Eq MachineState where
Prepare == Prepare = True
WaitForTurn == WaitForTurn = True
(WaitForChoice _) == (WaitForChoice _) = True
(GameOver gr1) == (GameOver gr2) = gr1 == gr2
_ == _ = False
instance Show MachineState where
show Prepare = "Prepare"
show WaitForTurn = "WaitForTurn"
show (WaitForChoice inq) = "WaitForChoice: " ++ show inq
show (GameOver winner) = "GameOver: " ++ show winner ++ " has won"
instance View MachineState where
getOwner (WaitForChoice inq) = getOwner inq
getOwner _ = Guest
showRestricted (WaitForChoice inq) = "WaitForChoice: " ++ showRestricted inq
showRestricted ms = show ms
data MachineStateId = MachineStateId
deriving (Eq,Show)
type instance IdF MachineState = MachineStateId
instance IdAble MachineState where
idOf _ = MachineStateId
class IdAble board =>
BoardC board where
emptyBoard :: board
-- | metainformation on the state of the board
getMachineState' :: board -> MachineState
-- | set the metainfo
setMachineState' :: MachineState -> board -> board
-- | get the player, which is expected to act next (take a turn, give an answer, ...)
-- if another user is acting, the game fails
getCurrentPlayer' :: board -> UserId
-- | the current turn is done
advancePlayerOrder :: board -> board
-- | atomic update
-- this should check for winning conditions and do all other checks, which
-- depend on the current state and could happen in mid turn
doAtomicUpdate :: board -> Except Text board
-- | unpack the currently known result from the board
-- If there is a winner, the board should know about it
getWinner :: board -> Maybe UserId
getWinner b = case getMachineState' b of
GameOver winner -> Just winner
_ -> Nothing
-- | determine whether the game has already a winner and thus is ended
hasWinner :: board -> Bool
hasWinner board = case getWinner board of
Just _ -> True
Nothing -> False
|
maximilianhuber/innovation
|
lib/Game/MetaGame/Types/Board.hs
|
bsd-3-clause
| 2,953
| 0
| 10
| 768
| 553
| 297
| 256
| 53
| 0
|
{-# LANGUAGE OverloadedStrings #-}
module Kai.Syntax where
import qualified Language.Lua.Syntax as Lua
import qualified Data.ByteString.Lazy as BS
import qualified Data.ByteString.Lazy.Char8 as C8
import Data.Sequence ((|>),(<|), ViewL(..), ViewR(..))
import qualified Data.Sequence as S
import qualified Data.Vector as V
import Data.Monoid
import qualified Data.Foldable as F
import qualified Text.PrettyPrint.Leijen as PP
data KaiLua a = Call !a (Lua.FunctionCall ()) | Block !a (Lua.Block a)
deriving (Show, Eq)
newtype LuaRef = LuaRef Int
deriving (Show, Eq)
data TypingBit a
= TypingLua !a LuaRef -- 'bound' to a (KaiLua a)
| TypingNewPar !a
| TypingSpace !a
| TypingSymbol !a BS.ByteString
| TypingMath !a (Math a)
deriving (Show, Eq)
instance PP.Pretty (TypingBit a) where
pretty (TypingLua _ (LuaRef r)) = PP.text $ "<" <> show r <> ">"
pretty (TypingNewPar _) = PP.line PP.<> PP.line
pretty (TypingSpace _) = PP.text " "
pretty (TypingSymbol _ bs) = PP.text (C8.unpack bs)
pretty (TypingMath _ m) = PP.hcat [PP.text "[", PP.pretty m, PP.text "]"]
data Typing a = Typing !a (S.Seq (TypingBit a))
deriving (Show, Eq)
instance PP.Pretty (Typing a) where
pretty (Typing _ tbs) = PP.hcat . map PP.pretty . F.toList $ tbs
data MathBit a
= MathLua !a LuaRef
| MathOp !a MathOp (MathBit a) (MathBit a)
| MathSymbol !a BS.ByteString
| SubMath !a (Math a)
deriving (Show, Eq)
instance PP.Pretty (MathBit a) where
pretty (MathLua _ (LuaRef r)) = PP.text $ "<" <> show r <> ">"
pretty (MathOp _ op x y) = PP.hsep [PP.pretty x, PP.pretty op, PP.pretty y]
pretty (MathSymbol _ bs) = PP.text . C8.unpack $ bs
pretty (SubMath _ m) = PP.hcat [PP.text "{", PP.pretty m, PP.text "}"]
data MathOp = MathSub | MathSup
deriving (Show, Eq)
instance PP.Pretty MathOp where
pretty MathSub = PP.text "_"
pretty MathSup = PP.text "^"
data Math a = Math !a (S.Seq (MathBit a))
deriving (Show, Eq)
instance PP.Pretty (Math a) where
pretty (Math _ mbs) = PP.hsep . map PP.pretty . F.toList $ mbs
data KaiDoc a = KaiDoc
{ kaiDocAnnotation :: a
, kaiRoot :: Lua.FunctionCall ()
, kaiDocTypings :: V.Vector (Typing a)
}
deriving (Show, Eq)
instance PP.Pretty (KaiDoc a) where
pretty kd = PP.vsep $ PP.pretty (kaiRoot kd) : (concatMap (\(n,t) -> [PP.text $ "--- Typing " <> show n <> " ---", PP.pretty t]) . zip [0..] . F.toList . kaiDocTypings $ kd)
|
ScrambledEggsOnToast/Kai
|
src/Kai/Syntax.hs
|
bsd-3-clause
| 2,482
| 0
| 19
| 541
| 1,068
| 567
| 501
| 85
| 0
|
{-# LANGUAGE TemplateHaskell #-}
module QCommon.PMoveGlobals where
import Control.Lens (makeLenses)
import qualified Data.Vector as V
import Linear.V3 (V3(..))
import qualified Constants
import Game.PMoveT
import QCommon.PmlT
import Types
makeLenses ''PMoveGlobals
initialPMoveGlobals :: PMoveGlobals
initialPMoveGlobals = PMoveGlobals
{ _pmPM = newPMoveT
, _pmPML = newPmlT
, _pmPlanes = V.replicate Constants.maxClipPlanes (V3 0 0 0)
, _pmStopSpeed = 100
, _pmMaxSpeed = 300
, _pmDuckSpeed = 100
, _pmAccelerate = 10
, _pmAirAccelerate = 0
, _pmWaterAccelerate = 10
, _pmFriction = 6
, _pmWaterFriction = 1
, _pmWaterSpeed = 400
}
|
ksaveljev/hake-2
|
src/QCommon/PMoveGlobals.hs
|
bsd-3-clause
| 816
| 0
| 9
| 272
| 167
| 104
| 63
| 24
| 1
|
#!/usr/bin/env runhaskell
-- Reads markdown (man/xmonad.1.markdown) from stdin, subtitutes
-- ___KEYBINDINGS___ for key-binding definitions generated from
-- src/XMonad/Config.hs, prints result to stdout.
--
-- Unlike the rest of xmonad, this file is released under the GNU General
-- Public License version 2 or later. (Historical reasons, used to link with
-- GPL-licensed pandoc.)
import Data.Char
import Data.List
main :: IO ()
main = do
keybindings <- guessBindings
interact $ unlines . replace "___KEYBINDINGS___" keybindings . lines
-- | The format for the docstrings in "Config.hs" takes the following form:
--
-- @
-- -- mod-x %! Frob the whatsit
-- @
--
-- "Frob the whatsit" will be used as the description for keybinding "mod-x".
-- If the name of the key binding is omitted, the function tries to guess it
-- from the rest of the line. For example:
--
-- @
-- [ ((modMask .|. shiftMask, xK_Return), spawn "xterm") -- %! Launch an xterm
-- @
--
-- Here, "mod-shift-return" will be used as the key binding name.
guessBindings :: IO String
guessBindings = do
buf <- readFile "./src/XMonad/Config.hs"
return (intercalate "\n\n" (map markdownDefn (allBindings buf)))
allBindings :: String -> [(String, String)]
allBindings = concatMap parseLine . lines
where
parseLine :: String -> [(String, String)]
parseLine l
| " -- " `isInfixOf` l
, Just d <- parseDesc l = [(intercalate "-" (parseKeys l), d)]
| otherwise = []
parseDesc :: String -> Maybe String
parseDesc = fmap (trim . drop 4) . find (" %! " `isPrefixOf`) . tails
parseKeys :: String -> [String]
parseKeys l = case lex l of
[("", _)] -> []
[("--", rest)] -> case words rest of
k : "%!" : _ -> [k]
_ -> []
[(k, rest)] -> parseKey k ++ parseKeys rest
parseKey :: String -> [String]
parseKey k | "Mask" `isSuffixOf` k = [reverse (drop 4 (reverse k))]
| "xK_" `isPrefixOf` k = [map toLower (drop 3 k)]
| otherwise = []
-- FIXME: What escaping should we be doing on these strings?
markdownDefn :: (String, String) -> String
markdownDefn (key, desc) = key ++ "\n: " ++ desc
replace :: Eq a => a -> a -> [a] -> [a]
replace x y = map (\a -> if a == x then y else a)
trim :: String -> String
trim = reverse . dropWhile isSpace . reverse . dropWhile isSpace
|
xmonad/xmonad
|
util/GenerateManpage.hs
|
bsd-3-clause
| 2,399
| 0
| 14
| 579
| 632
| 341
| 291
| 36
| 4
|
module PBKDF2 where
import Data.Bits
import Data.Word
import Data.Char (ord)
import Data.List (unfoldr, intersperse)
-- for converting between words of different size and other numbers.
import qualified Codec.Binary.UTF8.String as S
import Numeric
-- for testing.
import Debug.Trace
import Test.QuickCheck (quickCheck, Property)
import qualified Test.QuickCheck as Q
import qualified Data.HMAC as HMAC (hmac_sha1)
import qualified Data.Digest.SHA1 as SHA1
--------------------------------------------------------------------------------
-- * PBKDF2.
--
-- 1. If dkLen > (2^32 - 1) * hLen, output "derived key too long" and
-- stop.
--
-- 2. Let l be the number of hLen-octet blocks in the derived key,
-- rounding up, and let r be the number of octets in the last
-- block:
--
-- l = ceiling (dkLen / hLen) ,
-- r = dkLen - (l - 1) * hLen .
--
-- 3. For each block of the derived key apply the function F defined
-- below to the password P, the salt S, the iteration count c, and
-- the block index to compute the block:
--
-- T_1 = F (P, S, c, 1) ,
-- T_2 = F (P, S, c, 2) ,
-- ...
-- T_l = F (P, S, c, l) ,
--
-- where the function F is defined as the exclusive-or sum of the
-- first c iterates of the underlying pseudorandom function PRF
-- applied to the password P and the concatenation of the salt S
-- and the block index i:
--
-- F (P, S, c, i) = U_1 ⊕ U_2 ⊕ ... ⊕ U_c
--
-- where
--
-- U_1 = PRF (P, S ∥ int (i)) ,
-- U_2 = PRF (P, U_1) ,
-- ...
-- U_c = PRF (P, U_{c-1}) .
--
-- 4. Concatenate the blocks and extract the first dkLen octets to
-- produce a derived key DK:
--
-- DK = T_1 ∥ T_2 ∥ ... ∥ T_l<0..r-1>
--
-- 5. Output the derived key DK.
--
--------------------------------------------------------------------------------
type Password = [Word8] -- password, an octet string.
type Salt = [Word8] -- salt, an octet string.
type Hash = [Word8] -- derived key, a dkLen-octet string.
-- *** I have slightly modified the algorithm and skipped 'r', which is used to
-- drop any extra blocks introduced by rounding 'l'. Since these are dropped
-- from the last blocks, we could just as well grab the 'dkLen' first blocks
-- instead. This is under the assumption that 'dkLen' is a multiple of 8.
pbkdf2 :: Password -> Salt -> Int -> Int -> Hash
pbkdf2 pswd salt c dkLen
| dkLen > (2^32 - 1) * hLen = error "derived key too long"
| otherwise =
let l = dkLen `mdiv` hLen
us :: Int -> [[Word8]]
us i = take c
$ iterate (hmac pswd)
$ hmac pswd (salt ++ int4b i)
f :: Int -> [Word8]
f i = foldr1 mxor (us i)
ts :: [[Word8]]
ts = map f [1..l]
in
take dkLen $ concat ts
-- length in octest of pseudorandom function input, SHA1 blocks are 512 bits.
blocksize :: Int
blocksize = 64
-- length in octets of pseudorandom function output, SHA1 outputs 160 bits.
hLen :: Int
hLen = 20
--------------------------------------------------------------------------------
-- * HMAC-SHA1.
--
-- The definition of HMAC requires a cryptographic hash function, for which we
-- will use SHA1 and we denote by H, and a secret key K. We denote by B the
-- byte-length of blocks (B=64 for SHA1), and by L the byte-length of hash
-- outputs (L=20 for SHA-1). The authentication key K can be of any length up
-- to B. Applications that use keys longer than B bytes will first hash the key
-- using H and then use the resultant L byte string as the actual key to HMAC.
-- In any case the minimal recommended length for K is L bytes.
--
-- We define two fixed and different strings ipad and opad as follows
-- (the 'i' and 'o' are mnemonics for inner and outer):
--
-- ipad = the byte 0x36 repeated B times
-- opad = the byte 0x5C repeated B times.
--
-- To compute HMAC over the data 'text' we perform
--
-- H(K XOR opad, H(K XOR ipad, text))
--
-- Namely,
--
-- (1) append zeros to the end of K to create a B byte string
-- (e.g., if K is of length 20 bytes and B=64, then K will be
-- appended with 44 zero bytes 0x00)
-- (2) XOR (bitwise exclusive-OR) the B byte string computed in step
-- (1) with ipad
-- (3) append the stream of data 'text' to the B byte string resulting
-- from step (2)
-- (4) apply H to the stream generated in step (3)
-- (5) XOR (bitwise exclusive-OR) the B byte string computed in
-- step (1) with opad
-- (6) append the H result from step (4) to the B byte string
-- resulting from step (5)
-- (7) apply H to the stream generated in step (6) and output
-- the result
--
--------------------------------------------------------------------------------
hmac :: [Word8] -- message, an octet string.
-> [Word8] -- encryption key, an octet string.
-> [Word8] -- encoded message, an octet string.
hmac msg key =
let sized_key = hmac_padded_key key
o_key_pad = (0x5c `mrepeat` blocksize) `mxor` sized_key
i_key_pad = (0x36 `mrepeat` blocksize) `mxor` sized_key
in
sha1(o_key_pad ++ sha1(i_key_pad ++ msg))
hmac_padded_key :: [Word8] -> [Word8]
hmac_padded_key key = k ++ (0x00 `mrepeat` (blocksize - length k))
where k | length key > blocksize = sha1 key
| otherwise = key
----------------------------------------
prop_hmac_key_len :: [Word8] -> Property
prop_hmac_key_len key = length (hmac_padded_key key) Q.=== blocksize
--------------------------------------------------------------------------------
-- * SHA1
--
-- ...
--
--------------------------------------------------------------------------------
data Block = H !Word32 !Word32 !Word32 !Word32 !Word32
addBlock :: Block -> Block -> Block
addBlock (H a1 b1 c1 d1 e1) (H a2 b2 c2 d2 e2) =
H (a1+a2) (b1+b2) (c1+c2) (d1+d2) (e1+e2)
-- underlying pseudorandom function (hLen denotes the length in octets of the
-- pseudorandom function output).
sha1 :: [Word8] -> [Word8]
sha1 msg =
let f :: Int -> Word32 -> Word32 -> Word32 -> Word32
f t b c d
| 0 <= t && t <= 19 = (b .&. c) .|. ((complement b) .&. d)
| 20 <= t && t <= 39 = b `xor` c `xor` d
| 40 <= t && t <= 59 = (b .&. c) .|. (b .&. d) .|. (c .&. d)
| 60 <= t && t <= 79 = b `xor` c `xor` d
k :: Int -> Word32
k t
| 0 <= t && t <= 19 = 0x5a827999
| 20 <= t && t <= 39 = 0x6ed9eba1
| 40 <= t && t <= 59 = 0x8f1bbcdc
| 60 <= t && t <= 79 = 0xca62c1d6
step :: [Word32] -> Int -> Block -> Block
step w t (H a b c d e) = (H temp a (b `rotateL` 30) c d)
where
temp = (a `rotateL` 5) + (f t b c d) + e + (w !! t) + (k t)
block :: [Word32] -> Block -> Block
block ws ib = foldl (\b i -> step ws i b) ib [0..79]
process :: [[Word32]] -> Block -> Block
process ws ib = foldl (\b w -> b `addBlock` block w b) ib ws
words :: Block -> [Word8]
words (H a b c d e) = padding $ unroll $
(fromIntegral a `shiftL` 128) +
(fromIntegral b `shiftL` 96) +
(fromIntegral c `shiftL` 64) +
(fromIntegral d `shiftL` 32) +
(fromIntegral e)
where
padding :: [Word8] -> [Word8]
padding xs = 0x00 `mrepeat` (length xs - hLen) ++ xs
in
words $ process (sha1_preprocess msg) (sha1_init)
-- ...
sha1_init :: Block
sha1_init = H 0x67452301 0xefcdab89 0x98badcfe 0x10325476 0xc3d2e1f0
-- ...
sha1_padding :: [Word8] -> [Word8]
sha1_padding msg =
msg ++ [0x80] ++ (0x00 `mrepeat` padding) ++ int8b (mbits msg)
where
blocks :: Int
blocks = (length msg + 1) `mod` 64
padding :: Int
padding = if (blocks > 56) then (56 + 64 - blocks) else (56 - blocks)
-- A message is processed in successive 512-bit chunks, where each chunk is
-- is broken into sixteen 32-bit big-endian words and then exdented into
-- eighty 32-bit words according to:
--
-- for i from 16 to 79
-- w[i] = (w[i-3] xor w[i-8] xor w[i-14] xor w[i-16]) leftrotate 1
--
sha1_preprocess :: [Word8] -> [[Word32]]
sha1_preprocess = map (extend . map b2w . mchunk 4) . mchunk 64 . sha1_padding
where
word :: [Word32] -> Int -> Word32
word w i =
( (w !! (i-3))
`xor` (w !! (i-8))
`xor` (w !! (i-14))
`xor` (w !! (i-16))
)
`rotateL` 1
extend :: [Word32] -> [Word32]
extend ws = foldl (\w i -> w ++ [word w i]) ws [16..79]
----------------------------------------
prop_sha1_padding_len :: [Word8] -> Property
prop_sha1_padding_len msg = length (sha1_padding msg) `mod` 64 Q.=== 0
prop_sha1_preprocess_len :: [Word8] -> Property
prop_sha1_preprocess_len msg = error "todo"
--------------------------------------------------------------------------------
-- ** Operations from above specifications.
mbits :: [Word8] -> Int
mbits = (8*) . length
mdiv :: Int -> Int -> Int
mdiv a b = ceiling ((fromIntegral a) / (fromIntegral b))
mxor :: [Word8] -> [Word8] -> [Word8]
mxor = zipWith (xor)
mrepeat :: Word8 -> Int -> [Word8]
mrepeat = flip replicate
mchunk :: Int -> [a] -> [[a]]
mchunk s [] = []
mchunk s xs = let (h,t) = splitAt s xs in h : mchunk s t
----------------------------------------
int8b :: Int -> [Word8]
int8b i = mint i 8
int4b :: Int -> [Word8]
int4b i = mint i 4
-- INT i b is a b-octet encoding of the integer i, most significant octet first.
mint :: Int -> Int -> [Word8]
mint num bytes
| length o > bytes = error "INT(i): size too big."
| length o < bytes = (0x00 `mrepeat` (bytes - length o)) ++ o
| otherwise = o
where o = unroll (fromIntegral num)
--------------------------------------------------------------------------------
-- ** Conversion between word and integer types.
unroll :: Integer -> [Word8]
unroll = unfoldr stepR
where
stepR 0 = Nothing
stepR i = Just (fromIntegral i, i `shiftR` 8)
roll :: [Word8] -> Integer
roll = foldr stepL 0
where
stepL b a = a `shiftL` 8 .|. fromIntegral b
----------------------------------------
b2w :: [Word8] -> Word32
b2w = fromIntegral . roll
----------------------------------------
prop_octets_id :: Integer -> Property
prop_octets_id i = i >= 0 Q.==> roll (unroll i) Q.=== i
--------------------------------------------------------------------------------
-- ** Testing & QuickCheck.
-- In WPA2: DK = PBKDF2(HMAC−SHA1, passphrase, ssid, 4096, 256).
wpa2 pswd salt = pbkdf2 pswd salt 4096 256
-- HMAC_SHA1("key", "The quick brown fox jumps over the lazy dog") =
-- 0xde7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9
msg = S.encode "The quick brown fox jumps over the lazy dog"
key = S.encode "key"
res = 0xde7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9 :: Integer
----------------------------------------
hash :: [Word8] -> [Word8]
hash = padding . unroll . SHA1.toInteger . SHA1.hash
where
padding :: [Word8] -> [Word8]
padding xs = 0x00 `mrepeat` (length xs - hLen) ++ xs
--------------------------------------------------------------------------------
-- the end.
|
markus-git/PBKDF2
|
src/PBKDF2.hs
|
bsd-3-clause
| 11,210
| 0
| 16
| 2,790
| 2,651
| 1,486
| 1,165
| 156
| 2
|
module D12Lib where
import Control.Monad
import Data.Char
import Data.List
import Data.Maybe
import Text.Parsec hiding (Error)
import Text.Parsec.String
type Register = (Char, Int)
data RegOperand = Reg Char deriving (Eq, Show)
type RegOrIntOperand = Either RegOperand Int
data Instruction =
Cpy RegOrIntOperand RegOperand |
Jnz RegOrIntOperand Int |
Inc RegOperand |
Dec RegOperand
deriving (Eq, Show)
data VM = VM
{ registers :: [Register]
, tape :: [Instruction]
, pos :: Int
} deriving (Eq, Show)
instructionsP :: Parser [Instruction]
instructionsP = instructionP `sepEndBy1` newline
instructionP :: Parser Instruction
instructionP = choice $ map try [cpyP, incP, decP, jnzP]
cpyP :: Parser Instruction
cpyP = do
void $ string "cpy "
operand1 <- eitherP registerP numberP
void $ space
operand2 <- registerP
return $ Cpy operand1 operand2
incP :: Parser Instruction
incP = do
void $ string "inc "
operand1 <- registerP
return $ Inc operand1
decP :: Parser Instruction
decP = do
void $ string "dec "
operand1 <- registerP
return $ Dec operand1
jnzP :: Parser Instruction
jnzP = do
void $ string "jnz "
operand1 <- eitherP registerP numberP
void $ space
operand2 <- numberP
return $ Jnz operand1 operand2
eitherP :: Parser a -> Parser b -> Parser (Either a b)
eitherP pl pr = (Left <$> pl) <|> (Right <$> pr)
registerP :: Parser RegOperand
registerP = Reg <$> lower
numberP :: Parser Int
numberP = read <$> (negNumber <|> number)
where
negNumber = (:) <$> char '-' <*> number
number = many1 digit
terminated :: VM -> Bool
terminated VM { tape = ops, pos = p } = p >= length ops
newVM :: [Instruction] -> VM
newVM ops = VM
{ registers = [('a', 0), ('b', 0), ('c', 0), ('d', 0)]
, tape = ops
, pos = 0
}
newVM2 :: [Instruction] -> VM
newVM2 ops = VM
{ registers = [('a', 0), ('b', 0), ('c', 1), ('d', 0)]
, tape = ops
, pos = 0
}
step :: VM -> VM
step vm@VM { registers = rs, tape = ops, pos = p } = apply vm (ops !! p)
apply :: VM -> Instruction -> VM
apply vm (Cpy (Left r0) r1) = -- read r0, write to r1, new vm, move 1
move (set vm r1 (get vm r0)) 1
apply vm (Cpy (Right v) r) = -- write c to r, new vm, move 1
move (set vm r v) 1
apply vm (Inc r) = -- increment r, move 1
move (set vm r ((get vm r) + 1)) 1
apply vm (Dec r) = -- decrement r, move 1
move (set vm r ((get vm r) - 1)) 1
apply vm (Jnz (Left r) c) = apply vm (Jnz (Right (get vm r)) c)
apply vm (Jnz (Right c0) c1) = -- if c0 == 0, move c1, otherwise move 1
if c0 /= 0
then move vm c1
else move vm 1
get :: VM -> RegOperand -> Int
get vm (Reg r) = fromMaybe (error "bad register") $ lookup r (registers vm)
set :: VM -> RegOperand -> Int -> VM
set vm (Reg r) v = VM
{ registers = (map setReg . registers) vm
, tape = tape vm
, pos = pos vm }
where
setReg (rc, rv) | rc == r = (rc, v)
setReg (rc, rv) = (rc, rv)
{- | move tape position -}
move :: VM -> Int -> VM
move VM { registers = rs, tape = t, pos = p } c = VM
{ registers = rs
, tape = t
, pos = p + c
}
run :: VM -> VM
run = until terminated step
|
wfleming/advent-of-code-2016
|
2016/src/D12Lib.hs
|
bsd-3-clause
| 3,200
| 0
| 11
| 846
| 1,356
| 728
| 628
| 101
| 2
|
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# OPTIONS_GHC -F -pgmF trhsx #-}
module Crete.Templates.Menu where
import Control.Monad.Reader
import Data.Time (getCurrentTime)
import Happstack.Server
--import Happstack.Server.HSP.HTML
import HSX.XMLGenerator
import Crete.Url.Url (Sitemap(..), Url(..), translate, gePage, geProduct, slashUrlToStr)
import Crete.Type
import qualified Data.Text as Text
adjustWidth :: [a] -> Int
adjustWidth = (60 +) . (10 *) . length
dropdownbar ::
(MonadReader Config m, ServerMonad m, Functor m,
MonadIO m, XMLGenerator m) =>
Url -> m (XMLType m)
dropdownbar url = do
items <- map gePage `fmap` askCnf cnfPages
subitems <- map geProduct `fmap` askCnf cnfProducts
dp <- askCnf cnfProductPage
let isProd (WithLang _ (Page str)) = str == Text.pack dp
isProd _ = False
go (WithLang _ (Products _ _)) thisurl | isProd thisurl =
<li class="listmenu" id="active">
<% translate thisurl %>
<% submenu thisurl %>
</li>
go u thisurl | u == thisurl =
<li class="listmenu" id="active">
<% translate thisurl %>
<% submenu thisurl %>
</li>
go _ thisurl | isProd thisurl =
<li class="listmenu">
<% translate thisurl %>
<% submenu thisurl %>
</li>
go _ thisurl =
<li class="listmenu">
<a href=(slashUrlToStr thisurl)><% translate thisurl %></a>
<% submenu thisurl %>
</li>
submenu u | isProd u =
[<ul><% zipWith smitem [0::Int ..] subitems %></ul>]
submenu _ = []
smitem n u =
<li class="listsubmenu" id=("sub" ++ show n)>
<div>
<a href=(slashUrlToStr u)><% translate u %></a>
</div>
</li>
unXMLGenT $
<div class="dropdownheader">
<ul>
<% map (go url) items %>
</ul>
</div>
header ::
(MonadReader Config m, ServerMonad m, Functor m,
MonadIO m, XMLGenerator m) =>
Url -> m (XMLType m)
header url = dropdownbar url
footer ::
(MonadReader Config m, ServerMonad m, Functor m,
MonadIO m, XMLGenerator m) =>
m (XMLType m)
footer = do
time <- liftIO $ getCurrentTime
items <- map gePage `fmap` askCnf cnfFooters
let f thisurl =
<td width=(adjustWidth $ translate thisurl)>
<a href=(slashUrlToStr thisurl)>
<% translate thisurl %></a></td>
unXMLGenT $
<div class="footer">
<table class="footermenu">
<tr><% map f items %>
<td class="time"><% show time %></td></tr>
</table>
</div>
|
fphh/crete
|
src/Crete/Templates/Menu.hs
|
bsd-3-clause
| 2,751
| 91
| 26
| 806
| 1,025
| 519
| 506
| -1
| -1
|
module Distribution.Client.Dependency.Modular
( modularResolver, SolverConfig(..)) where
-- Here, we try to map between the external cabal-install solver
-- interface and the internal interface that the solver actually
-- expects. There are a number of type conversions to perform: we
-- have to convert the package indices to the uniform index used
-- by the solver; we also have to convert the initial constraints;
-- and finally, we have to convert back the resulting install
-- plan.
import Data.Map as M
( fromListWith )
import Distribution.Client.Dependency.Modular.Assignment
( Assignment, toCPs )
import Distribution.Client.Dependency.Modular.Dependency
( RevDepMap )
import Distribution.Client.Dependency.Modular.ConfiguredConversion
( convCP )
import Distribution.Client.Dependency.Modular.IndexConversion
( convPIs )
import Distribution.Client.Dependency.Modular.Log
( logToProgress )
import Distribution.Client.Dependency.Modular.Package
( PN )
import Distribution.Client.Dependency.Modular.Solver
( SolverConfig(..), solve )
import Distribution.Client.Dependency.Types
( DependencyResolver, PackageConstraint(..) )
import Distribution.Client.InstallPlan
( PlanPackage )
import Distribution.System
( Platform(..) )
-- | Ties the two worlds together: classic cabal-install vs. the modular
-- solver. Performs the necessary translations before and after.
modularResolver :: SolverConfig -> DependencyResolver
modularResolver sc (Platform arch os) cid iidx sidx pprefs pcs pns =
fmap (uncurry postprocess) $ -- convert install plan
logToProgress (maxBackjumps sc) $ -- convert log format into progress format
solve sc idx pprefs gcs pns
where
-- Indices have to be converted into solver-specific uniform index.
idx = convPIs os arch cid iidx sidx
-- Constraints have to be converted into a finite map indexed by PN.
gcs = M.fromListWith (++) (map (\ pc -> (pcName pc, [pc])) pcs)
-- Results have to be converted into an install plan.
postprocess :: Assignment -> RevDepMap -> [PlanPackage]
postprocess a rdm = map (convCP iidx sidx) (toCPs a rdm)
-- Helper function to extract the PN from a constraint.
pcName :: PackageConstraint -> PN
pcName (PackageConstraintVersion pn _) = pn
pcName (PackageConstraintInstalled pn ) = pn
pcName (PackageConstraintSource pn ) = pn
pcName (PackageConstraintFlags pn _) = pn
pcName (PackageConstraintStanzas pn _) = pn
|
alphaHeavy/cabal
|
cabal-install/Distribution/Client/Dependency/Modular.hs
|
bsd-3-clause
| 2,594
| 0
| 13
| 547
| 460
| 273
| 187
| 39
| 5
|
import qualified Data.Char as Char
s :: String
s = concatMap show [1..1000000]
index :: String -> Int -> Char
index s i = s !! (i - 1)
prod :: Int
prod
= product
. map (Char.digitToInt . index s)
$ [1,10,100,1000,10000,100000,1000000]
main :: IO ()
main = do
putStrLn . show $ prod
|
bgwines/project-euler
|
src/solved/problem40.hs
|
bsd-3-clause
| 290
| 2
| 10
| 63
| 146
| 80
| 66
| 13
| 1
|
{-
HashMap representation of Di-Graph where vertices are keys and collection of di-adjecent edges
is stored as a value. Efficient for traversing algorithms.
-}
module Instances.DiGraph.DiEdgesByVertexMap where
import Data.Hashable
import PolyGraph.Common
import PolyGraph.ReadOnly
import PolyGraph.ReadOnly.Graph
import PolyGraph.ReadOnly.DiGraph
import PolyGraph.Buildable
import PolyGraph.Adjustable
import PolyGraph.Common.BuildableCollection
import qualified Data.HashMap.Strict as HM
import qualified Data.Foldable as F
import Data.List ((\\))
type DiEdgeListByVertexMap v e = DiEdgesByVertexMap v e []
newtype DiEdgesByVertexMap v e t = DiEdgesByVertexMap { getHashMap :: HM.HashMap v (t e) } deriving (Show, Read)
------------------------------------------------------------------------------------------
-- HashMap is naturally a di-graph with [] being the Foldable for edges/vertices --
------------------------------------------------------------------------------------------
instance forall v e te. (Eq v, Hashable v, DiEdgeSemantics e v, Traversable te) =>
(GraphDataSet (DiEdgesByVertexMap v e te) v e []) where
isolatedVertices g =
let suspects = HM.keys . HM.filter (F.null) . getHashMap $ g
allToVertices = map(second . resolveDiEdge) . edges $ g
in suspects \\ allToVertices
edges = concat . map (F.toList) . HM.elems . getHashMap
instance forall v e te. (Eq v, Hashable v, Traversable te, DiEdgeSemantics e v, BuildableCollection (te e) e) =>
(DiAdjacencyIndex (DiEdgesByVertexMap v e te) v e te) where
cEdgesOf g v = HM.lookupDefault emptyBuildableCollection v (getHashMap g)
instance forall v e te. (Eq v, Hashable v, Traversable te, DiEdgeSemantics e v, BuildableCollection (te e) e) =>
(DiGraph (DiEdgesByVertexMap v e te) v e [])
instance forall v e te. (Eq v, Hashable v, Traversable te, DiEdgeSemantics e v, BuildableCollection (te e) e) =>
(BuildableGraphDataSet(DiEdgesByVertexMap v e te) v e []) where
empty = DiEdgesByVertexMap HM.empty
g +@ v = DiEdgesByVertexMap . (HM.insertWith (\new old -> old) v emptyBuildableCollection) . getHashMap $ g
g +~ e =
let OPair (v1,v2) = resolveDiEdge e
in DiEdgesByVertexMap .
(HM.insertWith (\new old -> old) v2 emptyBuildableCollection) .
(HM.insertWith (\new old -> addBuildableElement e old) v1 (singletonBuildableCollection e)) .
getHashMap $ g
union g1 g2 =
let mergeF :: te e -> te e -> te e
mergeF edges1 edges2 = unionBuildableCollections edges1 edges2
in DiEdgesByVertexMap $ HM.unionWith mergeF (getHashMap g1) (getHashMap g2)
-- this will be a bit slow but not too bad
instance forall v e te. (Eq v, Hashable v, Eq e, Traversable te, DiEdgeSemantics e v, AdjustableCollection (te e) e) =>
(AdjustableGraphDataSet(DiEdgesByVertexMap v e te) v e []) where
g \@ f =
let verticesTrimmed = DiEdgesByVertexMap . (HM.filterWithKey (\v _ -> f v)) . getHashMap $ g
edgeFilter :: e -> Bool
edgeFilter e =
let OPair (v1,v2) = resolveDiEdge e
in (f v1) && (f v2)
in DiEdgesByVertexMap . HM.map (filterBuildableCollection edgeFilter) . getHashMap $ verticesTrimmed
--map :: (v1 -> v2) -> HashMap k v1 -> HashMap k v2
filterEdges strict g f =
let edgesTrimmed = DiEdgesByVertexMap . HM.map (filterBuildableCollection f) . getHashMap $ g
in if strict
then DiEdgesByVertexMap . HM.filter (not . F.null) . getHashMap $ edgesTrimmed
else edgesTrimmed
|
rpeszek/GraphPlay
|
src/Instances/DiGraph/DiEdgesByVertexMap.hs
|
bsd-3-clause
| 3,897
| 17
| 18
| 1,058
| 1,041
| 557
| 484
| -1
| -1
|
import Test.Network.AuthorizeNet.Api (authorizeNetTests)
import Test.Tasty
main :: IO ()
main = defaultMain authorizeNetTests
|
MichaelBurge/haskell-authorize-net
|
test/Spec.hs
|
bsd-3-clause
| 128
| 0
| 6
| 15
| 36
| 20
| 16
| 4
| 1
|
module CLaSH.Desugar.Types
( DesugarState(..)
, DesugarSession
, DesugarStep
, dsDesugared
, dsBindings
, emptyDesugarState
)
where
-- External Modules
import Control.Monad.State.Strict (StateT)
import qualified Data.Label
import Data.Map (Map,empty)
import Language.KURE (RewriteM)
-- GHC API
import qualified CoreSyn
-- Internal Modules
import CLaSH.Util.Core.Types (TransformSession, CoreContext)
data DesugarState = DesugarState
{ _dsDesugared :: Map CoreSyn.CoreBndr CoreSyn.CoreExpr
, _dsBindings :: Map CoreSyn.CoreBndr CoreSyn.CoreExpr
}
emptyDesugarState ::
Map CoreSyn.CoreBndr CoreSyn.CoreExpr
-> DesugarState
emptyDesugarState bindings = DesugarState empty bindings
Data.Label.mkLabels [''DesugarState]
type DesugarSession = TransformSession (StateT DesugarState IO)
type DesugarStep = [CoreContext] -> CoreSyn.CoreExpr -> RewriteM DesugarSession [CoreContext] CoreSyn.CoreExpr
|
christiaanb/clash-tryout
|
src/CLaSH/Desugar/Types.hs
|
bsd-3-clause
| 937
| 0
| 10
| 141
| 226
| 132
| 94
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
module Main
where
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.STM
import Control.Concurrent.STM.TVar
import Control.Monad.Trans (liftIO)
import Data.Time
import Network.HTTP.Types (status200)
import Network.HTTP.Types.Header (hContentType)
import Network.Wai
import Network.Wai.Handler.Warp
import System.Environment (getArgs)
import System.Process.Monitor
main = do
args <- getArgs
let port = (read $ head args) :: Int
let cmd = drop 1 args
let intervals = []
putStrLn $ "Monitoring: " ++ show cmd
comm <- startMonitor cmd intervals
putStrLn $ "Monitor server running on port " ++ show port
run port (app comm)
app
:: TVar Comm
-> Application
app comm req resp = do
case pathInfo req of
("stop":_) -> do
liftIO $ terminateWorker comm
liftIO $ putStrLn "Monitoring completed."
threadDelay 500000 -- 500ms delay
resp stopR
_ -> resp defaultR
stopR
:: Response
stopR =
responseLBS
status200
[(hContentType, "text/plain")]
"Stopped"
defaultR
:: Response
defaultR =
responseLBS
status200
[(hContentType, "text/plain")]
""
startMonitor
:: [String]
-> [Interval]
-> IO (TVar Comm)
startMonitor args intervals = do
putStrLn "Monitoring beginning..."
time <- getCurrentTime
comm <- liftIO $ atomically $ newTVar $ mkComm time
forkIO $ doWork args comm intervals
return comm
doWork
:: [String]
-> TVar Comm
-> [Interval]
-> IO ()
doWork (x:xs) comm intervals = do
let worker = Executable x xs
job = mkJob worker
launchWorker job comm intervals
|
stormont/vg-process-monitor
|
WarpMonitor.hs
|
bsd-3-clause
| 1,695
| 38
| 10
| 410
| 462
| 260
| 202
| 66
| 2
|
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import Network.LambdaBridge.Bridge
import Network.LambdaBridge.SLIP
import Network.LambdaBridge.CRC
import Network.LambdaBridge.Bus hiding (debug)
import Network.LambdaBridge.Logging
import Network.LambdaBridge.Board hiding (debug)
import qualified Data.ByteString as BS
import Control.Concurrent
import Control.Monad
import Data.Monoid
import Data.String
import Data.Char
import System.IO
import Data.Time.Clock
import System.Random
debug = debugM "lambda-bridge.main"
io b = do
forkIO $ forever $ do
bs <- fromBridge b
print bs
let loop 1000000 = return ()
loop n = do
toBridge b $ fromString ("packet: " ++ show n)
loop (n+1)
loop 0
simBoard :: IO Board
simBoard = do
v1 <- newEmptyMVar
v2 <- newEmptyMVar
brd0 <- stateMachineToBus rxInitialState $ rxStateMachine v1
brd2 <- stateMachineToBus txInitialState $ txStateMachine v2
forkIO $ forever $ do
v <- takeMVar v1
debug $ "got " ++ show v
putMVar v2 (v)
debug $ "sent " ++ show v
-- forkIO $ forever $ do
-- sequence [ putMVar v2 n | n <- [100..200]]
let brd = virtualBus
[ (0, brd0)
, (2, brd2)
]
return brd
test_baud rate = do
-- our backbone, level 0
(lhs0,rhs0) <- connection
lhs1 <- baud rate (serialize lhs0)
rhs1 <- baud rate (serialize rhs0)
echo id rhs1 -- cap the far end
tm0 <- getCurrentTime
count <- newMVar 0
forkIO $ forever $ do
toBridge lhs1 $ BS.pack [33..100]
let pp n | isAscii n || n == '\n' = [n]
| otherwise = "."
forever $ do
bs <- fromBridge lhs1
n <- takeMVar count
let n' = n + BS.length bs
putMVar count n'
tm1 <- getCurrentTime
let diff :: Float = realToFrac $ tm1 `diffUTCTime` tm0
if (n `mod` 1000 == 0) then
putStrLn $ show n' ++ " bytes in " ++ show diff ++ " seconds, rate = "
++ show (floor (1 / (diff / fromIntegral n')) )
else return ()
main2 "115200" = test_baud 115200
main2 "9600" = test_baud 9600
main = do
setStdGen (mkStdGen 1000)
-- init_logging
hSetBuffering stdout LineBuffering
hSetBuffering stdout LineBuffering
sim_brd <- simBoard
-- our backbone, level 0
(lhs0,rhs0) <- connection
-- introduce delays
let rate = 9600
lhs1 <- baud rate (serialize lhs0)
rhs1 <- baud rate (serialize rhs0)
-- introduce errors
lhs2 <- noise 0.0001 (serialize lhs1)
; rhs2 <- noise 0.0001 (serialize rhs1)
-- level 1 simulator stack
lhs3 <- slipProtocol lhs2 ; rhs3 <- slipProtocol rhs2
-- level 2
lhs4 <- crc16Protocol lhs3 ; rhs4 <- crc16Protocol rhs3
-- level 3
lhs_brd <- bridgeToBus 0.1 lhs4
; interpBus rhs4 sim_brd
-- with the bridge set up, we can do testing
p0 <- busWritePort lhs_brd 0
p2 <- busReadPort lhs_brd 2
let text :: [String]
text = [ show n ++ " + " ++ show n ++ " = " ++ show (n+n) ++ "\n"
| n <- [0..100]
]
forkIO $ do
sequence_ [ writePort p0 $ BS.pack $ map (fromIntegral . ord) txt
| txt <- text
]
let pp n | isAscii n = [n] -- ['<',n,'>']
| otherwise = "."
forever $ do
bs <- readPort p2
putStr $ concatMap pp $ map (chr . fromIntegral) $ BS.unpack $ bs
hFlush stdout
return ()
|
ku-fpg/lambda-bridge
|
tests/rs232/Main.hs
|
bsd-3-clause
| 4,113
| 0
| 19
| 1,690
| 1,161
| 555
| 606
| 96
| 2
|
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -Wall #-}
-- {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- TEMP
-- {-# OPTIONS_GHC -fno-warn-unused-binds #-} -- TEMP
----------------------------------------------------------------------
-- |
-- Module : ReificationRules.BuildDictionary
-- Copyright : (c) 2016 Conal Elliott
-- License : BSD3
--
-- Maintainer : conal@conal.net
-- Stability : experimental
--
-- Adaptation of HERMIT's buildDictionaryT
----------------------------------------------------------------------
module ReificationRules.BuildDictionary (buildDictionary) where
import Control.Monad (guard)
import Data.Char (isSpace)
import System.IO.Unsafe (unsafePerformIO)
import GhcPlugins
import Control.Arrow (second)
import TcHsSyn (emptyZonkEnv,zonkEvBinds)
import TcRnMonad (getCtLocM)
import TcRnTypes (cc_ev)
import TcSMonad (runTcS)
import TcEvidence (evBindMapBinds)
import TcErrors(warnAllUnsolved)
import DsMonad
import DsBinds
import TcSimplify
import TcRnTypes
import ErrUtils (pprErrMsgBagWithLoc)
import Encoding (zEncodeString)
import Unique (mkUniqueGrimily)
import HERMIT.GHC.Typechecker (initTcFromModGuts)
runTcMUnsafe :: HscEnv -> DynFlags -> ModGuts -> TcM a -> a
runTcMUnsafe env dflags guts m = unsafePerformIO $ do
-- What is the effect of HsSrcFile (should we be using something else?)
-- What should the boolean flag be set to?
(msgs, mr) <- initTcFromModGuts env guts HsSrcFile False m
let showMsgs (warns, errs) = showSDoc dflags $ vcat
$ text "Errors:" : pprErrMsgBagWithLoc errs
++ text "Warnings:" : pprErrMsgBagWithLoc warns
maybe (fail $ showMsgs msgs) return mr
-- TODO: Try initTcForLookup or initTcInteractive in place of initTcFromModGuts.
-- If successful, drop dflags and guts arguments.
runDsMUnsafe :: HscEnv -> DynFlags -> ModGuts -> DsM a -> a
runDsMUnsafe env dflags guts = runTcMUnsafe env dflags guts . initDsTc
-- | Build a dictionary for the given
buildDictionary' :: HscEnv -> DynFlags -> ModGuts -> Id -> (Id, [CoreBind])
buildDictionary' env dflags guts evar =
let (i, bs) = runTcMUnsafe env dflags guts $ do
loc <- getCtLocM (GivenOrigin UnkSkol) Nothing
let predTy = varType evar
nonC = mkNonCanonical $
CtWanted { ctev_pred = predTy, ctev_dest = EvVarDest evar
, ctev_loc = loc }
wCs = mkSimpleWC [cc_ev nonC]
-- TODO: Make sure solveWanteds is the right function to call.
(_wCs', bnds0) <- second evBindMapBinds <$> runTcS (solveWanteds wCs)
-- Use the newly exported zonkEvBinds. <https://phabricator.haskell.org/D2088>
(_env',bnds) <- zonkEvBinds emptyZonkEnv bnds0
-- pprTrace "buildDictionary' _wCs'" (ppr _wCs') (return ())
-- changed next line from reportAllUnsolved, which panics. revisit and fix!
warnAllUnsolved _wCs'
return (evar, bnds)
in
(i, runDsMUnsafe env dflags guts (dsEvBinds bs))
-- TODO: Richard Eisenberg: "use TcMType.newWanted to make your CtWanted. As it
-- stands, if predTy is an equality constraint, your CtWanted will be
-- ill-formed, as all equality constraints should have HoleDests, not
-- EvVarDests. Using TcMType.newWanted will simplify and improve your code."
-- TODO: Why return the given evar?
-- TODO: Try to combine the two runTcMUnsafe calls.
buildDictionary :: HscEnv -> DynFlags -> ModGuts -> InScopeEnv -> Type -> Maybe CoreExpr
buildDictionary env dflags guts inScope ty =
do
guard (notNull bnds && isEmptyVarSet freeIds)
-- pprTrace "buildDictionary" (ppr ty <+> text "-->" <+> ppr dict) (return ())
return dict
where
name = "$d" ++ zEncodeString (filter (not . isSpace) (showPpr dflags ty))
binder = localId inScope name ty
(i,bnds) = buildDictionary' env dflags guts binder
dict =
case bnds of
-- The common case that we would have gotten a single non-recursive let
[NonRec v e] | i == v -> e
_ -> mkCoreLets bnds (varToCoreExpr i)
-- Sometimes buildDictionary' constructs bogus dictionaries with free
-- identifiers. Hence check that freeIds is empty. Allow for free *type*
-- variables, however, since there may be some in the given type as
-- parameters. Alternatively, check that there are no free variables (val or
-- type) in the resulting dictionary that were not in the original type.
freeIds = filterVarSet isId (exprFreeVars dict)
-- | Make a unique identifier for a specified type, using a provided name.
localId :: InScopeEnv -> String -> Type -> Id
localId (inScopeSet,_) str ty =
uniqAway inScopeSet (mkLocalId (stringToName str) ty)
stringToName :: String -> Name
stringToName str =
mkSystemVarName (mkUniqueGrimily (abs (fromIntegral (hashString str))))
(mkFastString str)
-- When mkUniqueGrimily's argument is negative, we see something like
-- "Exception: Prelude.chr: bad argument: (-52)". Hence the abs.
|
conal/reification-rules
|
src/ReificationRules/BuildDictionary.hs
|
bsd-3-clause
| 5,128
| 0
| 18
| 1,157
| 925
| 498
| 427
| -1
| -1
|
-----------------------------------------------------------------------------
--
-- Module : Modules.Compatibility
-- Copyright : (c) 2011 Lars Corbijn
-- License : BSD-style (see the file /LICENSE)
--
-- Maintainer :
-- Stability :
-- Portability :
--
-- | A small module adding some extra modules for compatibility with the
-- older layout of OpenGLRaw.
-----------------------------------------------------------------------------
module Modules.Compatibility (
addCompatibilityModules,
) where
-----------------------------------------------------------------------------
import Control.Monad
import Data.Monoid
import qualified Data.Set as S
import Language.Haskell.Exts.Syntax
import Language.OpenGLRaw.Base
import Spec
import Modules.Builder
import Modules.ModuleNames
-----------------------------------------------------------------------------
addCompatibilityModules :: Builder ()
addCompatibilityModules = do
addOldCoreProfile 3 1
addOldCoreProfile 3 2
addOldCoreTypes
addARBCompatibility
addOldCoreProfile :: Int -> Int -> Builder ()
addOldCoreProfile ma mi =
let modName = ModuleName $ "Graphics.Rendering.OpenGL.Raw.Core" ++ show ma ++ show mi
warning = DeprText "\"The core modules are moved to Graphics.Rendering.OpenGL.Raw.Core.CoreXY\""
in do cp <- askProfileModule ma mi DefaultProfile
addModuleWithWarning modName
Compatibility warning $ tellReExportModule cp
addOldCoreTypes :: Builder ()
addOldCoreTypes = do
let modName = ModuleName "Graphics.Rendering.OpenGL.Raw.Core31.Types"
warning = DeprText "\"The OpenGL types are moved to Graphics.Rendering.OpenGL.Raw.Types .\""
typesModule <- askTypesModule
addModuleWithWarning modName
Compatibility warning $ tellReExportModule typesModule
-- | Creates the ARB.Compatibility module.
addARBCompatibility :: Builder ()
addARBCompatibility = do
let modFilter1 cat = case cat of
(Version _ _ (ProfileName "compatibility")) -> True
_ -> False
cats <- asksCategories $ filter modFilter1
-- The basis for the ARB.Compatibility module are those enums that are
-- part of a OpenGL version with compatibility profile but not in the
-- core profile of the same version.
(enums, funcs) <- fmap mconcat $ forM cats $ \cat -> do
let coreCat = case cat of
(Version ma mi _) -> Version ma mi DefaultProfile
_ -> error "addARBCompatibility: Impossible"
catEnums <- asksLocationMap $ categoryValues cat
coreEnums <- asksLocationMap $ categoryValues coreCat
catFuncs <- asksLocationMap $ categoryValues cat
coreFuncs <- asksLocationMap $ categoryValues coreCat
let enums' :: S.Set EnumName
enums' = catEnums `S.difference` coreEnums
funcs' :: S.Set FuncName
funcs' = catFuncs `S.difference` coreFuncs
return (enums', funcs')
let modName = ModuleName "Graphics.Rendering.OpenGL.Raw.ARB.Compatibility"
warning = DeprText "\"The ARB.Compatibility is combined with the profiles.\""
mkReExport sv = do
mloc <- getDefineLoc sv
case mloc of
-- This module should be defined after the core modules have
-- been defined, and thus are all EnumNames/FuncNames already
-- defined.
Nothing -> error $ "addARBCompatibility: Yet undefined enum" ++ show sv
Just cat -> do
n <- unwrapNameM sv
rmodName <- askCategoryModule cat
return $ ReExport (n, rmodName) $ toGLName sv
addModuleWithWarning modName Compatibility warning $ do
mapM_ (mkReExport >=> tellPart) $ S.toList enums
mapM_ (mkReExport >=> tellPart) $ S.toList funcs
-- Somehow the forgot to mention that ARB_imaging is part of the
-- compatibility profile of OpenGL.
askCategoryModule (Extension (Vendor "ARB") "imaging" (ProfileName "compatibility"))
>>= tellReExportModule
-----------------------------------------------------------------------------
|
phaazon/OpenGLRawgen
|
src/Modules/Compatibility.hs
|
bsd-3-clause
| 4,200
| 0
| 20
| 1,000
| 745
| 370
| 375
| 64
| 4
|
{-# LANGUAGE RankNTypes #-}
-- | Block verification, application, and rollback: processing of SSC-related payload.
module Pos.DB.Ssc.Logic.VAR
(
sscVerifyBlocks
, sscApplyBlocks
, sscVerifyAndApplyBlocks
, sscRollbackBlocks
) where
import Control.Lens ((.=), _Wrapped)
import Control.Monad.Except (MonadError (throwError), runExceptT)
import Control.Monad.Morph (hoist)
import qualified Crypto.Random as Rand
import qualified Data.HashMap.Strict as HM
import Formatting (build, int, sformat, (%))
import Serokell.Util (listJson)
import Universum
import Pos.Chain.Block (ComponentBlock (..), HeaderHash, headerHash)
import Pos.Chain.Genesis as Genesis (Config, configBlockVersionData)
import Pos.Chain.Lrc (RichmenStakes)
import Pos.Chain.Ssc (HasSscConfiguration, MonadSscMem,
MultiRichmenStakes, PureToss, SscBlock,
SscGlobalState (..), SscGlobalUpdate, SscPayload (..),
SscVerifyError (..), applyGenesisBlock, askSscMem,
rollbackSsc, runPureTossWithLogger, sscGlobal,
sscIsCriticalVerifyError, sscRunGlobalUpdate,
supplyPureTossEnv, verifyAndApplySscPayload)
import Pos.Chain.Update (BlockVersionData)
import Pos.Core (SlotCount, epochIndexL, epochOrSlotG)
import Pos.Core.Chrono (NE, NewestFirst (..), OldestFirst (..))
import Pos.Core.Exception (assertionFailed)
import Pos.Core.Reporting (MonadReporting, reportError)
import Pos.DB (MonadDBRead, MonadGState, SomeBatchOp (..),
gsAdoptedBVData)
import Pos.DB.Lrc (HasLrcContext, getSscRichmen)
import qualified Pos.DB.Ssc.GState as DB
import Pos.Util.AssertMode (inAssertMode)
import Pos.Util.Lens (_neHead, _neLast)
import Pos.Util.Wlog (WithLogger, logDebug)
----------------------------------------------------------------------------
-- Modes
----------------------------------------------------------------------------
type SscVerifyMode m =
( MonadState SscGlobalState m
, WithLogger m
, MonadError SscVerifyError m
, Rand.MonadRandom m
)
-- 'MonadIO' is needed only for 'TVar' (@gromak hopes).
-- 'MonadRandom' is needed for crypto (@neongreen hopes).
type SscGlobalVerifyMode ctx m =
(HasSscConfiguration,
MonadSscMem ctx m,
MonadReader ctx m, HasLrcContext ctx,
MonadDBRead m, MonadGState m, WithLogger m, MonadReporting m,
MonadIO m, Rand.MonadRandom m)
type SscGlobalApplyMode ctx m = SscGlobalVerifyMode ctx m
----------------------------------------------------------------------------
-- Verify
----------------------------------------------------------------------------
-- | Verify sequence of blocks and return global state which
-- corresponds to application of given blocks. If blocks are invalid,
-- this function will return 'Left' with appropriate error.
-- All blocks must be from the same epoch.
sscVerifyBlocks
:: SscGlobalVerifyMode ctx m
=> Genesis.Config
-> OldestFirst NE SscBlock
-> m (Either SscVerifyError SscGlobalState)
sscVerifyBlocks genesisConfig blocks = do
let epoch = blocks ^. _Wrapped . _neHead . epochIndexL
let lastEpoch = blocks ^. _Wrapped . _neLast . epochIndexL
let differentEpochsMsg =
sformat
("sscVerifyBlocks: different epochs ("%int%", "%int%")")
epoch
lastEpoch
inAssertMode $ unless (epoch == lastEpoch) $
assertionFailed differentEpochsMsg
richmenSet <- getSscRichmen (configBlockVersionData genesisConfig)
"sscVerifyBlocks"
epoch
bvd <- gsAdoptedBVData
globalVar <- sscGlobal <$> askSscMem
gs <- readTVarIO globalVar
res <-
runExceptT
(execStateT (sscVerifyAndApplyBlocks genesisConfig richmenSet bvd blocks) gs)
case res of
Left e
| sscIsCriticalVerifyError e ->
reportError $ sformat ("Critical error in ssc: "%build) e
_ -> pass
return res
----------------------------------------------------------------------------
-- Apply
----------------------------------------------------------------------------
-- | Apply sequence of definitely valid blocks. Global state which is
-- result of application of these blocks can be optionally passed as
-- argument (it can be calculated in advance using 'sscVerifyBlocks').
sscApplyBlocks
:: SscGlobalApplyMode ctx m
=> Genesis.Config
-> OldestFirst NE SscBlock
-> Maybe SscGlobalState
-> m [SomeBatchOp]
sscApplyBlocks genesisConfig blocks (Just newState) = do
inAssertMode $ do
let hashes = map headerHash blocks
expectedState <- sscVerifyValidBlocks genesisConfig blocks
if | newState == expectedState -> pass
| otherwise -> onUnexpectedVerify hashes
sscApplyBlocksFinish newState
sscApplyBlocks genesisConfig blocks Nothing =
sscApplyBlocksFinish =<< sscVerifyValidBlocks genesisConfig blocks
sscApplyBlocksFinish
:: (SscGlobalApplyMode ctx m)
=> SscGlobalState -> m [SomeBatchOp]
sscApplyBlocksFinish gs = do
sscRunGlobalUpdate (put gs)
inAssertMode $
logDebug $
sformat ("After applying blocks SSC global state is:\n"%build) gs
pure $ sscGlobalStateToBatch gs
sscVerifyValidBlocks
:: SscGlobalApplyMode ctx m
=> Genesis.Config
-> OldestFirst NE SscBlock
-> m SscGlobalState
sscVerifyValidBlocks genesisConfig blocks =
sscVerifyBlocks genesisConfig blocks >>= \case
Left e -> onVerifyFailedInApply hashes e
Right newState -> return newState
where
hashes = map headerHash blocks
onUnexpectedVerify
:: forall m a.
(WithLogger m, MonadThrow m)
=> OldestFirst NE HeaderHash -> m a
onUnexpectedVerify hashes = assertionFailed msg
where
fmt =
"sscApplyBlocks: verfication of blocks "%listJson%
" returned unexpected state"
msg = sformat fmt hashes
onVerifyFailedInApply
:: forall m a.
(WithLogger m, MonadThrow m)
=> OldestFirst NE HeaderHash -> SscVerifyError -> m a
onVerifyFailedInApply hashes e = assertionFailed msg
where
fmt =
"sscApplyBlocks: verification of blocks "%listJson%" failed: "%build
msg = sformat fmt hashes e
----------------------------------------------------------------------------
-- Verify and apply
----------------------------------------------------------------------------
-- | Verify SSC-related part of given blocks with respect to current GState
-- and apply them on success. Blocks must be from the same epoch.
sscVerifyAndApplyBlocks
:: SscVerifyMode m
=> Genesis.Config
-> RichmenStakes
-> BlockVersionData
-> OldestFirst NE SscBlock
-> m ()
sscVerifyAndApplyBlocks genesisConfig richmenStake bvd blocks =
verifyAndApplyMultiRichmen genesisConfig False (richmenData, bvd) blocks
where
epoch = blocks ^. _Wrapped . _neHead . epochIndexL
richmenData = HM.fromList [(epoch, richmenStake)]
verifyAndApplyMultiRichmen
:: SscVerifyMode m
=> Genesis.Config
-> Bool
-> (MultiRichmenStakes, BlockVersionData)
-> OldestFirst NE SscBlock
-> m ()
verifyAndApplyMultiRichmen genesisConfig onlyCerts env =
tossToVerifier . hoist (supplyPureTossEnv env) .
mapM_ verifyAndApplyDo
where
verifyAndApplyDo (ComponentBlockGenesis header) = applyGenesisBlock $ header ^. epochIndexL
verifyAndApplyDo (ComponentBlockMain header payload) =
verifyAndApplySscPayload genesisConfig (Right header) $
filterPayload payload
filterPayload payload
| onlyCerts = leaveOnlyCerts payload
| otherwise = payload
leaveOnlyCerts (CommitmentsPayload _ certs) =
CommitmentsPayload mempty certs
leaveOnlyCerts (OpeningsPayload _ certs) = OpeningsPayload mempty certs
leaveOnlyCerts (SharesPayload _ certs) = SharesPayload mempty certs
leaveOnlyCerts c@(CertificatesPayload _) = c
----------------------------------------------------------------------------
-- Rollback
----------------------------------------------------------------------------
-- | Rollback application of given sequence of blocks. Bad things can
-- happen if these blocks haven't been applied before.
sscRollbackBlocks
:: SscGlobalApplyMode ctx m
=> SlotCount -> NewestFirst NE SscBlock -> m [SomeBatchOp]
sscRollbackBlocks epochSlots blocks = sscRunGlobalUpdate $ do
sscRollbackU epochSlots blocks
sscGlobalStateToBatch <$> get
sscRollbackU :: SlotCount -> NewestFirst NE SscBlock -> SscGlobalUpdate ()
sscRollbackU epochSlots blocks = tossToUpdate $ rollbackSsc epochSlots oldestEOS payloads
where
oldestEOS = blocks ^. _Wrapped . _neLast . epochOrSlotG
payloads = NewestFirst $ mapMaybe extractPayload $ toList blocks
extractPayload (ComponentBlockMain _ a) = Just a
extractPayload (ComponentBlockGenesis _) = Nothing
----------------------------------------------------------------------------
-- Utilities
----------------------------------------------------------------------------
tossToUpdate :: PureToss a -> SscGlobalUpdate a
tossToUpdate action = do
oldState <- use identity
(res, newState) <- runPureTossWithLogger oldState action
(identity .= newState) $> res
tossToVerifier
:: SscVerifyMode m
=> ExceptT SscVerifyError PureToss a
-> m a
tossToVerifier action = do
oldState <- use identity
(resOrErr, newState) <-
runPureTossWithLogger oldState $ runExceptT action
case resOrErr of
Left e -> throwError e
Right res -> (identity .= newState) $> res
-- | Dump global state to DB.
sscGlobalStateToBatch :: SscGlobalState -> [SomeBatchOp]
sscGlobalStateToBatch = one . SomeBatchOp . DB.sscGlobalStateToBatch
|
input-output-hk/pos-haskell-prototype
|
db/src/Pos/DB/Ssc/Logic/VAR.hs
|
mit
| 10,008
| 0
| 15
| 2,169
| 2,040
| 1,078
| 962
| -1
| -1
|
{-# LANGUAGE GADTs #-}
module TypeChecking.Context where
import Control.Monad
import Syntax.Term
data Ctx s f b a where
Nil :: Ctx s f b b
Snoc :: Ctx s f b a -> s -> f a -> Ctx s f b (Scoped a)
(+++) :: Ctx s f a b -> Ctx s f b c -> Ctx s f a c
ctx +++ Nil = ctx
ctx +++ Snoc ctx' s t = Snoc (ctx +++ ctx') s t
lengthCtx :: Ctx s f b a -> Int
lengthCtx Nil = 0
lengthCtx (Snoc ctx _ _) = lengthCtx ctx + 1
lookupCtx :: (Monad g, Functor f, Eq s) => s -> Ctx s f b a -> Maybe (g a, f a)
lookupCtx _ Nil = Nothing
lookupCtx b (Snoc ctx s t) = if s == b
then Just (return Bound, fmap Free t)
else fmap (\(te, ty) -> (liftM Free te, fmap Free ty)) (lookupCtx b ctx)
ctxToVars :: Ctx s f b a -> [a]
ctxToVars = reverse . go
where
go :: Ctx s f b a -> [a]
go Nil = []
go (Snoc ctx s _) = Bound : map Free (go ctx)
close :: Functor f => Ctx c g b a -> f (Either c a) -> f (Either c b)
close Nil t = t
close (Snoc ctx s _) t = close ctx $ fmap (\v -> case v of
Left c -> Left c
Right Bound -> Left s
Right (Free a) -> Right a) t
liftBase :: Ctx s f b a -> b -> a
liftBase Nil = id
liftBase (Snoc ctx _ _) = Free . liftBase ctx
toBase :: Ctx s f b a -> a -> Maybe b
toBase Nil b = Just b
toBase Snoc{} Bound = Nothing
toBase (Snoc ctx _ _) (Free a) = toBase ctx a
ctxVars :: Ctx s f b a -> [s]
ctxVars = reverse . go
where
go :: Ctx s f b a -> [s]
go Nil = []
go (Snoc ctx v _) = v : go ctx
abstractTerm :: Ctx s f b a -> Term p a -> Term p b
abstractTerm Nil term = term
abstractTerm (Snoc ctx v _) term = abstractTerm ctx (Lambda term)
|
bitemyapp/hoq
|
src/TypeChecking/Context.hs
|
gpl-2.0
| 1,625
| 0
| 14
| 484
| 921
| 459
| 462
| 44
| 3
|
{-# LANGUAGE GeneralizedNewtypeDeriving, LambdaCase, TypeFamilies, ViewPatterns, FlexibleContexts #-}
module Commands.Plugins.Spiros.Template.Types where
-- import Commands.Plugins.Spiros.Extra (insertByClipboard)
import Commands.Plugins.Spiros.Extra.Types
import Commands.Backends.Workflow as W
import Data.Monoid.Split
-- import qualified Data.List as List
import Control.Monad (replicateM_)
import GHC.Exts (IsString (..)) -- , IsList (..))
import Prelude.Spiros hiding (rstrip,lstrip)
import Prelude()
{- | a simple monoid that can hold the metadata of a cursor position. you can then can set the position of the cursor after inserting a template.
can be used with @-XQuasiQuotes@ ('qc' supports interpolation).
see "Commands.Plugins.Spiros.Template.haddockTemplate" for example.
TODO...
Template ~ [Either (First ()) String)]
(String, First (), String) ~ (String, String)
:: [Either (First ()) String] -> (String, String)
'Split' keeps the rightmost divider:
>>> import Data.Monoid.Split
>>> M "a" <> ("b" :| "c") <> ("d" :| "e")
"abcd" :| "e"
-}
-- data Template
-- = TemplateCursor
-- | TemplateText String
-- | TemplateList [Template]
-- deriving (Show,Read,Eq,Ord,Generic,Data,NFData)
newtype Template = Template { getTemplate :: Split String }
deriving (Show,Read,Eq,Generic,Data,Semigroup,Monoid) -- TODO Hashable, Ord, NFData
{- | when constructed with 'mappend', a @Template@ is always flat (see 'flattenTemplate').
@
'mempty' = 'TemplateList' []
@
-}
-- instance Monoid Template where
-- mempty = TemplateList []
-- mappend x y = TemplateList (mappend (toTemplateList x) (toTemplateList y))
{-|
@
'fromString' ~ 'M'
@
-}
instance IsString Template where
fromString = M > Template
{-|
@
'fromList' = 'fromTemplateList'
'toList' = 'toTemplateList'
@
-}
-- instance IsList Template where
-- type Item Template = Template
-- fromList = fromTemplateList
-- toList = toTemplateList
--
-- toTemplateList :: Template -> [Template]
-- toTemplateList = \case
-- TemplateList ts -> ts
-- t -> [t]
--
-- fromTemplateList :: [Template] -> Template
-- fromTemplateList = TemplateList
-- | @getTemplate > 'unsplit'@
fromTemplate :: Template -> String
fromTemplate = getTemplate > unsplit
-- ================================================================ --
{-| munges the template, making it 'insert'able.
strips one leading newline and one trailing newline.
increases readability of quasi-quotes, e.g.:
@
haddockTemplate_2 = ['qc'|
\{-| {'cursor'}
-}
|]
@
rather than:
@
haddockTemplate_3 = ['qc'|\{-| {'cursor'}
-}|]
@
becoming:
@
Template {getTemplate = "\n{-| " :| "\n\n-}\n"}
@
if you want that leading/trailing white space, just add "extra" whitespace, or use a string literal.
-}
mungeTemplate :: Template -> (String, String)
mungeTemplate template = (before, after)
where
before = (lstrip) beforeTemplate
after = (rstrip) afterTemplate
(beforeTemplate, afterTemplate) = splitTemplateByCursor template
rstrip = reverse.lstrip.reverse -- TODO case on nonempty, last, check, init
lstrip = \case
('\n':xs) -> xs
xs -> xs
{- | input should have zero or one 'TemplateCursor'(s). splits on the first, when multiple.
outputs should have zero 'TemplateCursor'(s).
-}
splitTemplateByCursor :: Template -> (String, String)
splitTemplateByCursor = getTemplate > \case
M x -> (x, "") -- no cursor
x :| y -> (x, y)
{- | @cursor ~ 'split'@
there is always zero @('Template' ('M' ...))@
or one @('Template' (... ':|' ...))@ cursor.
-}
cursor :: Template
cursor = Template split
-- ================================================================ --
-- workflow stuff
{- |
strips one leading newline and one trailing newline,
which increases the readability of quasiquotes.
-}
insertTemplate :: MonadWorkflow m => Template -> m ()
insertTemplate template = do
let (before, after) = mungeTemplate template
-- -- when inserted not by clipboard, it's
-- -- (a) harder to undo and
-- -- (b) triggers functions, like "import" opens the mini buffer
-- insertByClipboard before
-- insertByClipboard after
-- replicateM_ (length after) (W.press "<left>")
-- when inserted not by clipboard, it's
-- (a) harder to undo and
-- (b) triggers functions, like "import" opens the mini buffer
W.insert before
W.insert after
replicateM_ (length after) moveLeft
where
moveLeft = W.press "<left>"
|
sboosali/commands-spiros
|
config/Commands/Plugins/Spiros/Template/Types.hs
|
gpl-2.0
| 4,410
| 0
| 11
| 740
| 468
| 281
| 187
| 37
| 2
|
module Boolean.Eval where
-- $Id$
-- import Boolean.Data
import Boolean.Op
import Expression.Op
import Autolib.FiniteMap
import Autolib.Util.Wort
import Autolib.Set
import Autolib.Reporter
import Autolib.ToDoc
type Belegung v = FiniteMap v Bool
belegungen :: Ord v
=> Set v
-> [ Belegung v ]
belegungen vs = do
xs <- alle [ False, True ] $ cardinality vs
return $ listToFM $ zip ( setToList vs ) xs
eval :: Belegung Identifier -> Exp Bool -> Reporter Bool
eval b =
let look x = case lookupFM b x of
Just y -> return y
Nothing -> reject $ text "Boolean.Eval:" <+> toDoc x
in tfoldR look inter
|
Erdwolf/autotool-bonn
|
src/Boolean/Eval.hs
|
gpl-2.0
| 634
| 4
| 14
| 147
| 227
| 114
| 113
| 21
| 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.StorageGateway.DescribeTapes
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Returns a description of the specified Amazon Resource Name (ARN) of virtual
-- tapes. If a 'TapeARN' is not specified, returns a description of all virtual
-- tapes associated with the specified gateway.
--
-- <http://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DescribeTapes.html>
module Network.AWS.StorageGateway.DescribeTapes
(
-- * Request
DescribeTapes
-- ** Request constructor
, describeTapes
-- ** Request lenses
, dtGatewayARN
, dtLimit
, dtMarker
, dtTapeARNs
-- * Response
, DescribeTapesResponse
-- ** Response constructor
, describeTapesResponse
-- ** Response lenses
, dtrMarker
, dtrTapes
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.StorageGateway.Types
import qualified GHC.Exts
data DescribeTapes = DescribeTapes
{ _dtGatewayARN :: Text
, _dtLimit :: Maybe Nat
, _dtMarker :: Maybe Text
, _dtTapeARNs :: List "TapeARNs" Text
} deriving (Eq, Ord, Read, Show)
-- | 'DescribeTapes' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dtGatewayARN' @::@ 'Text'
--
-- * 'dtLimit' @::@ 'Maybe' 'Natural'
--
-- * 'dtMarker' @::@ 'Maybe' 'Text'
--
-- * 'dtTapeARNs' @::@ ['Text']
--
describeTapes :: Text -- ^ 'dtGatewayARN'
-> DescribeTapes
describeTapes p1 = DescribeTapes
{ _dtGatewayARN = p1
, _dtTapeARNs = mempty
, _dtMarker = Nothing
, _dtLimit = Nothing
}
dtGatewayARN :: Lens' DescribeTapes Text
dtGatewayARN = lens _dtGatewayARN (\s a -> s { _dtGatewayARN = a })
-- | Specifies that the number of virtual tapes described be limited to the
-- specified number.
--
-- Amazon Web Services may impose its own limit, if this field is not set.
dtLimit :: Lens' DescribeTapes (Maybe Natural)
dtLimit = lens _dtLimit (\s a -> s { _dtLimit = a }) . mapping _Nat
-- | A marker value, obtained in a previous call to 'DescribeTapes'. This marker
-- indicates which page of results to retrieve.
--
-- If not specified, the first page of results is retrieved.
dtMarker :: Lens' DescribeTapes (Maybe Text)
dtMarker = lens _dtMarker (\s a -> s { _dtMarker = a })
-- | Specifies one or more unique Amazon Resource Names (ARNs) that represent the
-- virtual tapes you want to describe. If this parameter is not specified, AWS
-- Storage Gateway returns a description of all virtual tapes associated with
-- the specified gateway.
dtTapeARNs :: Lens' DescribeTapes [Text]
dtTapeARNs = lens _dtTapeARNs (\s a -> s { _dtTapeARNs = a }) . _List
data DescribeTapesResponse = DescribeTapesResponse
{ _dtrMarker :: Maybe Text
, _dtrTapes :: List "Tapes" Tape
} deriving (Eq, Read, Show)
-- | 'DescribeTapesResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dtrMarker' @::@ 'Maybe' 'Text'
--
-- * 'dtrTapes' @::@ ['Tape']
--
describeTapesResponse :: DescribeTapesResponse
describeTapesResponse = DescribeTapesResponse
{ _dtrTapes = mempty
, _dtrMarker = Nothing
}
-- | An opaque string which can be used as part of a subsequent DescribeTapes call
-- to retrieve the next page of results.
--
-- If a response does not contain a marker, then there are no more results to
-- be retrieved.
dtrMarker :: Lens' DescribeTapesResponse (Maybe Text)
dtrMarker = lens _dtrMarker (\s a -> s { _dtrMarker = a })
-- | An array of virtual tape descriptions.
dtrTapes :: Lens' DescribeTapesResponse [Tape]
dtrTapes = lens _dtrTapes (\s a -> s { _dtrTapes = a }) . _List
instance ToPath DescribeTapes where
toPath = const "/"
instance ToQuery DescribeTapes where
toQuery = const mempty
instance ToHeaders DescribeTapes
instance ToJSON DescribeTapes where
toJSON DescribeTapes{..} = object
[ "GatewayARN" .= _dtGatewayARN
, "TapeARNs" .= _dtTapeARNs
, "Marker" .= _dtMarker
, "Limit" .= _dtLimit
]
instance AWSRequest DescribeTapes where
type Sv DescribeTapes = StorageGateway
type Rs DescribeTapes = DescribeTapesResponse
request = post "DescribeTapes"
response = jsonResponse
instance FromJSON DescribeTapesResponse where
parseJSON = withObject "DescribeTapesResponse" $ \o -> DescribeTapesResponse
<$> o .:? "Marker"
<*> o .:? "Tapes" .!= mempty
instance AWSPager DescribeTapes where
page rq rs
| stop (rs ^. dtrMarker) = Nothing
| otherwise = (\x -> rq & dtMarker ?~ x)
<$> (rs ^. dtrMarker)
|
kim/amazonka
|
amazonka-storagegateway/gen/Network/AWS/StorageGateway/DescribeTapes.hs
|
mpl-2.0
| 5,612
| 0
| 12
| 1,267
| 835
| 495
| 340
| 85
| 1
|
{- |
Module : Network.MPD.Commands.Query
Copyright : (c) Joachim Fasting 2012
License : MIT
Maintainer : Joachim Fasting <joachifm@fastmail.fm>
Stability : unstable
Portability : unportable
Query interface.
-}
module Network.MPD.Commands.Query (Query, (=?) ,(/=?), (%?), (~?), (/~?), qNot, qModSince, qFile, qBase, anything) where
import Network.MPD.Commands.Arg
import Network.MPD.Commands.Types
import Data.Time (UTCTime,formatTime,defaultTimeLocale)
-- | An interface for creating MPD queries.
--
-- For example, to match any song where the value of artist is \"Foo\", we
-- use:
--
-- > Artist =? "Foo"
--
-- We can also compose queries, thus narrowing the search. For example, to
-- match any song where the value of artist is \"Foo\" and the value of album
-- is \"Bar\", we use:
--
-- > Artist =? "Foo" <> Album =? "Bar"
data Query = Query [Match] | Filter Expr
deriving Show
-- A single query clause, comprising a metadata key and a desired value.
data Match = Match Metadata Value
instance Show Match where
show (Match meta query) = show meta ++ " \"" ++ toString query ++ "\""
showList xs _ = unwords $ fmap show xs
-- A general MPD 0.21 style filter.
data Expr = Exact Match
| ExactNot Match
| Contains Match
| Regex Match
| RegexNot Match
| File Path
| Base Path
| ModifiedSince UTCTime
| ExprNot Expr
| ExprAnd Expr Expr
| ExprEmpty
instance Show Expr where
show (Exact (Match meta query)) = "(" ++ show meta ++ " == " ++
"\\\"" ++ toString query ++ "\\\"" ++ ")"
show (ExactNot (Match meta query)) = "(" ++ show meta ++ " != " ++
"\\\"" ++ toString query ++ "\\\"" ++ ")"
show (Contains (Match meta query)) = "(" ++ show meta ++ " contains " ++
"\\\"" ++ toString query ++ "\\\"" ++ ")"
show (Regex (Match meta query)) = "(" ++ show meta ++ " =~ " ++
"\\\"" ++ toString query ++ "\\\"" ++ ")"
show (RegexNot (Match meta query)) = "(" ++ show meta ++ " !~ " ++
"\\\"" ++ toString query ++ "\\\"" ++ ")"
show (File file) = "(file == " ++ "\\\"" ++ toString file ++ "\\\"" ++ ")"
show (Base dir) = "(base " ++ "\\\"" ++ toString dir ++ "\\\"" ++ ")"
show (ModifiedSince time) = "(modified-since " ++ "\\\"" ++
formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%SZ" time ++
"\\\"" ++ ")"
show (ExprNot expr) = "(!" ++ show expr ++ ")"
show (ExprAnd e1 e2) = "(" ++ show e1 ++ " AND " ++ show e2 ++ ")"
show ExprEmpty = ""
toExpr :: [Match] -> Expr
toExpr [] = ExprEmpty
toExpr (m:[]) = Exact m
toExpr (m:ms) = ExprAnd (Exact m) (toExpr ms)
instance Monoid Query where
mempty = Query []
Query a `mappend` Query b = Query (a ++ b)
Query [] `mappend` Filter b = Filter b
Filter a `mappend` Query [] = Filter a
Query a `mappend` Filter b = Filter (ExprAnd (toExpr a) b)
Filter a `mappend` Query b = Filter (ExprAnd a (toExpr b))
Filter a `mappend` Filter b = Filter (a <> b)
instance Semigroup Query where
(<>) = mappend
instance Semigroup Expr where
ex1 <> ex2 = ExprAnd ex1 ex2
instance MPDArg Query where
prep (Query ms) = foldl (<++>) (Args [])
(fmap (\(Match m q) -> Args [show m] <++> q) ms)
prep (Filter expr) = Args ["\"" ++ show expr ++ "\""]
-- | An empty query. Matches anything.
anything :: Query
anything = mempty
-- | Create a query matching a tag with a value.
(=?) :: Metadata -> Value -> Query
m =? s = Query [Match m s]
-- | Create a query matching a tag with anything but a value.
--
-- Since MPD 0.21.
--
-- @since 0.9.3.0
(/=?) :: Metadata -> Value -> Query
m /=? s = Filter (ExactNot (Match m s))
-- | Create a query for a tag containing a value.
--
-- Since MPD 0.21.
--
-- @since 0.9.3.0
(%?) :: Metadata -> Value -> Query
m %? s = Filter (Contains (Match m s))
-- | Create a query matching a tag with regexp.
--
-- Since MPD 0.21.
--
-- @since 0.9.3.0
(~?) :: Metadata -> Value -> Query
m ~? s = Filter (Regex (Match m s))
-- | Create a query matching a tag with anything but a regexp.
--
-- Since MPD 0.21.
--
-- @since 0.9.3.0
(/~?) :: Metadata -> Value -> Query
m /~? s = Filter (RegexNot (Match m s))
-- | Negate a Query.
--
-- Since MPD 0.21.
--
-- @since 0.9.3.0
qNot :: Query -> Query
qNot (Query ms) = Filter (ExprNot (toExpr ms))
qNot (Filter (ExprNot ex)) = Filter ex
qNot (Filter ex) = Filter (ExprNot ex)
-- | Create a query for songs modified since a date.
--
-- Since MPD 0.21.
--
-- @since 0.9.3.0
qModSince :: UTCTime -> Query
qModSince time = Filter (ModifiedSince time)
-- | Create a query for the full song URI relative to the music directory.
--
-- Since MPD 0.21.
--
-- @since 0.9.3.0
qFile :: Path -> Query
qFile file = Filter (File file)
-- | Limit the query to the given directory, relative to the music directory.
--
-- Since MPD 0.21.
--
-- @since 0.9.3.0
qBase :: Path -> Query
qBase dir = Filter (Base dir)
|
bens/libmpd-haskell
|
src/Network/MPD/Commands/Query.hs
|
lgpl-2.1
| 5,169
| 0
| 14
| 1,399
| 1,530
| 809
| 721
| 82
| 1
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="fil-PH">
<title>Pagtukoy ng teknolohiya | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Mga nilalaman</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Paghahanap</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Mga paborito</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
veggiespam/zap-extensions
|
addOns/wappalyzer/src/main/javahelp/org/zaproxy/zap/extension/wappalyzer/resources/help_fil_PH/helpset_fil_PH.hs
|
apache-2.0
| 998
| 85
| 52
| 163
| 406
| 213
| 193
| -1
| -1
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : Size.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:14
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qth.ClassTypes.Core.Size (
ISize(..), Size, SizeF
,withCSize, withCSizeF, withSizeResult, withSizeFResult
)
where
import Foreign.C
import Foreign.Ptr
import Foreign.Storable
import Foreign.Marshal.Alloc
import Qtc.Classes.Types
import Qth.Core.Base
data ISize a = (Ord a, Num a) => ISize a a
type Size = ISize Int
type SizeF = ISize Double
withCSize :: Size -> (CInt -> CInt -> IO a) -> IO a
withCSize (ISize w h) f
= f (toCInt w) (toCInt h)
withSizeResult :: (Ptr CInt -> Ptr CInt -> IO ()) -> IO Size
withSizeResult f
= alloca $ \cw ->
alloca $ \ch ->
do f cw ch
w <- peek cw
h <- peek ch
return (fromCSize w h)
fromCSize :: CInt -> CInt -> Size
fromCSize w h
= ISize (fromCInt w) (fromCInt h)
withCSizeF :: SizeF -> (CDouble -> CDouble -> IO a) -> IO a
withCSizeF (ISize w h) f
= f (toCDouble w) (toCDouble h)
withSizeFResult :: (Ptr CDouble -> Ptr CDouble -> IO ()) -> IO SizeF
withSizeFResult f
= alloca $ \cw ->
alloca $ \ch ->
do f cw ch
w <- peek cw
h <- peek ch
return (fromCSizeF w h)
fromCSizeF :: CDouble -> CDouble -> SizeF
fromCSizeF w h
= ISize (fromCDouble w) (fromCDouble h)
|
uduki/hsQt
|
Qth/ClassTypes/Core/Size.hs
|
bsd-2-clause
| 1,593
| 0
| 13
| 367
| 531
| 272
| 259
| -1
| -1
|
{-# OPTIONS -fno-warn-overlapping-patterns #-}
-- | Optimizations to Image data-structures. Takes advantage of <http://hackage.haskell.org/package/uniplate>.
module Diagrams.AST.Optimize ( optimize ) where
import Diagrams.AST
import Data.Generics.Uniplate.Data
{- | The function 'optimize' takes an Image and returns an equivilant Image that optimizes the structure of the data.
Optimizations include:
* Turning @ 0 @ scalings into 'Blank' images
* Concatinating consecutive scalings, rotations, and translations
* Removing identity transformations
* Turning singleton transformation lists into regular transformations
-}
-- Using "rewrite" instead of transform (http://community.haskell.org/~ndm/darcs/uniplate/uniplate.htm)
optimize :: Image -> Image
optimize = reList . rewrite o . deList
-- Don't modify blank images
o (Modifier _ Blank) = Just Blank
-- Leaving the debate about pattern-matching on doubles until later
-- Identity scaling
o (Modifier (Scale 0 _) _) = Just Blank
o (Modifier (Scale _ 0) _) = Just Blank
o (Modifier (Scale 1 1) i) = Just i
-- Rotate a Circle? WTF?
o (Modifier (Rotate _) (Shape Circle)) = Just $ Shape Circle
-- Identity rotations - Monoidal properties on angle
o (Modifier (Rotate r') i)
| norm r' == 0 = Just i
| r' > 1 || r' < 0 = Just $ Modifier (Rotate $ norm r') i
| otherwise = Nothing
where
norm r
| r > 1 = norm (r-1)
| r < 0 = norm (r+1)
| otherwise = r
-- Identity translations
o (Modifier (Translate 0 0) i) = Just i
-- Consecutive Scales
o (Modifier (Scale x y) (Modifier (Scale x' y') i)) = Just $ Modifier (Scale (x*x') (y*y')) i
-- Consecutive Translations
o (Modifier (Translate x y) (Modifier (Translate x' y') i)) = Just $ Modifier (Translate (x+x') (y+y')) i
-- Consecutive Rotations
o (Modifier (Rotate a) (Modifier (Rotate a') i)) = Just $ Modifier (Rotate (a+a')) i
-- Removing Blanks from Combinations
o (Images (Atop Blank i)) = Just i
o (Images (Atop i Blank)) = Just i
o (Images (Above Blank i)) = Just i
o (Images (Above i Blank)) = Just i
o (Images (NextTo Blank i)) = Just i
o (Images (NextTo i Blank)) = Just i
-- Default
o _ = Nothing
-- Helpers
deList :: Image -> Image
deList = transform d
where
-- Changes
d (Modifier (Changes []) i) = i
d (Modifier (Changes l) i) = (foldl1 (.) . map Modifier $ l) i
-- Layers
d (Images (Layers [])) = Blank
d (Images (Layers l)) = f Atop l
-- Vertical
d (Images (Vertical [])) = Blank
d (Images (Vertical l)) = f Above l
-- Horizontal
d (Images (Horizontal [])) = Blank
d (Images (Horizontal l)) = f NextTo l
-- Default
d i = i
-- Helpers
f c = foldr (Images `owl` c) Blank where owl = (.).(.)
reList :: Image -> Image
reList = rewrite r
where
-- Modifications
r (Modifier m (Modifier (Changes l) i)) = Just $ Modifier (Changes (m:l)) i
r (Modifier m (Modifier m' i)) = Just $ Modifier (Changes [m, m']) i
-- Atop
r (Images (Atop i (Images (Layers l)))) = Just $ Images $ Layers (i:l)
r (Images (Atop i (Images (Atop j k)))) = Just $ Images $ Layers [i, j, k]
-- Above
r (Images (Above i (Images (Vertical l)))) = Just $ Images $ Vertical (i:l)
r (Images (Above i (Images (Above j k)))) = Just $ Images $ Vertical [i, j, k]
-- NextTo
r (Images (NextTo i (Images (Horizontal l)))) = Just $ Images $ Horizontal (i:l)
r (Images (NextTo i (Images (NextTo j k)))) = Just $ Images $ Horizontal [i, j, k]
-- Default
r _ = Nothing
|
sordina/Diagrams-AST
|
src/Diagrams/AST/Optimize.hs
|
bsd-3-clause
| 3,581
| 1
| 15
| 857
| 1,466
| 747
| 719
| 53
| 9
|
module CodeGen.Preprocessor(preprocess) where
import Data.List
import Data.Maybe
import qualified AST.AST as A
import qualified AST.Util as Util
import qualified AST.Meta as Meta
import qualified Types as Ty
-- | Functions run on the entire AST before code generation.
preprocess :: A.Program -> A.Program
preprocess = injectTraitsToClasses . giveClosuresUniqueNames
injectTraitsToClasses :: A.Program -> A.Program
injectTraitsToClasses p =
Util.mapProgramClass p injectTraitsToClass
where
injectTraitsToClass :: A.ClassDecl -> A.ClassDecl
injectTraitsToClass c@A.Class{A.ccomposition} =
foldr injectTraitToClass c (A.typesFromTraitComposition ccomposition)
injectTraitToClass :: Ty.Type -> A.ClassDecl -> A.ClassDecl
injectTraitToClass traitType c@A.Class{A.cmethods} =
let
traitTemplate = A.getTrait traitType p
injectedMethods = flattenTrait c traitType traitTemplate
in
c{A.cmethods = cmethods ++ injectedMethods}
-- | @flattenTrait cdecl t tdecl@ returns the methods of
-- @tdecl@, translated to appear as if they were declared in
-- @cdecl@ with any type parameters of @tdecl@ instantiated to the
-- type arguments of @t@.
flattenTrait :: A.ClassDecl -> Ty.Type -> A.TraitDecl -> [A.MethodDecl]
flattenTrait cdecl traitType template =
let
formals = Ty.getTypeParameters $ A.tname template
actuals = Ty.getTypeParameters traitType
bindings = zip formals actuals
traitMethods = A.tmethods template
classMethods = map A.methodName $ A.cmethods cdecl
nonOverridden = filter ((`notElem` classMethods) . A.methodName) traitMethods
in
map (convertMethod bindings cdecl) nonOverridden
-- | @convertMethod bindings cdecl m@ converts all types
-- appearing in @m@ using @bindings@ as a convertion table. It
-- also gives all accesses of or through @this@ types as if
-- @cdecl@ was the current enclosing class.
convertMethod ::
[(Ty.Type, Ty.Type)] -> A.ClassDecl -> A.MethodDecl -> A.MethodDecl
convertMethod bindings cdecl method =
let
header = A.mheader method
htype = convertType $ A.methodType method
hparams = map convertNode $ A.methodParams method
mheader = header{A.htype, A.hparams}
mbody = Util.extend convertExpr $ A.mbody method
in
method{A.mheader, A.mbody}
where
convertType :: Ty.Type -> Ty.Type
convertType = Ty.replaceTypeVars bindings
convertExpr :: A.Expr -> A.Expr
convertExpr e
| A.isThisAccess e = A.setType (A.cname cdecl) $ convertNode e
| isThisFieldAccess e =
let f = A.name e
ty = getFieldType f (A.cfields cdecl)
in A.setType ty $ convertNode e
| otherwise = convertNode $ Util.exprTypeMap convertType e
isThisFieldAccess A.FieldAccess{A.target} = A.isThisAccess target
isThisFieldAccess _ = False
getFieldType f =
A.ftype . fromMaybe err . find ((== f) . A.fname)
where
err = error $ "Preprocessor.hs: Could not find field: " ++ show f
convertNode :: A.HasMeta n => n -> n
convertNode node =
let
oldType = A.getType node
newType = convertType oldType
in
A.setType newType node
giveClosuresUniqueNames :: A.Program -> A.Program
giveClosuresUniqueNames = snd . Util.extendAccumProgram uniqueClosureName 0
where
uniqueClosureName acc e
| A.isClosure e =
let m = A.getMeta e
mclosure = Meta.metaClosure ("closure" ++ show acc) m
in (acc + 1, A.setMeta e mclosure)
| otherwise = (acc, e)
|
Paow/encore
|
src/back/CodeGen/Preprocessor.hs
|
bsd-3-clause
| 3,611
| 0
| 15
| 843
| 959
| 493
| 466
| -1
| -1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.SQS.GetQueueUrl
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Returns the URL of an existing queue. This action provides a simple way to
-- retrieve the URL of an Amazon SQS queue.
--
-- To access a queue that belongs to another AWS account, use the 'QueueOwnerAWSAccountId' parameter to specify the account ID of the queue's owner. The queue's owner
-- must grant you permission to access the queue. For more information about
-- shared queue access, see 'AddPermission' or go to <http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/acp-overview.html Shared Queues> in the /AmazonSQS Developer Guide/.
--
-- <http://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_GetQueueUrl.html>
module Network.AWS.SQS.GetQueueUrl
(
-- * Request
GetQueueUrl
-- ** Request constructor
, getQueueUrl
-- ** Request lenses
, gquQueueName
, gquQueueOwnerAWSAccountId
-- * Response
, GetQueueUrlResponse
-- ** Response constructor
, getQueueUrlResponse
-- ** Response lenses
, gqurQueueUrl
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.SQS.Types
import qualified GHC.Exts
data GetQueueUrl = GetQueueUrl
{ _gquQueueName :: Text
, _gquQueueOwnerAWSAccountId :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'GetQueueUrl' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'gquQueueName' @::@ 'Text'
--
-- * 'gquQueueOwnerAWSAccountId' @::@ 'Maybe' 'Text'
--
getQueueUrl :: Text -- ^ 'gquQueueName'
-> GetQueueUrl
getQueueUrl p1 = GetQueueUrl
{ _gquQueueName = p1
, _gquQueueOwnerAWSAccountId = Nothing
}
-- | The name of the queue whose URL must be fetched. Maximum 80 characters;
-- alphanumeric characters, hyphens (-), and underscores (_) are allowed.
gquQueueName :: Lens' GetQueueUrl Text
gquQueueName = lens _gquQueueName (\s a -> s { _gquQueueName = a })
-- | The AWS account ID of the account that created the queue.
gquQueueOwnerAWSAccountId :: Lens' GetQueueUrl (Maybe Text)
gquQueueOwnerAWSAccountId =
lens _gquQueueOwnerAWSAccountId
(\s a -> s { _gquQueueOwnerAWSAccountId = a })
newtype GetQueueUrlResponse = GetQueueUrlResponse
{ _gqurQueueUrl :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'GetQueueUrlResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'gqurQueueUrl' @::@ 'Text'
--
getQueueUrlResponse :: Text -- ^ 'gqurQueueUrl'
-> GetQueueUrlResponse
getQueueUrlResponse p1 = GetQueueUrlResponse
{ _gqurQueueUrl = p1
}
-- | The URL for the queue.
gqurQueueUrl :: Lens' GetQueueUrlResponse Text
gqurQueueUrl = lens _gqurQueueUrl (\s a -> s { _gqurQueueUrl = a })
instance ToPath GetQueueUrl where
toPath = const "/"
instance ToQuery GetQueueUrl where
toQuery GetQueueUrl{..} = mconcat
[ "QueueName" =? _gquQueueName
, "QueueOwnerAWSAccountId" =? _gquQueueOwnerAWSAccountId
]
instance ToHeaders GetQueueUrl
instance AWSRequest GetQueueUrl where
type Sv GetQueueUrl = SQS
type Rs GetQueueUrl = GetQueueUrlResponse
request = post "GetQueueUrl"
response = xmlResponse
instance FromXML GetQueueUrlResponse where
parseXML = withElement "GetQueueUrlResult" $ \x -> GetQueueUrlResponse
<$> x .@ "QueueUrl"
|
kim/amazonka
|
amazonka-sqs/gen/Network/AWS/SQS/GetQueueUrl.hs
|
mpl-2.0
| 4,402
| 0
| 9
| 968
| 505
| 308
| 197
| 62
| 1
|
module Main where
import Text.PrettyPrint.HughesPJ
xs :: [Doc]
xs = [text "hello",
nest 10 (text "world")]
d1 :: Doc
d1 = vcat xs
d2 :: Doc
d2 = foldr ($$) empty xs
d3 :: Doc
d3 = foldr ($+$) empty xs
main :: IO ()
main = do print d1
print d2
print d3
|
beni55/pretty
|
tests/T3911.hs
|
bsd-3-clause
| 286
| 0
| 8
| 88
| 127
| 68
| 59
| 15
| 1
|
-- | Type-safe client-server communication framework for Haste.
--
-- In addition to the Haste.App extras, this module exports the same API as
-- "Haste", modified slightly to work better with the automatic program
-- slicing Haste.App provides. This means that you should import either this
-- module *or* Haste, but *not* both.
module Haste.App (
MonadIO, Remotable, App, Server, Remote, Done,
Sessions, SessionID,
liftServerIO, forkServerIO, remote, runApp,
(<.>), getSessionID, getActiveSessions, onSessionEnd,
AppCfg, defaultConfig, cfgHost, cfgPort, mkConfig,
Client,
runClient, onServer, liftIO,
JSString, JSAny, URL, alert, prompt, eval, writeLog, catJSStr, fromJSStr,
module Haste.DOM.Core,
module Haste.Random,
module Haste.Prim.JSType,
module Haste.Hash,
module Haste.Binary
) where
import Haste.App.Client
import Haste.App.Monad
import Haste.Binary (Binary (..))
import Haste.DOM.Core
import Haste.Random
import Haste.Prim.JSType
import Haste.Hash
import Haste
import Control.Monad.IO.Class
|
beni55/haste-compiler
|
libraries/haste-lib/src/Haste/App.hs
|
bsd-3-clause
| 1,065
| 0
| 6
| 184
| 208
| 141
| 67
| 23
| 0
|
{-# LANGUAGE ScopedTypeVariables, BangPatterns #-}
-- K-Means sample from "Parallel and Concurrent Programming in Haskell"
--
-- With three versions:
-- [ kmeans_seq ] a sequential version
-- [ kmeans_strat ] a parallel version using Control.Parallel.Strategies
-- [ kmeans_par ] a parallel version using Control.Monad.Par
--
-- Usage (sequential):
-- $ ./kmeans seq
--
-- Usage (Strategies):
-- $ ./kmeans strat 600 +RTS -N4
--
-- Usage (Par monad):
-- $ ./kmeans par 600 +RTS -N4
--
-- Usage (divide-and-conquer / Par monad):
-- $ ./kmeans divpar 7 +RTS -N4
--
-- Usage (divide-and-conquer / Eval monad):
-- $ ./kmeans diveval 7 +RTS -N4
import System.IO
import KMeansCore
import Data.Array
import Data.Array.Unsafe as Unsafe
import Text.Printf
import Data.List
import Data.Function
import Data.Binary (decodeFile)
import Debug.Trace
import Control.Parallel.Strategies as Strategies
import Control.Monad.Par as Par
import Control.DeepSeq
import System.Environment
import Data.Time.Clock
import Control.Exception
import Control.Concurrent
import Control.Monad.ST
import Data.Array.ST
import System.Mem
import Data.Maybe
import qualified Data.Vector as Vector
import Data.Vector (Vector)
import qualified Data.Vector.Mutable as MVector
-- -----------------------------------------------------------------------------
-- main: read input files, time calculation
main = runInUnboundThread $ do
points <- decodeFile "points.bin"
clusters <- read `fmap` readFile "clusters"
let nclusters = length clusters
args <- getArgs
npoints <- evaluate (length points)
performGC
t0 <- getCurrentTime
final_clusters <- case args of
["seq" ] -> kmeans_seq nclusters points clusters
["strat", n] -> kmeans_strat (read n) nclusters points clusters
["par", n] -> kmeans_par (read n) nclusters points clusters
["divpar", n] -> kmeans_div_par (read n) nclusters points clusters npoints
["diveval", n] -> kmeans_div_eval (read n) nclusters points clusters npoints
_other -> error "args"
t1 <- getCurrentTime
print final_clusters
printf "Total time: %.2f\n" (realToFrac (diffUTCTime t1 t0) :: Double)
-- -----------------------------------------------------------------------------
-- K-Means: repeatedly step until convergence (sequential)
-- <<kmeans_seq
kmeans_seq :: Int -> [Point] -> [Cluster] -> IO [Cluster]
kmeans_seq nclusters points clusters =
let
loop :: Int -> [Cluster] -> IO [Cluster]
loop n clusters | n > tooMany = do -- <1>
putStrLn "giving up."
return clusters
loop n clusters = do
printf "iteration %d\n" n
putStr (unlines (map show clusters))
let clusters' = step nclusters clusters points -- <2>
if clusters' == clusters -- <3>
then return clusters
else loop (n+1) clusters'
in
loop 0 clusters
tooMany = 80
-- >>
-- -----------------------------------------------------------------------------
-- K-Means: repeatedly step until convergence (Strategies)
-- <<kmeans_strat
kmeans_strat :: Int -> Int -> [Point] -> [Cluster] -> IO [Cluster]
kmeans_strat numChunks nclusters points clusters =
let
chunks = split numChunks points -- <1>
loop :: Int -> [Cluster] -> IO [Cluster]
loop n clusters | n > tooMany = do
printf "giving up."
return clusters
loop n clusters = do
printf "iteration %d\n" n
putStr (unlines (map show clusters))
let clusters' = parSteps_strat nclusters clusters chunks -- <2>
if clusters' == clusters
then return clusters
else loop (n+1) clusters'
in
loop 0 clusters
-- >>
-- <<split
split :: Int -> [a] -> [[a]]
split numChunks xs = chunk (length xs `quot` numChunks) xs
chunk :: Int -> [a] -> [[a]]
chunk n [] = []
chunk n xs = as : chunk n bs
where (as,bs) = splitAt n xs
-- >>
-- -----------------------------------------------------------------------------
-- K-Means: repeatedly step until convergence (Par monad)
kmeans_par :: Int -> Int -> [Point] -> [Cluster] -> IO [Cluster]
kmeans_par mappers nclusters points clusters =
let
chunks = split mappers points
loop :: Int -> [Cluster] -> IO [Cluster]
loop n clusters | n > tooMany = do printf "giving up."; return clusters
loop n clusters = do
printf "iteration %d\n" n
putStr (unlines (map show clusters))
let
clusters' = steps_par nclusters clusters chunks
if clusters' == clusters
then return clusters
else loop (n+1) clusters'
in
loop 0 clusters
-- -----------------------------------------------------------------------------
-- kmeans_div_par: Use divide-and-conquer, and the Par monad for parallellism.
kmeans_div_par :: Int -> Int -> [Point] -> [Cluster] -> Int -> IO [Cluster]
kmeans_div_par threshold nclusters points clusters npoints =
let
tree = mkPointTree threshold points npoints
loop :: Int -> [Cluster] -> IO [Cluster]
loop n clusters | n > tooMany = do printf "giving up."; return clusters
loop n clusters = do
hPrintf stderr "iteration %d\n" n
hPutStr stderr (unlines (map show clusters))
let
divconq :: Tree [Point] -> Par (Vector PointSum)
divconq (Leaf points) = return $ assign nclusters clusters points
divconq (Node left right) = do
i1 <- spawn $ divconq left
i2 <- spawn $ divconq right
c1 <- get i1
c2 <- get i2
return $! combine c1 c2
clusters' = makeNewClusters $ runPar $ divconq tree
if clusters' == clusters
then return clusters
else loop (n+1) clusters'
in
loop 0 clusters
data Tree a = Leaf a
| Node (Tree a) (Tree a)
mkPointTree :: Int -> [Point] -> Int -> Tree [Point]
mkPointTree threshold points npoints = go 0 points npoints
where
go depth points npoints
| depth >= threshold = Leaf points
| otherwise = Node (go (depth+1) xs half)
(go (depth+1) ys half)
where
half = npoints `quot` 2
(xs,ys) = splitAt half points
-- -----------------------------------------------------------------------------
-- kmeans_div_eval: Use divide-and-conquer, and the Eval monad for parallellism.
kmeans_div_eval :: Int -> Int -> [Point] -> [Cluster] -> Int -> IO [Cluster]
kmeans_div_eval threshold nclusters points clusters npoints =
let
tree = mkPointTree threshold points npoints
loop :: Int -> [Cluster] -> IO [Cluster]
loop n clusters | n > tooMany = do printf "giving up."; return clusters
loop n clusters = do
hPrintf stderr "iteration %d\n" n
hPutStr stderr (unlines (map show clusters))
let
divconq :: Tree [Point] -> Vector PointSum
divconq (Leaf points) = assign nclusters clusters points
divconq (Node left right) = runEval $ do
c1 <- rpar $ divconq left
c2 <- rpar $ divconq right
rdeepseq c1
rdeepseq c2
return $! combine c1 c2
clusters' = makeNewClusters $ divconq tree
if clusters' == clusters
then return clusters
else loop (n+1) clusters'
in
loop 0 clusters
-- -----------------------------------------------------------------------------
-- Perform one step of the K-Means algorithm
-- <<step
step :: Int -> [Cluster] -> [Point] -> [Cluster]
step nclusters clusters points
= makeNewClusters (assign nclusters clusters points)
-- >>
-- <<assign
assign :: Int -> [Cluster] -> [Point] -> Vector PointSum
assign nclusters clusters points = Vector.create $ do
vec <- MVector.replicate nclusters (PointSum 0 0 0)
let
addpoint p = do
let c = nearest p; cid = clId c
ps <- MVector.read vec cid
MVector.write vec cid $! addToPointSum ps p
mapM_ addpoint points
return vec
where
nearest p = fst $ minimumBy (compare `on` snd)
[ (c, sqDistance (clCent c) p) | c <- clusters ]
-- >>
data PointSum = PointSum {-# UNPACK #-} !Int {-# UNPACK #-} !Double {-# UNPACK #-} !Double
instance NFData PointSum where
rnf (PointSum count xs ys) = () -- all fields are strict
-- <<addToPointSum
addToPointSum :: PointSum -> Point -> PointSum
addToPointSum (PointSum count xs ys) (Point x y)
= PointSum (count+1) (xs + x) (ys + y)
-- >>
-- <<pointSumToCluster
pointSumToCluster :: Int -> PointSum -> Cluster
pointSumToCluster i (PointSum count xs ys) =
Cluster { clId = i
, clCent = Point (xs / fromIntegral count) (ys / fromIntegral count)
}
-- >>
-- <<addPointSums
addPointSums :: PointSum -> PointSum -> PointSum
addPointSums (PointSum c1 x1 y1) (PointSum c2 x2 y2)
= PointSum (c1+c2) (x1+x2) (y1+y2)
-- >>
-- <<combine
combine :: Vector PointSum -> Vector PointSum -> Vector PointSum
combine = Vector.zipWith addPointSums
-- >>
-- <<parSteps_strat
parSteps_strat :: Int -> [Cluster] -> [[Point]] -> [Cluster]
parSteps_strat nclusters clusters pointss
= makeNewClusters $
foldr1 combine $
(map (assign nclusters clusters) pointss
`using` parList rseq)
-- >>
steps_par :: Int -> [Cluster] -> [[Point]] -> [Cluster]
steps_par nclusters clusters pointss
= makeNewClusters $
foldl1' combine $
(runPar $ Par.parMap (assign nclusters clusters) pointss)
-- <<makeNewClusters
makeNewClusters :: Vector PointSum -> [Cluster]
makeNewClusters vec =
[ pointSumToCluster i ps
| (i,ps@(PointSum count _ _)) <- zip [0..] (Vector.toList vec)
, count > 0
]
-- >>
-- v. important: filter out any clusters that have
-- no points. This can happen when a cluster is not
-- close to any points. If we leave these in, then
-- the NaNs mess up all the future calculations.
|
prt2121/haskell-practice
|
parconc/kmeans/kmeans.hs
|
apache-2.0
| 10,152
| 2
| 19
| 2,672
| 2,861
| 1,457
| 1,404
| 197
| 6
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="hu-HU">
<title>Quick Start | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Keresés</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
rnehra01/zap-extensions
|
src/org/zaproxy/zap/extension/quickstart/resources/help_hu_HU/helpset_hu_HU.hs
|
apache-2.0
| 975
| 85
| 52
| 160
| 401
| 211
| 190
| -1
| -1
|
import qualified Data.Vector as U
import Data.Bits
main = print . U.minimumBy (\x y -> GT) . U.map (*2) . U.map (`shiftL` 2) $ U.replicate (100000000 :: Int) (5::Int)
|
phaazon/vector
|
old-testsuite/microsuite/minimumBy.hs
|
bsd-3-clause
| 168
| 1
| 11
| 30
| 92
| 51
| 41
| 3
| 1
|
{-# LANGUAGE TupleSections, OverloadedStrings #-}
module Handler.Home where
import Import
-- This is a handler function for the GET request method on the HomeR
-- resource pattern. All of your resource patterns are defined in
-- config/routes
--
-- The majority of the code you will write in Yesod lives in these handler
-- functions. You can spread them across multiple files if you are so
-- inclined, or create a single monolithic file.
getHomeR :: Handler Html
getHomeR = do
(formWidget, formEnctype) <- generateFormPost sampleForm
let submission = Nothing :: Maybe (FileInfo, Text)
handlerName = "getHomeR" :: Text
defaultLayout $ do
aDomId <- newIdent
setTitle "Welcome To Yesod!"
$(widgetFile "homepage")
postHomeR :: Handler Html
postHomeR = do
((result, formWidget), formEnctype) <- runFormPost sampleForm
let handlerName = "postHomeR" :: Text
submission = case result of
FormSuccess res -> Just res
_ -> Nothing
defaultLayout $ do
aDomId <- newIdent
setTitle "Welcome To Yesod!"
$(widgetFile "homepage")
sampleForm :: Form (FileInfo, Text)
sampleForm = renderDivs $ (,)
<$> fileAFormReq "Choose a file"
<*> areq textField "What's on the file?" Nothing
|
zhy0216/haskell-learning
|
yosog/Handler/Home.hs
|
mit
| 1,287
| 0
| 13
| 303
| 253
| 130
| 123
| 27
| 2
|
{-# LANGUAGE TypeFamilies #-}
module T11164a where
data family T a
|
olsner/ghc
|
testsuite/tests/rename/should_compile/T11164a.hs
|
bsd-3-clause
| 68
| 0
| 3
| 12
| 10
| 8
| 2
| 3
| 0
|
{-# LANGUAGE Safe #-}
{-# LANGUAGE FlexibleInstances #-}
module SH_Overlap1_A (
C(..)
) where
import SH_Overlap1_B
instance
{-# OVERLAPS #-}
C [Int] where
f _ = "[Int]"
|
urbanslug/ghc
|
testsuite/tests/safeHaskell/overlapping/SH_Overlap1_A.hs
|
bsd-3-clause
| 186
| 0
| 6
| 44
| 38
| 24
| 14
| 9
| 0
|
module ShouldCompile where
{-| weoprjwer {- | qwoiejqwioe -}-}
main = undefined
|
oldmanmike/ghc
|
testsuite/tests/haddock/should_compile_noflag_haddock/haddockC010.hs
|
bsd-3-clause
| 82
| 0
| 4
| 14
| 10
| 7
| 3
| 2
| 1
|
module Language.Plover.ErrorUtil where
import Data.Tag
import Data.List
import Text.ParserCombinators.Parsec
import System.IO.Error
import Control.Applicative ((<$>))
showTagPositions :: Tag SourcePos -> IO String
showTagPositions tag = do
sls <- mapM showLineFromFile (sort $ nub $ getTags tag)
return $ "Error " ++ unlines (("at " ++) <$> sls)
showLineFromFile :: SourcePos -> IO String
showLineFromFile pos = case sourceName pos of
"*stdin*" -> return $ show pos ++ ":\n"
fileName -> catchIOError (do ls <- lines <$> readFile fileName
return $ showLine ls pos)
(\err -> return $ show pos ++ ":\n")
-- | Gives a carat pointing to a position in a line in a source file
showLine :: [String] -- ^ the lines from the source file
-> SourcePos
-> String
showLine ls pos
= show pos ++ ":\n"
++ line
where line = if sourceLine pos <= length ls
then ls !! (sourceLine pos - 1) ++ "\n" ++ errptr
else "(end of file)\n"
errptr = replicate (sourceColumn pos - 1) ' ' ++ "^"
|
swift-nav/plover
|
src/Language/Plover/ErrorUtil.hs
|
mit
| 1,173
| 0
| 14
| 375
| 328
| 169
| 159
| 26
| 2
|
module Main where
import Control.Monad.Trans.Resource
import Data.Char
import Data.Conduit
import qualified Data.Conduit.Combinators as CC
import qualified Data.Conduit.Text as CT
import qualified Data.Text as DT
findWords :: Monad m => Conduit DT.Text m DT.Text
findWords = dropBad >> start
where
dropBad = CT.dropWhile (not . isAlpha)
start = CC.peek >>= maybe (return ()) (const $ loop)
loop = do
CT.takeWhile isAlpha
dropBad
findWords
main :: IO ()
main = runResourceT $ CC.stdin
$$ findWords
=$ CC.unlines
=$ CC.stdout
|
dancor/melang
|
src/Main/pull-words.hs
|
mit
| 577
| 0
| 11
| 130
| 185
| 103
| 82
| 20
| 1
|
module Language.RuScript.ByteCode (
ByteCode(..)
, Label
, initLabel
, genLabel
, Pos
, Address
) where
data ByteCode = CALL Int
| INVOKE String
| RET
-- * Address should be `Pos` after pass one
| JUMP Address
| JUMPT Address
| JUMPF Address
-- *
| PUSH Int
| POP Int
| NEW Int
| PUSHA String
| POPA String
| PUSHSTR String
| PUSHINT Int
| PUSHBOOL Int
| CLASS Int Int Int
| SFUNC
| EBODY Int
-- * Extensions
| PUSHLIST
| PUSHNIL
deriving (Show, Eq)
-- Label
newtype Label = Label Int -- Label no.
deriving (Show, Eq, Ord)
initLabel :: Label
initLabel = Label 0
genLabel :: Label -> (Label, Label)
genLabel (Label i) = (Label i, Label $ i + 1)
-- Position in the bytecode array
type Pos = Int
-- Abstract address is either a absolute position, or a label
type Address = Either Pos Label
|
izgzhen/RuScript
|
rusc/src/Language/RuScript/ByteCode.hs
|
mit
| 1,147
| 0
| 7
| 515
| 243
| 146
| 97
| 35
| 1
|
-- Tardis monad
-- ref:
|
Airtnp/Freshman_Simple_Haskell_Lib
|
Idioms/Tardis-monad.hs
|
mit
| 24
| 0
| 2
| 5
| 4
| 3
| 1
| 1
| 0
|
module Jolly.Eval
( Value(..)
, TermEnv
, Interpreter
, runEval
, emptyTermEnv
) where
import Control.Monad.Identity
import qualified Data.Map.Strict as Map
import Jolly.Syntax
data Value
= VInt Int
| VBool Bool
| VClosure String
Expr
TermEnv
deriving (Show)
type TermEnv = Map.Map String Value
type Interpreter t = Identity t
emptyTermEnv :: TermEnv
emptyTermEnv = Map.empty
eval :: TermEnv -> Expr -> Interpreter Value
eval env expr =
case expr of
Lit (LInt k) -> return $ VInt k
Lit (LBool k) -> return $ VBool k
Var x -> do
let Just v = Map.lookup x env
return v
Op op a b -> do
VInt a' <- eval env a
VInt b' <- eval env b
return $ binop op a' b'
Lam x body -> return (VClosure x body env)
App fun arg -> do
VClosure x body clo <- eval env fun
argv <- eval env arg
let nenv = Map.insert x argv clo
eval nenv body
Let x e body -> do
e' <- eval env e
let nenv = Map.insert x e' env
eval nenv body
If cond tr fl -> do
VBool br <- eval env cond
if br
then eval env tr
else eval env fl
Fix e -> eval env (App e (Fix e))
binop :: BinOp -> Int -> Int -> Value
binop Add a b = VInt $ a + b
binop Mul a b = VInt $ a * b
binop Sub a b = VInt $ a - b
binop Eql a b = VBool $ a == b
runEval :: TermEnv -> String -> Expr -> (Value, TermEnv)
runEval env nm ex =
let res = runIdentity (eval env ex)
in (res, Map.insert nm res env)
|
jchildren/jolly
|
src/Jolly/Eval.hs
|
mit
| 1,544
| 0
| 14
| 514
| 667
| 325
| 342
| 57
| 10
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
-- | This module captures in a typeclass the interface of concurrency
-- monads.
module Control.Monad.Conc.Class
( MonadConc(..)
-- * Utilities
, spawn
, forkFinally
, killThread
) where
import Control.Concurrent (forkIO)
import Control.Concurrent.MVar (MVar, readMVar, newEmptyMVar, putMVar, tryPutMVar, takeMVar, tryTakeMVar)
import Control.Exception (Exception, AsyncException(ThreadKilled), SomeException)
import Control.Monad (liftM)
import Control.Monad.Catch (MonadCatch, MonadThrow, MonadMask)
import Control.Monad.Reader (ReaderT(..), runReaderT)
import Control.Monad.STM (STM)
import Control.Monad.STM.Class (MonadSTM, CTVar)
import Control.Monad.Trans (lift)
import Data.IORef (IORef, atomicModifyIORef, newIORef, readIORef)
import qualified Control.Concurrent as C
import qualified Control.Monad.Catch as Ca
import qualified Control.Monad.RWS.Lazy as RL
import qualified Control.Monad.RWS.Strict as RS
import qualified Control.Monad.STM as S
import qualified Control.Monad.State.Lazy as SL
import qualified Control.Monad.State.Strict as SS
import qualified Control.Monad.Writer.Lazy as WL
import qualified Control.Monad.Writer.Strict as WS
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative (Applicative)
import Data.Monoid (Monoid, mempty)
#endif
-- | @MonadConc@ is an abstraction over GHC's typical concurrency
-- abstraction. It captures the interface of concurrency monads in
-- terms of how they can operate on shared state and in the presence
-- of exceptions.
--
-- There are a few notable differences between this and the @Par@
-- monad approach: firstly, @Par@ imposes 'NFData' constraints on
-- everything, as it achieves its speed-up by forcing evaluation in
-- separate threads. @MonadConc@ doesn't do that, and so you need to
-- be careful about where evaluation occurs, just like with
-- 'MVar's. Secondly, this builds on @Par@'s futures by allowing
-- @CVar@s which threads can read from and write to, possibly multiple
-- times, whereas with the @Par@ monads it is illegal to write
-- multiple times to the same @IVar@ (or to non-blockingly read from
-- it) which, when there are no exceptions, removes the possibility of
-- data races.
--
-- Every @MonadConc@ has an associated 'MonadSTM', transactions of
-- which can be run atomically.
class ( Applicative m, Monad m
, MonadCatch m, MonadThrow m, MonadMask m
, MonadSTM (STMLike m)
, Eq (ThreadId m), Show (ThreadId m)) => MonadConc m where
-- | The associated 'MonadSTM' for this class.
type STMLike m :: * -> *
-- | The mutable reference type, like 'MVar's. This may contain one
-- value at a time, attempting to read or take from an \"empty\"
-- @CVar@ will block until it is full, and attempting to put to a
-- \"full\" @CVar@ will block until it is empty.
type CVar m :: * -> *
-- | The mutable non-blocking reference type. These are like
-- 'IORef's, but don't have the potential re-ordering problem
-- mentioned in Data.IORef.
type CRef m :: * -> *
-- | An abstract handle to a thread.
type ThreadId m :: *
-- | Fork a computation to happen concurrently. Communication may
-- happen over @CVar@s.
fork :: m () -> m (ThreadId m)
-- | Like 'fork', but the child thread is passed a function that can
-- be used to unmask asynchronous exceptions. This function should
-- not be used within a 'mask' or 'uninterruptibleMask'.
forkWithUnmask :: ((forall a. m a -> m a) -> m ()) -> m (ThreadId m)
-- | Fork a computation to happen on a specific processor. The
-- specified int is the /capability number/, typically capabilities
-- correspond to physical processors or cores but this is
-- implementation dependent. The int is interpreted modulo to the
-- total number of capabilities as returned by 'getNumCapabilities'.
forkOn :: Int -> m () -> m (ThreadId m)
-- | Get the number of Haskell threads that can run simultaneously.
getNumCapabilities :: m Int
-- | Get the @ThreadId@ of the current thread.
myThreadId :: m (ThreadId m)
-- | Create a new empty @CVar@.
newEmptyCVar :: m (CVar m a)
-- | Put a value into a @CVar@. If there is already a value there,
-- this will block until that value has been taken, at which point
-- the value will be stored.
putCVar :: CVar m a -> a -> m ()
-- | Attempt to put a value in a @CVar@ non-blockingly, returning
-- 'True' (and filling the @CVar@) if there was nothing there,
-- otherwise returning 'False'.
tryPutCVar :: CVar m a -> a -> m Bool
-- | Block until a value is present in the @CVar@, and then return
-- it. As with 'readMVar', this does not \"remove\" the value,
-- multiple reads are possible.
readCVar :: CVar m a -> m a
-- | Take a value from a @CVar@. This \"empties\" the @CVar@,
-- allowing a new value to be put in. This will block if there is no
-- value in the @CVar@ already, until one has been put.
takeCVar :: CVar m a -> m a
-- | Attempt to take a value from a @CVar@ non-blockingly, returning
-- a 'Just' (and emptying the @CVar@) if there was something there,
-- otherwise returning 'Nothing'.
tryTakeCVar :: CVar m a -> m (Maybe a)
-- | Create a new reference.
newCRef :: a -> m (CRef m a)
-- | Read the current value stored in a reference.
readCRef :: CRef m a -> m a
-- | Atomically modify the value stored in a reference.
modifyCRef :: CRef m a -> (a -> (a, b)) -> m b
-- | Replace the value stored in a reference.
--
-- > writeCRef r a = modifyCRef r $ const (a, ())
writeCRef :: CRef m a -> a -> m ()
writeCRef r a = modifyCRef r $ const (a, ())
-- | Perform an STM transaction atomically.
atomically :: STMLike m a -> m a
-- | Throw an exception. This will \"bubble up\" looking for an
-- exception handler capable of dealing with it and, if one is not
-- found, the thread is killed.
--
-- > throw = Control.Monad.Catch.throwM
throw :: Exception e => e -> m a
throw = Ca.throwM
-- | Catch an exception. This is only required to be able to catch
-- exceptions raised by 'throw', unlike the more general
-- Control.Exception.catch function. If you need to be able to catch
-- /all/ errors, you will have to use 'IO'.
--
-- > catch = Control.Monad.Catch.catch
catch :: Exception e => m a -> (e -> m a) -> m a
catch = Ca.catch
-- | Throw an exception to the target thread. This blocks until the
-- exception is delivered, and it is just as if the target thread
-- had raised it with 'throw'. This can interrupt a blocked action.
throwTo :: Exception e => ThreadId m -> e -> m ()
-- | Executes a computation with asynchronous exceptions
-- /masked/. That is, any thread which attempts to raise an
-- exception in the current thread with 'throwTo' will be blocked
-- until asynchronous exceptions are unmasked again.
--
-- The argument passed to mask is a function that takes as its
-- argument another function, which can be used to restore the
-- prevailing masking state within the context of the masked
-- computation. This function should not be used within an
-- 'uninterruptibleMask'.
--
-- > mask = Control.Monad.Catch.mask
mask :: ((forall a. m a -> m a) -> m b) -> m b
mask = Ca.mask
-- | Like 'mask', but the masked computation is not
-- interruptible. THIS SHOULD BE USED WITH GREAT CARE, because if a
-- thread executing in 'uninterruptibleMask' blocks for any reason,
-- then the thread (and possibly the program, if this is the main
-- thread) will be unresponsive and unkillable. This function should
-- only be necessary if you need to mask exceptions around an
-- interruptible operation, and you can guarantee that the
-- interruptible operation will only block for a short period of
-- time. The supplied unmasking function should not be used within a
-- 'mask'.
--
-- > uninterruptibleMask = Control.Monad.Catch.uninterruptibleMask
uninterruptibleMask :: ((forall a. m a -> m a) -> m b) -> m b
uninterruptibleMask = Ca.uninterruptibleMask
-- | Runs its argument, just as if the @_concNoTest@ weren't there.
--
-- This function is purely for testing purposes, and indicates that
-- it's not worth considering more than one schedule here. This is
-- useful if you have some larger computation built up out of
-- subcomputations which you have already got tests for: you only
-- want to consider what's unique to the large component.
--
-- The test runner will report a failure if the argument fails.
--
-- Note that inappropriate use of @_concNoTest@ can actually
-- /suppress/ bugs! For this reason it is recommended to use it only
-- for things which don't make use of any state from a larger
-- scope. As a rule-of-thumb: if you can't define it as a top-level
-- function taking no @CVRef@, @CVar@, or @CTVar@ arguments, you
-- probably shouldn't @_concNoTest@ it.
--
-- > _concNoTest x = x
_concNoTest :: m a -> m a
_concNoTest = id
-- | Does nothing.
--
-- This function is purely for testing purposes, and indicates that
-- the thread has a reference to the provided @CVar@ or
-- @CTVar@. This function may be called multiple times, to add new
-- knowledge to the system. It does not need to be called when
-- @CVar@s or @CTVar@s are created, these get recorded
-- automatically.
--
-- Gathering this information allows detection of cases where the
-- main thread is blocked on a variable no runnable thread has a
-- reference to, which is a deadlock situation.
--
-- > _concKnowsAbout _ = return ()
_concKnowsAbout :: Either (CVar m a) (CTVar (STMLike m) a) -> m ()
_concKnowsAbout _ = return ()
-- | Does nothing.
--
-- The counterpart to '_concKnowsAbout'. Indicates that the
-- referenced variable will never be touched again by the current
-- thread.
--
-- Note that inappropriate use of @_concForgets@ can result in false
-- positives! Be very sure that the current thread will /never/
-- refer to the variable again, for instance when leaving its scope.
--
-- > _concForgets _ = return ()
_concForgets :: Either (CVar m a) (CTVar (STMLike m) a) -> m ()
_concForgets _ = return ()
-- | Does nothing.
--
-- Indicates to the test runner that all variables which have been
-- passed in to this thread have been recorded by calls to
-- '_concKnowsAbout'. If every thread has called '_concAllKnown',
-- then detection of nonglobal deadlock is turned on.
--
-- If a thread receives references to @CVar@s or @CTVar@s in the
-- future (for instance, if one was sent over a channel), then
-- '_concKnowsAbout' should be called immediately, otherwise there
-- is a risk of identifying false positives.
--
-- > _concAllKnown = return ()
_concAllKnown :: m ()
_concAllKnown = return ()
instance MonadConc IO where
type STMLike IO = STM
type CVar IO = MVar
type CRef IO = IORef
type ThreadId IO = C.ThreadId
readCVar = readMVar
fork = forkIO
forkWithUnmask = C.forkIOWithUnmask
forkOn = C.forkOn
getNumCapabilities = C.getNumCapabilities
myThreadId = C.myThreadId
throwTo = C.throwTo
newEmptyCVar = newEmptyMVar
putCVar = putMVar
tryPutCVar = tryPutMVar
takeCVar = takeMVar
tryTakeCVar = tryTakeMVar
newCRef = newIORef
readCRef = readIORef
modifyCRef = atomicModifyIORef
atomically = S.atomically
-- | Create a concurrent computation for the provided action, and
-- return a @CVar@ which can be used to query the result.
spawn :: MonadConc m => m a -> m (CVar m a)
spawn ma = do
cvar <- newEmptyCVar
_ <- fork $ _concKnowsAbout (Left cvar) >> ma >>= putCVar cvar
return cvar
-- | Fork a thread and call the supplied function when the thread is
-- about to terminate, with an exception or a returned value. The
-- function is called with asynchronous exceptions masked.
--
-- This function is useful for informing the parent when a child
-- terminates, for example.
forkFinally :: MonadConc m => m a -> (Either SomeException a -> m ()) -> m (ThreadId m)
forkFinally action and_then =
mask $ \restore ->
fork $ Ca.try (restore action) >>= and_then
-- | Raise the 'ThreadKilled' exception in the target thread. Note
-- that if the thread is prepared to catch this exception, it won't
-- actually kill it.
killThread :: MonadConc m => ThreadId m -> m ()
killThread tid = throwTo tid ThreadKilled
-------------------------------------------------------------------------------
-- Transformer instances
instance MonadConc m => MonadConc (ReaderT r m) where
type STMLike (ReaderT r m) = STMLike m
type CVar (ReaderT r m) = CVar m
type CRef (ReaderT r m) = CRef m
type ThreadId (ReaderT r m) = ThreadId m
fork = reader fork
forkOn i = reader (forkOn i)
forkWithUnmask ma = ReaderT $ \r -> forkWithUnmask (\f -> runReaderT (ma $ reader f) r)
_concNoTest = reader _concNoTest
getNumCapabilities = lift getNumCapabilities
myThreadId = lift myThreadId
throwTo t = lift . throwTo t
newEmptyCVar = lift newEmptyCVar
readCVar = lift . readCVar
putCVar v = lift . putCVar v
tryPutCVar v = lift . tryPutCVar v
takeCVar = lift . takeCVar
tryTakeCVar = lift . tryTakeCVar
newCRef = lift . newCRef
readCRef = lift . readCRef
modifyCRef r = lift . modifyCRef r
atomically = lift . atomically
_concKnowsAbout = lift . _concKnowsAbout
_concForgets = lift . _concForgets
_concAllKnown = lift _concAllKnown
reader :: Monad m => (m a -> m b) -> ReaderT r m a -> ReaderT r m b
reader f ma = ReaderT $ \r -> f (runReaderT ma r)
instance (MonadConc m, Monoid w) => MonadConc (WL.WriterT w m) where
type STMLike (WL.WriterT w m) = STMLike m
type CVar (WL.WriterT w m) = CVar m
type CRef (WL.WriterT w m) = CRef m
type ThreadId (WL.WriterT w m) = ThreadId m
fork = writerlazy fork
forkOn i = writerlazy (forkOn i)
forkWithUnmask ma = lift $ forkWithUnmask (\f -> fst `liftM` WL.runWriterT (ma $ writerlazy f))
_concNoTest = writerlazy _concNoTest
getNumCapabilities = lift getNumCapabilities
myThreadId = lift myThreadId
throwTo t = lift . throwTo t
newEmptyCVar = lift newEmptyCVar
readCVar = lift . readCVar
putCVar v = lift . putCVar v
tryPutCVar v = lift . tryPutCVar v
takeCVar = lift . takeCVar
tryTakeCVar = lift . tryTakeCVar
newCRef = lift . newCRef
readCRef = lift . readCRef
modifyCRef r = lift . modifyCRef r
atomically = lift . atomically
_concKnowsAbout = lift . _concKnowsAbout
_concForgets = lift . _concForgets
_concAllKnown = lift _concAllKnown
writerlazy :: (Monad m, Monoid w) => (m a -> m b) -> WL.WriterT w m a -> WL.WriterT w m b
writerlazy f ma = lift . f $ fst `liftM` WL.runWriterT ma
instance (MonadConc m, Monoid w) => MonadConc (WS.WriterT w m) where
type STMLike (WS.WriterT w m) = STMLike m
type CVar (WS.WriterT w m) = CVar m
type CRef (WS.WriterT w m) = CRef m
type ThreadId (WS.WriterT w m) = ThreadId m
fork = writerstrict fork
forkOn i = writerstrict (forkOn i)
forkWithUnmask ma = lift $ forkWithUnmask (\f -> fst `liftM` WS.runWriterT (ma $ writerstrict f))
_concNoTest = writerstrict _concNoTest
getNumCapabilities = lift getNumCapabilities
myThreadId = lift myThreadId
throwTo t = lift . throwTo t
newEmptyCVar = lift newEmptyCVar
readCVar = lift . readCVar
putCVar v = lift . putCVar v
tryPutCVar v = lift . tryPutCVar v
takeCVar = lift . takeCVar
tryTakeCVar = lift . tryTakeCVar
newCRef = lift . newCRef
readCRef = lift . readCRef
modifyCRef r = lift . modifyCRef r
atomically = lift . atomically
_concKnowsAbout = lift . _concKnowsAbout
_concForgets = lift . _concForgets
_concAllKnown = lift _concAllKnown
writerstrict :: (Monad m, Monoid w) => (m a -> m b) -> WS.WriterT w m a -> WS.WriterT w m b
writerstrict f ma = lift . f $ fst `liftM` WS.runWriterT ma
instance MonadConc m => MonadConc (SL.StateT s m) where
type STMLike (SL.StateT s m) = STMLike m
type CVar (SL.StateT s m) = CVar m
type CRef (SL.StateT s m) = CRef m
type ThreadId (SL.StateT s m) = ThreadId m
fork = statelazy fork
forkOn i = statelazy (forkOn i)
forkWithUnmask ma = SL.StateT $ \s -> (\a -> (a,s)) `liftM` forkWithUnmask (\f -> SL.evalStateT (ma $ statelazy f) s)
_concNoTest = statelazy _concNoTest
getNumCapabilities = lift getNumCapabilities
myThreadId = lift myThreadId
throwTo t = lift . throwTo t
newEmptyCVar = lift newEmptyCVar
readCVar = lift . readCVar
putCVar v = lift . putCVar v
tryPutCVar v = lift . tryPutCVar v
takeCVar = lift . takeCVar
tryTakeCVar = lift . tryTakeCVar
newCRef = lift . newCRef
readCRef = lift . readCRef
modifyCRef r = lift . modifyCRef r
atomically = lift . atomically
_concKnowsAbout = lift . _concKnowsAbout
_concForgets = lift . _concForgets
_concAllKnown = lift _concAllKnown
statelazy :: Monad m => (m a -> m b) -> SL.StateT s m a -> SL.StateT s m b
statelazy f ma = SL.StateT $ \s -> (\b -> (b,s)) `liftM` f (SL.evalStateT ma s)
instance MonadConc m => MonadConc (SS.StateT s m) where
type STMLike (SS.StateT s m) = STMLike m
type CVar (SS.StateT s m) = CVar m
type CRef (SS.StateT s m) = CRef m
type ThreadId (SS.StateT s m) = ThreadId m
fork = statestrict fork
forkOn i = statestrict (forkOn i)
forkWithUnmask ma = SS.StateT $ \s -> (\a -> (a,s)) `liftM` forkWithUnmask (\f -> SS.evalStateT (ma $ statestrict f) s)
_concNoTest = statestrict _concNoTest
getNumCapabilities = lift getNumCapabilities
myThreadId = lift myThreadId
throwTo t = lift . throwTo t
newEmptyCVar = lift newEmptyCVar
readCVar = lift . readCVar
putCVar v = lift . putCVar v
tryPutCVar v = lift . tryPutCVar v
takeCVar = lift . takeCVar
tryTakeCVar = lift . tryTakeCVar
newCRef = lift . newCRef
readCRef = lift . readCRef
modifyCRef r = lift . modifyCRef r
atomically = lift . atomically
_concKnowsAbout = lift . _concKnowsAbout
_concForgets = lift . _concForgets
_concAllKnown = lift _concAllKnown
statestrict :: Monad m => (m a -> m b) -> SS.StateT s m a -> SS.StateT s m b
statestrict f ma = SS.StateT $ \s -> (\b -> (b,s)) `liftM` f (SS.evalStateT ma s)
instance (MonadConc m, Monoid w) => MonadConc (RL.RWST r w s m) where
type STMLike (RL.RWST r w s m) = STMLike m
type CVar (RL.RWST r w s m) = CVar m
type CRef (RL.RWST r w s m) = CRef m
type ThreadId (RL.RWST r w s m) = ThreadId m
fork = rwslazy fork
forkOn i = rwslazy (forkOn i)
forkWithUnmask ma = RL.RWST $ \r s -> (\a -> (a,s,mempty)) `liftM` forkWithUnmask (\f -> fst `liftM` RL.evalRWST (ma $ rwslazy f) r s)
_concNoTest = rwslazy _concNoTest
getNumCapabilities = lift getNumCapabilities
myThreadId = lift myThreadId
throwTo t = lift . throwTo t
newEmptyCVar = lift newEmptyCVar
readCVar = lift . readCVar
putCVar v = lift . putCVar v
tryPutCVar v = lift . tryPutCVar v
takeCVar = lift . takeCVar
tryTakeCVar = lift . tryTakeCVar
newCRef = lift . newCRef
readCRef = lift . readCRef
modifyCRef r = lift . modifyCRef r
atomically = lift . atomically
_concKnowsAbout = lift . _concKnowsAbout
_concForgets = lift . _concForgets
_concAllKnown = lift _concAllKnown
rwslazy :: (Monad m, Monoid w) => (m a -> m b) -> RL.RWST r w s m a -> RL.RWST r w s m b
rwslazy f ma = RL.RWST $ \r s -> (\b -> (b,s,mempty)) `liftM` f (fst `liftM` RL.evalRWST ma r s)
instance (MonadConc m, Monoid w) => MonadConc (RS.RWST r w s m) where
type STMLike (RS.RWST r w s m) = STMLike m
type CVar (RS.RWST r w s m) = CVar m
type CRef (RS.RWST r w s m) = CRef m
type ThreadId (RS.RWST r w s m) = ThreadId m
fork = rwsstrict fork
forkOn i = rwsstrict (forkOn i)
forkWithUnmask ma = RS.RWST $ \r s -> (\a -> (a,s,mempty)) `liftM` forkWithUnmask (\f -> fst `liftM` RS.evalRWST (ma $ rwsstrict f) r s)
_concNoTest = rwsstrict _concNoTest
getNumCapabilities = lift getNumCapabilities
myThreadId = lift myThreadId
throwTo t = lift . throwTo t
newEmptyCVar = lift newEmptyCVar
readCVar = lift . readCVar
putCVar v = lift . putCVar v
tryPutCVar v = lift . tryPutCVar v
takeCVar = lift . takeCVar
tryTakeCVar = lift . tryTakeCVar
newCRef = lift . newCRef
readCRef = lift . readCRef
modifyCRef r = lift . modifyCRef r
atomically = lift . atomically
_concKnowsAbout = lift . _concKnowsAbout
_concForgets = lift . _concForgets
_concAllKnown = lift _concAllKnown
rwsstrict :: (Monad m, Monoid w) => (m a -> m b) -> RS.RWST r w s m a -> RS.RWST r w s m b
rwsstrict f ma = RS.RWST $ \r s -> (\b -> (b,s,mempty)) `liftM` f (fst `liftM` RS.evalRWST ma r s)
|
bitemyapp/dejafu
|
Control/Monad/Conc/Class.hs
|
mit
| 21,777
| 0
| 16
| 5,481
| 5,039
| 2,707
| 2,332
| 293
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Document.Internal where
import Data.Default (def)
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Functor.Identity
import qualified Data.Text.Lazy as L
import Data.Time.Clock
import Data.Time.ISO8601 (parseISO8601)
import Text.Blaze.Html (Html)
import Text.Markdown (markdown, MarkdownSettings(..))
import Text.Parsec
import Text.Parsec.Perm
type Fields = (T.Text, T.Text, T.Text, UTCTime, [T.Text])
fields :: ParsecT String u Identity Fields
fields = permute (tuple <$$> title
<|?> ("", slug)
<|?> ("", disqusId)
<||> posted
<|?> ([], tags))
where
tuple a b c d e = (a, b, c, d, e)
title :: ParsecT String u Identity T.Text
title = fmap T.pack $ try $ (string "Title: ") >> singleLine
slug :: ParsecT String u Identity T.Text
slug = try $ do
string "Slug: "
let slugChar = alphaNum <|> char '-' <|> char '_'
<?> "URL-friendly string: alphanumerics, -, or _"
fmap T.pack $ manyTill slugChar (char '\n')
disqusId :: ParsecT String u Identity T.Text
disqusId = fmap T.pack $ try $ (string "DisqusId: ") >> singleLine
posted :: ParsecT String u Identity UTCTime
posted = try $ do
string "Posted: "
postedAt <- singleLine
case parseISO8601 postedAt of
Just x -> return x
Nothing -> unexpected "Posted date must be an ISO 8601 datetime"
tags :: ParsecT String u Identity [T.Text]
tags = try $ do
string "Tags:\n"
fmap (map T.pack) $ many $ (string " ") >> singleLine
aboveFold :: ParsecT String u Identity Html
aboveFold = do
let dashes = many1 $ char '-'
separator = dashes >> string "8<" >> dashes >> char '\n'
above <- manyTill singleLine $ try separator
return $ md $ L.pack $ unlines above
belowFold :: ParsecT String u Identity Html
belowFold = fmap (md . L.pack . unlines) $ many1 singleLine
singleLine :: ParsecT String u Identity String
singleLine = manyTill anyChar (char '\n')
slugify :: T.Text -> T.Text
slugify = T.filter (`S.member` legalChars) . T.map despace . T.toLower
where despace ' ' = '-'
despace x = x
legalChars = S.fromList $ '-' : ['0'..'9'] ++ "_" ++ ['a'..'z']
md :: L.Text -> Html
md = markdown $ def { msXssProtect = False }
|
ErinCall/bloge
|
src/Document/Internal.hs
|
mit
| 2,511
| 0
| 14
| 716
| 829
| 437
| 392
| 60
| 2
|
-- Built for xmonad v.0.13
-- Author: Martin "kluvin" Kleiven
-- Licensed under MIT
--
-- The following imports' documentation along with usage examples and etc
-- can be looked up at http://xmonad.org/xmonad-docs/xmonad-contrib/
--
import XMonad
import XMonad.StackSet as W
import XMonad.Actions.Navigation2D
import XMonad.Actions.UpdatePointer
import XMonad.Actions.CycleWS
import XMonad.Layout.Spacing
import XMonad.Layout.Reflect
import XMonad.Layout.MultiToggle
import XMonad.Layout.BinarySpacePartition
import XMonad.Hooks.ManageDocks
import XMonad.Util.EZConfig
myTerminal = "termite"
myWorkspaces = ["Web", "Web-2", "Code", "Code-etc",
"Music", "etc-terms", "IM"] ++ map show [8..9]
-- Default Layouts
myLayout = avoidStruts $
spacingWithEdge 0 $
mkToggle (single REFLECTX) $
mkToggle (single REFLECTY) $
(emptyBSP ||| Full) -- Layouts
-- Make cursor follow focused window, center
myLogHook = updatePointer (0.5, 0.5) (0, 0)
-- Make focused window follow cursor
myFocusFollowsMouse = True
-- No borders, we have visual feedback by the position of the cursor
myBorderWidth = 0
-- Make default Mod key the 'windows', or 'super', key
myModMask = mod4Mask
-- Keybindings to remove from the default config
myRemovedKeys = [ "M-<Space>"
, "M-<Return>"
, "M-S-c"
]
-- Keybindings to add
myAdditionalKeys = [ ("M-x w", spawn "firefox")
, ("M-<Space>", spawn "rofi -show run")
, ("M-l", spawn "shlock")
, ("M-<Return>", spawn myTerminal)
, ("M-c", kill)
, ("M-a", swapNextScreen)
, ("M-g", windows W.swapMaster)
, ("M-b", sendMessage Balance)
, ("M-e", sendMessage Equalize)
, ("M-r x", sendMessage $ Toggle REFLECTX)
, ("M-r y", sendMessage $ Toggle REFLECTY)
, ("M-]", incSpacing (-5))
, ("M-[", incSpacing 5)
]
-- Load xmonad with the defaults we have specified
main = xmonad $ docks $ navigation2DP def
("<Up>", "<Left>", "<Down>", "<Right>")
[("M-", windowGo ),
("M-S-", windowSwap)]
False
$ def
-- simple stuff
{ terminal = myTerminal
, focusFollowsMouse = myFocusFollowsMouse
, borderWidth = myBorderWidth
, modMask = myModMask
, XMonad.workspaces = myWorkspaces
-- hooks, layouts
, logHook = myLogHook
, layoutHook = myLayout
} `removeKeysP` myRemovedKeys
`additionalKeysP` myAdditionalKeys
|
kluvin/dotfiles
|
xmonad/.xmonad/xmonad.hs
|
mit
| 3,151
| 0
| 11
| 1,253
| 512
| 314
| 198
| 54
| 1
|
{-# LANGUAGE PackageImports #-}
{-# OPTIONS_GHC -fno-warn-dodgy-exports -fno-warn-unused-imports #-}
-- | Reexports "Data.Either.Compat"
-- from a globally unique namespace.
module Data.Either.Compat.Repl (
module Data.Either.Compat
) where
import "this" Data.Either.Compat
|
haskell-compat/base-compat
|
base-compat/src/Data/Either/Compat/Repl.hs
|
mit
| 276
| 0
| 5
| 31
| 28
| 21
| 7
| 5
| 0
|
{-# LANGUAGE TupleSections #-}
module TextlunkyParser(
parseInput
)
where
import Data.List.Split
import Control.Applicative hiding((<|>))
import Types.TextlunkyCommand
import Data.Direction
import Types.Synonyms
import Data.Vectors(Vector3(..))
import qualified Data.Map as M
import Control.Monad.Trans.Free
import Control.Monad.Identity
import Control.Monad.Trans
import Control.Applicative
import Data.Maybe
import Data.List
-- NB. check BINARY commands first, then unary ones.
-- | Binary:
-- | - Move - Direction - eg. "move north"
-- | - Look - Direction - eg. "look left" "look north"
-- | - Throw - Direction - eg. "throw north" "throw up"
-- | - ShootD - Direction - eg. "shoot right" "shoot north"
-- | - MoveTo - Entity - eg. "moveTo shotgun" "moveTo spike pit"
-- | - Pickup - (Maybe Entity) - eg. "pickup shotgun" "pickup" "pickup damsel"
-- | - DropItem - (Maybe Entity) - eg. "drop" "drop gun" "drop rock"
-- | - Jump - (Maybe Enemy) - eg. "jump" "jump on spider" "jump over spike pit" (maybe)
-- | - Attack - (Maybe Enemy) - eg. "attack" "attack spider" "kill snake"
-- | - ShootE - Enemy - eg. "shoot" "shoot cobra"
-- | - Bomb - (Maybe Direction) - eg. "bomb" "place bomb" "bomb left wall"
-- | This is all that really matters to the rest of the application
parseInput :: String -> Textlunky ()
parseInput = parseCommands . getCommands
getCommands :: String -> [[String]]
getCommands = splitOneOf combine . splitOn " "
parseUnary :: [String] -- Possible Command List
-> (() -> TextlunkyCommand ()) -- Unary Command
-> [String] -- User Command List
-> Maybe (Textlunky ()) -- Response
parseUnary cmdList cmd xs =
case any (`elem` cmdList) xs of
True -> Just $ liftF $ cmd ()
_ -> Nothing
parseDirectionBinary :: [String]
-> (Direction -> () -> TextlunkyCommand ())
-> [String]
-> Maybe (Textlunky ())
parseDirectionBinary cmdList cmd xs =
case any (`elem` cmdList) xs of
True -> case parseDirection xs of
Just dir -> Just $ liftF $ cmd dir ()
_ -> Nothing
_ -> Nothing
-- find the first direction mentioned in a command string
parseDirection :: [String] -> Maybe Direction
parseDirection xs =
case filter isJust dirs of
[] -> Nothing
(x:_) -> x
where dirs = map (flip M.lookup directionMap) xs
{- ************ START PARSERS ************** -}
-- 0-ary parser
parseEnd xs = if any (`elem` end) xs
then Just (liftF End)
else Nothing
-- Unary parsers
parseYOLO = parseUnary ["yolo"] YOLO
parseDropItem = parseUnary dropItem DropItem
parsePickupU = parseUnary pickup (Pickup Nothing)
parseJumpU = parseUnary jump (Jump Nothing)
parseAttackU = parseUnary attack (Attack Nothing)
parseRope = parseUnary rope Rope
parseExitLevel = parseUnary leave ExitLevel
parseShowRoom = parseUnary showRoom ShowFull
parseShowEnts = parseUnary showEnts ShowEntities
parseWalls = parseUnary showWall Walls
parseMe = parseUnary me ShowMe
-- kill self if user doesn't specify what to shoot
parseShootSelf xs = parseUnary shoot ShootSelf xs
<|> parseUnary attack ShootSelf xs
<|> parseUnary shootself ShootSelf xs
parseDropDown xs = case "drop" `elem` xs of
True -> case "down" `elem` xs of
True -> Just $ liftF $ DropDown ()
_ -> Nothing
_ -> case any (`elem` dropDown) xs of
True -> Just $ liftF $ DropDown ()
_ -> Nothing
where dropDown = ["fall", "godown"]
-- check for desire to open gold chest
parseOpenChest xs = case any (`elem` open) xs of
True -> case "gold" `elem` xs of
True -> Just $ liftF $ OpenGoldChest ()
_ -> Just $ liftF $ OpenChest ()
_ -> Nothing
-- Binary (Direction) Parsers
-- TODO: Enemy and Entity parsers
parseMoveB = parseDirectionBinary move Move
parseShootB xs = parseDirectionBinary shoot ShootD xs
<|> parseDirectionBinary attack ShootD xs
parseLook = parseDirectionBinary look Look
parseThrow = parseDirectionBinary throw Throw
parseBombB xs = case any (== "bomb") xs of
True -> Just $ liftF $ Bomb (parseDirection xs) ()
_ -> Nothing
-- @TODO: Make this more obvious, moveto nw should go to nw corner
-- ...etc.
parseMoveTo xs = case dirs of
ds@[x, y, z] -> let [x', y', z'] = map (fromJust . flip M.lookup directionMap) ds
in case toVector3 (x', y', z') of
Just v -> Just $ liftF $ MoveTo v ()
_ -> Nothing
_ -> Nothing
where dirs = filter (`elem` directions) xs
parseCommands :: [[String]] -> Textlunky ()
parseCommands [] = return ()
parseCommands (x:xs) =
case parseCommand x of
Just f -> do f
parseCommands xs
_ -> parseCommands xs
--TODO: Parse Enemy and Entity actions
parseCommand :: [String] -> Maybe (Textlunky ())
parseCommand xs = foldr1 (<|>)
. map ($ xs)
$ [ parseMe ,
parseMoveB ,
parseMoveTo ,
parseShootB ,
parseLook ,
parseDropDown ,
parseThrow ,
parseBombB ,
parseDropItem ,
parseShowRoom ,
parsePickupU ,
parseJumpU ,
parseAttackU ,
parseShowEnts ,
parseWalls ,
parseRope ,
parseShootSelf,
parseExitLevel,
parseOpenChest,
parseEnd ,
parseYOLO ]
{- ************ END PARSERS ************** -}
{- ************ START COMMAND LISTS ************** -}
me = ["me", "stats", "items", "my", "collection"]
move = ["move", "m", "walk", "go", "mv"]
moveTo = ["move to", "go to", "mvto", "goto"]
pickup = ["pickup", "take", "grab"]
dropItem = ["drop", "put down"]
jump = ["jump", "jmp", "leap"]
attack = ["attack", "kill", "murder", "destroy"]
shoot = ["shoot", "fire"]
shootself = ["die", "killself"]
throw = ["throw", "chuck", "toss"]
rope = ["rope", "throwrope"]
bomb = ["bomb"]
open = ["open", "chest", "openchest", "getchest"]
leave = ["leave", "exit", "finish", "end"]
dropDown = ["drop", "dropdown", "fall", "hole"]
look = ["look", "view", "peek", "search", "examine"]
combine = ["&", "and", "then", "."] -- | Process many commands at once
end = ["end", "quit"] -- | For completeness
showWall = ["walls", "lookwalls"]
showEnts = ["stuff", "entities", "contents"]
showRoom = ["show", "search", "room", "look", "view", "examine"]
north = ["n", "north", "forward", "fw"]
south = ["s", "south", "backwards", "back", "bk"]
east = ["e", "east", "right", "r"]
west = ["w", "west", "left", "l"]
up = ["u", "up"]
down = ["d", "down"]
middle = ["middle", "mid", "m"]
-- | Available initial Commands
commands :: [String]
commands = concat [move, moveTo, pickup, dropItem, jump, attack, shoot,
throw, rope, bomb, open, leave, dropDown, look, end]
{- ************ END COMMAND LISTS ************** -}
-- | Corresponds to Direction
directions :: [String]
directions = concat [north, south, east, west, up, down, middle]
directionMap :: M.Map String Direction
directionMap = M.fromList $ dirs >>= (uncurry map)
where dirs = [ ((,N), north ),
((,S), south ),
((,E), east ),
((,W), west ),
((,U), up ),
((,D), down ),
((,M), middle) ]
-- | Unary:
-- | - ShootSelf - eg. "kill" "shoot" with no other keywords
-- | - Rope - eg. "rope" "throw rope" (note "rope" takes precedence over "throw")
-- | - OpenGoldChest - eg. "open gold chest" "open chest" (if no other chests in room)
-- | - OpenChest - eg. "open chest"
-- | - ExitLevel - eg. "exit" "leave" "finish" "go through door"
-- | - DropDown - eg. "fall" "go down" "drop down"
-- | - End (?) - only for continuity
-- | (with Nothing) - (no keywords to indicate otherwise)
-- | - DropItem - eg. "drop <item>" "drop"
-- | - Pickup - eg. "pick up" "take"
-- | - Jump - eg. "jump"
-- | - Attack - eg. "attack"
-- | Associates unary operations with their corresponding free action
unaryMap :: M.Map String (FreeT TextlunkyCommand Identity ())
unaryMap = M.fromList $ unaries >>= (uncurry map)
where unaries = [ ((,liftF (ShootSelf ())) , shootself ),
((,liftF (Rope ())) , rope ),
((,liftF (OpenChest ())) , open ),
((,liftF (ExitLevel ())) , leave ),
((,liftF (DropDown ())) , dropDown ),
((,liftF (DropItem ())) , dropItem ),
((,liftF (Pickup Nothing ())) , pickup ),
((,liftF (Jump Nothing ())) , jump ),
((,liftF (Attack Nothing ())) , attack ) ]
|
5outh/textlunky
|
src/TextlunkyParser.hs
|
mit
| 9,502
| 0
| 16
| 3,060
| 2,284
| 1,319
| 965
| 173
| 4
|
fsfactorial n = product [1..n]
{-
factorial 4
product [1..4]
product [1,2,3,4]
1*2*3*4
24
-}
fsproduct :: Num a => [a] -> a
fsproduct [] = 1
fsproduct (x:xs) = x * product xs
fsfactrec :: (Num a, Eq a) => a -> a
fsfactrec 0 = 1
fsfactrec n = n * fsfactrec (n - 1)
{-
product [1..n] == fsfactrec n
product [1,2,3,...,n-1,n] == n * fsfactrec n - 1 = n * n - 1 * ... * fsfactrec 0
1 * 2 * 3 * ... * (n-1) * n == n * (n-1) * ... * 3 * 2 * 1
-}
fsdrop 0 xs = xs
fsdrop _ [] = []
fsdrop n (x:xs) = fsdrop (n-1) xs
-- Exercise 1
fsand :: [Bool] -> Bool
fsand [] = True
fsand (x:xs)
| x = fsand xs
| otherwise = False
fsconcat :: [[a]] -> [a]
fsconcat [] = []
fsconcat (x:xs) = x ++ fsconcat xs
fsreplicate :: Int -> a -> [a]
fsreplicate 0 _ = []
fsreplicate n x = x:fsreplicate (n-1) x
fsindex :: [a] -> Int -> a
fsindex (x:xs) 0 = x
fsindex (x:xs) n = fsindex xs (n - 1)
fselem :: Eq a => a -> [a] -> Bool
fselem _ [] = False
fselem n (x:xs)
| n == x = True
| otherwise = fselem n xs
-- Exercise 2
fsmerge :: [Int] -> [Int] -> [Int]
fsmerge xs [] = xs
fsmerge [] ys = ys
fsmerge xo@(x:xs) yo@(y:ys)
| x <= y = x:fsmerge xs yo
| otherwise = y:fsmerge xo ys
-- Exercise 3
fsmsort :: [Int] -> [Int]
fsmsort [] = []
fsmsort [x] = [x]
fsmsort xs = fsmerge (fsmsort firstHalf) (fsmsort secondHalf)
where
(firstHalf, secondHalf) = splitAt mid xs
mid = length xs `div` 2
|
feliposz/learning-stuff
|
haskell/c9lectures-ch6.hs
|
mit
| 1,415
| 0
| 8
| 365
| 691
| 358
| 333
| 41
| 1
|
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module Gen.Expr
( exprGen
) where
import Gen.Core
import Gen.Literal ()
-- | Generates expressions.
exprGen :: Gen BasicExpr
exprGen = sized exprGen' where
exprGen' 0 = Fix <$> oneof [ liftM Literal arbitrary,
liftM Variable arbitrary ]
exprGen' n =
let n' = n `div` 2 in
let recGen = (exprGen' n') in
-- Types here are "small arbitrary" since we don't want humongous types.
Fix <$> oneof [
liftM3 BinaryOp arbitrary recGen recGen,
liftM2 UnaryOp arbitrary recGen,
-- Don't want to generate a conversion of a variable from a
-- named type, which is indistinguishable from a call. A type
-- of size 2 can never be a named type.
liftM2 Conversion (resize 2 arbitrary) recGen,
liftM2 Selector recGen arbitrary,
liftM2 Index recGen recGen,
-- First type of slice: no max, optional high and low
liftM4 Slice recGen
(maybeGen recGen)
(maybeGen recGen)
genNothing,
-- Second type of slice: optional low, required high and max
liftM4 Slice recGen
(maybeGen recGen)
(Just <$> recGen)
(Just <$> recGen),
liftM2 TypeAssertion (exprGen' 1) smallArbitrary,
-- Since a call with only a named type and no arguments looks
-- exactly like a call with one argument, we don't generate
-- calls with types. Those will be tested manually.
liftM3 Call recGen
genNothing
(vectorOf n' (exprGen' 0))]
instance Arbitrary BasicBinaryOp where
arbitrary = elements [ LogicalOr, LogicalAnd, Equal, NotEqual, LessThan
, LessThanEqual, GreaterThan, GreaterThanEqual, Plus, Minus, BitwiseOr
, BitwiseXor, Times, Divide, Modulo, ShiftLeft, ShiftRight, BitwiseAnd
, BitwiseAndNot ]
instance Arbitrary BasicUnaryOp where
arbitrary = elements [Positive, Negative, LogicalNot, BitwiseNot
, Dereference, Reference, Receive]
instance Arbitrary BasicExpr where
arbitrary = exprGen
|
djeik/goto
|
test/Gen/Expr.hs
|
mit
| 2,431
| 0
| 18
| 892
| 419
| 232
| 187
| 41
| 2
|
module Main where
import System.Environment
import GetDocs
import GetTypes
main :: IO ()
main = do
(mode:outputFormat:f:_) <- getArgs
case mode of
"docs" -> getDocs outputFormat f
"types" -> getTypes outputFormat f
_ -> putStrLn "Expected either docs or types + a filename"
|
deadfoxygrandpa/ElmEditorInfo
|
main.hs
|
mit
| 317
| 0
| 11
| 86
| 90
| 46
| 44
| 11
| 3
|
-- | In this module, we implement a decision procedure for observational
-- equivalence of programs of a very simple language. This language allows
-- programs of finitely-indexed, inductive and coinductive type.
-- A program consists of a definition block and a term, where a definition block
-- contains definitions of the form f : A = D for some symbol f, type A and
-- a body D. A body, in turn, is either of the form { ξ ↦ t } or
-- { π₁ ↦ t₁; π₂ ↦ t₂ } for terms t, t₁, t₂. These are copattern abstractions
-- á la Abel et al.
module DecideEquiv
(TyVar, SVar, Var, Type(..),
Idx(..), Term(..), prj, out, Body(..), Defs, Prog(..),
Pred, reduceCheck, reduce, Rel, bisimCand
)
where
import Data.Map as Map
import qualified Data.Set as Set
import Data.Set (Set)
import Control.Monad.Reader
import Control.Monad.Except
type TyVar = String
type SVar = String
type Var = String
-- | Possible types:
-- A ::= X | A + A | μX.A | A × A | νX.A
data Type = PT TyVar
| Sum Type Type
| Lfp TyVar Type
| Prod Type Type
| Gfp TyVar Type
deriving (Eq, Ord)
-- | subst a x b substitutes a for x in b. Assumption: a is closed.
subst :: Type -> TyVar -> Type -> Type
subst a x (PT y) = if x == y then a else PT y
subst a x (Sum b1 b2) = Sum (subst a x b1) (subst a x b2)
subst a x b@(Lfp y c) = if x == y then b else (Lfp y (subst a x c))
subst a x (Prod b1 b2) = Prod (subst a x b1) (subst a x b2)
subst a x b@(Gfp y c) = if x == y then b else (Gfp y (subst a x c))
-- | Index of coproduct injections and product projections
data Idx = L | R deriving (Eq, Ord)
instance Show Idx where
show L = "1"
show R = "2"
-- | Allowed terms:
-- t ::= f | κ₁ t | κ₂ t | α t | π₁ t | π₂ t | ξ t
-- where f is a symbol defined in a definition block,
-- κ₁ is the first coproduct injection, α the lfp injection,
-- π₁ the first product projection and ξ the gfp projection.
data Term = Sym SVar Type
| Inj Idx Term Type
| In Term Type
| Prj Idx Term Type
| Out Term Type
deriving (Eq, Ord)
getType :: Term -> Type
getType (Sym _ a) = a
getType (Inj _ _ a) = a
getType (In _ a) = a
getType (Prj _ _ a) = a
getType (Out _ a) = a
prj :: Idx -> Term -> Term
prj L t = case getType t of
Prod a1 _ -> Prj L t a1
_ -> error $ "Type error: applying projection to non-product type"
prj R t = case getType t of
Prod _ a2 -> Prj R t a2
_ -> error $ "Type error: applying projection to non-product type"
out :: Term -> Term
out t = case getType t of
Gfp x a -> Out t (subst (Gfp x a) x a)
_ -> error $ "Type error: applying ξ to non-gfp type"
-- | Body D of a definition f : A = D. Note that we allow only
-- one-layer copatterns for products and gfps.
data Body = ProdAbs Term Term
| GfpAbs Term
instance Show Body where
show (ProdAbs t1 t2) = "{π₁ ↦ " ++ show t1 ++ "; π₂ ↦ " ++ show t2 ++ "}"
show (GfpAbs t) = "{ξ ↦ " ++ show t ++ "}"
-- | Definition block that assigns to symbols f their type
-- and body.
type Defs = Map SVar (Type, Body)
-- | Programs are terms using symbols from a definition block.
data Prog = Prog Defs Term
------ Pretty printing ----
instance Show Type where
showsPrec _ (PT x) = showString x
showsPrec p (Sum a b) = showParen (p > 10) $
showsPrec 10 a .
showString " + " .
showsPrec 10 b
showsPrec p (Lfp x a) = showParen (p > 0) $
showString "μ" .
showString x .
showString ". " .
showsPrec 0 a
showsPrec p (Prod a b) = showParen (p > 10) $
showsPrec 11 a .
showString " × " .
showsPrec 11 b
showsPrec p (Gfp x a) = showParen (p > 0) $
showString "ν" .
showString x .
showString ". " .
showsPrec 0 a
subscriptIdx L = "₁"
subscriptIdx R = "₂"
instance Show Term where
showsPrec _ (Sym x _) = showString x
showsPrec p (Inj i t _) = showParen (p > 0) $
showString ("κ" ++ subscriptIdx i ++ " ") .
showsPrec 1 t
showsPrec p (In t _) = showParen (p > 0) $
showString "α " .
showsPrec 1 t
showsPrec p (Prj i t _) = showParen (p > 0) $
showString ("π" ++ subscriptIdx i ++ " ") .
showsPrec 1 t
showsPrec p (Out t _) = showParen (p > 0) $
showString "ξ " .
showsPrec 1 t
-- | Evaluation context into which we can put terms.
data EvCtx = PrjC Idx
| OutC
-- | Type-indexed predicates on terms.
type Pred = Map Type (Set Term)
inPred :: (Term, Type) -> Pred -> Bool
inPred (t, a) p =
case Map.lookup a p of
Nothing -> False
Just q -> t `Set.member` q
-- | Tries to reduce a term to PWHNF and tracks a predicate that
-- witnesses whether the given terms diverges under the reduction relation.
-- If this happens, we abort and return the predicate.
reduceCheck :: Defs -> Term -> Pred -> Either Pred Term
reduceCheck d t@(Sym f a) p =
if (t, a) `inPred` p then Left p else return t
reduceCheck d t@(Inj _ _ _) p = return t
reduceCheck d t@(In _ _) p = return t
reduceCheck d t@(Prj i r a) p = reduceCheckCoind d t a r p (PrjC i)
reduceCheck d t@(Out r a) p = reduceCheckCoind d t a r p OutC
reduceCheckCoind :: Defs -> Term -> Type -> Term -> Pred -> EvCtx ->
Either Pred Term
reduceCheckCoind d t a r p e =
if (t, a) `inPred` p
then Left p
else let p' = Map.insertWith (Set.union) a (Set.singleton t) p
in reduceCheckCoindCont d r p' e
where
reduceCheckCoindCont d r p' e =
do r' <- reduceCheck d r p'
case r' of
Sym f _ ->
let t' = reduceSym d f e
in reduceCheck d t' p'
_ -> error "Could not reduce to PWHNF"
reduceSym :: Defs -> SVar -> EvCtx -> Term
reduceSym d f (PrjC i) =
case Map.lookup f d of
Nothing -> error $ "Undefined symbol: " ++ f
Just (_, b) ->
case b of
ProdAbs t1 t2 ->
case i of
L -> t1
R -> t2
_ -> error $ "Typing error: projection applied to non-product term"
reduceSym d f OutC =
case Map.lookup f d of
Nothing -> error $ "Undefined symbol: " ++ f
Just (_, b) ->
case b of
GfpAbs t' -> t'
_ -> error $ "Typing error: tried to do transition from non-gfp term"
-- | Bring terms into principal weak head normal form, that is,
-- into "κ₁ t", "κ₁ t" or "α t" for inductive, and into "f" for coinductive
-- types. To achieve this, we contract applications of projections.
-- This function may fail if there is no PWHNF, which can be caused either by t
-- diverging or by a typing error.
reduce :: Defs -> Term -> Term
reduce d t =
case reduceCheck d t Map.empty of
Left _ -> error $ show t ++ " has no PWHNF since it diverges."
Right t' -> t'
-- | Type-indexed relations on terms.
type Rel = Map Type (Set (Term, Term))
-- | Tests that we can make on programs/terms.
data Test = Top
| Bot
| InjT Test Test
| InT Test
| PrjT Idx Test
| OutT Test
instance Show Test where
show Top = "⊤"
show Bot = "⟂"
show (InjT t1 t2) = "[" ++ show t1 ++ "," ++ show t2 ++ "]"
show (InT t) = "α⁻¹ " ++ show t
show (PrjT i t) = "[π" ++ subscriptIdx i ++ "]" ++ " " ++ show t
show (OutT t) = "[ξ]" ++ " " ++ show t
-- | While trying to build a bisimulation, can abort with an error or a test.
-- In the latter case, the given terms were not observationally equivalent.
data Abort = Error String
| InEquiv Test
deriving Show
-- | Internal monad for equivalence check.
type M a = ReaderT Defs (Either Abort) a
lookupSym :: SVar -> M Body
lookupSym f =
do r <- asks (Map.lookup f)
case r of
Nothing -> throwError $ Error $ "Unknown symbol " ++ f
Just (_, b) -> return b
-- | Once we found that two terms disagree at some point, we need to construct
-- test that witnesses this fact. While going up, we extend the found test to
-- account for the path we had to take to get to the point of disagreement.
updateTest :: (Test -> Test) -> M a -> M a
updateTest tc m =
catchError m (\e -> case e of
Error s -> throwError $ Error s
InEquiv t -> throwError $ InEquiv $ tc t)
-- | Checks whether the given terms are already related.
inBisim :: Type -> Term -> Term -> Rel -> Bool
inBisim a t1 t2 b =
case Map.lookup a b of
Nothing -> False
Just s -> Set.member (t1, t2) s
-- | Decide whether two terms t₁,t₂ : A are observationally equivalent, we
-- denote this by t₁ ~ t₂.
--
-- We assume that if t₁ and t₂ are related by b, then b is closed under term
-- derivations. For example, if t₁,t₂ : A₁ × A₂, then there are s₁,s₂ : A₁ with
-- π₁ tk ->> sk that are related by b. Analogously for the other types, details
-- are in the paper.
--
-- The procedure works as follows. Whenever we have a term in PWHNF, we check
-- whether it is already in the given relation and by assumption it is already
-- closed as bisimulation up-to convertibility.
-- Otherwise, we have three cases:
-- 1. Both terms are signature symbols. Since they are of the same type, both
-- must have a body for, say, gfps D₁ = { ξ ↦ s } and D₂ = { ξ ↦ r }.
-- Then we add (t₁,t₂) to b and check recursively s ~ r.
-- If this fails with a test φ, then we return the test [ξ] φ, otherwise the
-- resulting bisimulation.
-- Analogously, we proceed for product types.
-- 2. Both terms are of inductive type, say a coproduct, and in WHNF "κi s₁" and
-- "κi s₂". If i /= j, then t₁ /~ t₂ and we abort with the test [⊤, ⟂] that
-- distinguishes them. Otherwise, we add (t₁, t₂) to b and continue
-- recursively to check s₁ ~ s₂.
-- 3. The terms are not in PWHNF. Then we just reduce them to PWHNF and continue
-- from there.
createBisimCand :: Term -> Term -> Rel -> M Rel
createBisimCand t1@(Sym x a) t2@(Sym y _) b0 =
if inBisim a t1 t2 b0
then return b0
else do
bx <- lookupSym x
by <- lookupSym y
let b0' = Map.unionWith Set.union b0 $
Map.singleton a $ Set.singleton (t1, t2)
case (bx, by) of
(ProdAbs s1 s2, ProdAbs r1 r2) ->
do b1 <- proj L $ createBisimCand s1 r1 b0'
proj R $ createBisimCand s2 r2 b1
(GfpAbs s, GfpAbs r) ->
out $ createBisimCand s r b0'
_ -> throwError $ Error $
"Type error: " ++ show t1 ++ " vs. " ++ show t2
where
proj i = updateTest (PrjT i)
out = updateTest OutT
createBisimCand t1@(Inj i r1 a) t2@(Inj j r2 _) b0 =
if i == j
then if inBisim a t1 t2 b0
then return b0
else
let b0' = Map.unionWith Set.union b0 $
Map.singleton a $ Set.singleton (t1, t2)
in inj i $ createBisimCand r1 r1 b0'
else throwError $ InEquiv $ InjT Top Bot
where inj i = updateTest (\t -> case i of
L -> InjT t Bot
R -> InjT Bot t)
createBisimCand t1@(In s1 a) t2@(In s2 _) b0 =
if inBisim a t1 t2 b0
then return b0
else
let b0' = Map.unionWith Set.union b0 $
Map.singleton a $ Set.singleton (t1, t2)
in updateTest InT $ createBisimCand s1 s2 b0'
createBisimCand t1 t2 b0 =
do d <- ask
let t1' = reduce d t1
t2' = reduce d t2
createBisimCand t1' t2' b0
-- | If the given terms are observationally equivalent, then we return a
-- bisimulation up-to convertibility that relates these terms, otherwise we
-- abort with a test that distinguishes them.
bisimCand :: Defs -> Term -> Term -> Either Abort Rel
bisimCand d t1 t2 = runReaderT (createBisimCand t1 t2 Map.empty) d
|
hbasold/Sandbox
|
OTTTests/DecideEquiv.hs
|
mit
| 12,536
| 0
| 16
| 4,127
| 3,417
| 1,755
| 1,662
| 223
| 8
|
module Ridge.Reader where
import Control.Monad
import qualified Data.EDN as EDN
import qualified Data.ByteString.Lazy as BL
import Ridge.Types
readString :: BL.ByteString -> Maybe Object
readString = EDN.parseMaybe >=> (return . toObject)
|
gfredericks/ridge
|
Ridge/Reader.hs
|
epl-1.0
| 240
| 0
| 7
| 31
| 65
| 40
| 25
| 7
| 1
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE DeriveGeneric, OverloadedStrings #-}
module Buildsome.Db
( Db, with
, registeredOutputsRef, leakedOutputsRef
, InputDesc(..), FileDesc(..)
, OutputDesc(..)
, ExecutionLog(..), executionLog
, FileContentDescCache(..), fileContentDescCache
, Reason(..)
, IRef(..)
, MFileContentDesc, MakefileParseCache(..), makefileParseCache
) where
import Buildsome.BuildId (BuildId)
import qualified Crypto.Hash.MD5 as MD5
import Data.Binary (Binary(..))
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BS8
import Data.Default (def)
import Data.IORef
import Data.Map (Map)
import Data.Monoid ((<>))
import Data.Set (Set)
import qualified Data.Set as S
import Data.Time.Clock (DiffTime)
import Data.Time.Clock.POSIX (POSIXTime)
import qualified Database.LevelDB.Base as LevelDB
import GHC.Generics (Generic)
import Lib.Binary (encode, decode)
import Lib.Directory (catchDoesNotExist, createDirectories, makeAbsolutePath)
import Lib.Exception (bracket)
import qualified Lib.FSHook as FSHook
import Lib.FileDesc (FileContentDesc, FileModeDesc, FileStatDesc)
import Lib.FilePath (FilePath, (</>), (<.>))
import Lib.Makefile (Makefile)
import qualified Lib.Makefile as Makefile
import Lib.Makefile.Monad (PutStrLn)
import Lib.StdOutputs (StdOutputs(..))
import Lib.TimeInstances ()
import qualified System.Posix.ByteString as Posix
import Prelude.Compat hiding (FilePath)
schemaVersion :: ByteString
schemaVersion = "schema.ver.20"
data Db = Db
{ dbLevel :: LevelDB.DB
, dbRegisteredOutputs :: IORef (Set FilePath)
, dbLeakedOutputs :: IORef (Set FilePath)
}
data FileContentDescCache = FileContentDescCache
{ fcdcModificationTime :: POSIXTime
, fcdcFileContentDesc :: FileContentDesc
} deriving (Generic, Show)
instance Binary FileContentDescCache
data Reason
= BecauseSpeculative Reason
| BecauseHintFrom [FilePath]
| BecauseHooked FSHook.AccessDoc
| BecauseChildOfFullyRequestedDirectory Reason
| BecauseContainerDirectoryOfInput Reason FilePath
| BecauseContainerDirectoryOfOutput FilePath
| BecauseInput Reason FilePath
| BecauseRequested ByteString
deriving (Generic, Show)
instance Binary Reason
data InputDesc = InputDesc
{ idModeAccess :: Maybe (Reason, FileModeDesc)
, idStatAccess :: Maybe (Reason, FileStatDesc)
, idContentAccess :: Maybe (Reason, FileContentDesc)
} deriving (Generic, Show)
instance Binary InputDesc
data FileDesc ne e
= FileDescNonExisting ne
| FileDescExisting e
deriving (Generic, Eq, Ord, Show)
instance (Binary ne, Binary e) => Binary (FileDesc ne e)
data OutputDesc = OutputDesc
{ odStatDesc :: FileStatDesc
, odContentDesc :: Maybe FileContentDesc -- Nothing if directory
} deriving (Generic, Show)
instance Binary OutputDesc
data ExecutionLog = ExecutionLog
{ elBuildId :: BuildId
, elCommand :: ByteString -- Mainly for debugging
, elInputsDescs :: Map FilePath (FileDesc Reason (POSIXTime, InputDesc))
, elOutputsDescs :: Map FilePath (FileDesc () OutputDesc)
, elStdoutputs :: StdOutputs ByteString
, elSelfTime :: DiffTime
} deriving (Generic, Show)
instance Binary ExecutionLog
registeredOutputsRef :: Db -> IORef (Set FilePath)
registeredOutputsRef = dbRegisteredOutputs
leakedOutputsRef :: Db -> IORef (Set FilePath)
leakedOutputsRef = dbLeakedOutputs
setKey :: Binary a => Db -> ByteString -> a -> IO ()
setKey db key val = LevelDB.put (dbLevel db) def key $ encode val
getKey :: Binary a => Db -> ByteString -> IO (Maybe a)
getKey db key = fmap decode <$> LevelDB.get (dbLevel db) def key
deleteKey :: Db -> ByteString -> IO ()
deleteKey db = LevelDB.delete (dbLevel db) def
options :: LevelDB.Options
options =
LevelDB.defaultOptions
{ LevelDB.createIfMissing = True
, LevelDB.errorIfExists = False
}
withLevelDb :: FilePath -> (LevelDB.DB -> IO a) -> IO a
withLevelDb dbPath =
LevelDB.withDB (BS8.unpack (dbPath </> schemaVersion)) options
with :: FilePath -> (Db -> IO a) -> IO a
with rawDbPath body = do
dbPath <- makeAbsolutePath rawDbPath
createDirectories dbPath
withLevelDb dbPath $ \levelDb ->
withIORefFile (dbPath </> "outputs") $ \registeredOutputs ->
withIORefFile (dbPath </> "leaked_outputs") $ \leakedOutputs ->
body (Db levelDb registeredOutputs leakedOutputs)
where
withIORefFile path =
bracket (newIORef =<< decodeFileOrEmpty path) (writeBack path)
writeBack path ref = do
BS8.writeFile (BS8.unpack (path <.> "tmp")) .
BS8.unlines . S.toList =<< readIORef ref
Posix.rename (path <.> "tmp") path
decodeFileOrEmpty path =
(S.fromList . BS8.lines <$> BS8.readFile (BS8.unpack path))
`catchDoesNotExist` return S.empty
data IRef a = IRef
{ readIRef :: IO (Maybe a)
, writeIRef :: a -> IO ()
, delIRef :: IO ()
}
mkIRefKey :: Binary a => ByteString -> Db -> IRef a
mkIRefKey key db = IRef
{ readIRef = getKey db key
, writeIRef = setKey db key
, delIRef = deleteKey db key
}
executionLog :: Makefile.Target -> Db -> IRef ExecutionLog
executionLog target = mkIRefKey targetKey
where
targetKey = MD5.hash $ Makefile.targetInterpolatedCmds target
fileContentDescCache :: FilePath -> Db -> IRef FileContentDescCache
fileContentDescCache = mkIRefKey
type MFileContentDesc = FileDesc () FileContentDesc
data MakefileParseCache = MakefileParseCache
{ mpcInputs :: (FilePath, Map FilePath MFileContentDesc)
, mpcOutput :: (Makefile, [PutStrLn])
} deriving (Generic)
instance Binary MakefileParseCache
makefileParseCache :: Db -> Makefile.Vars -> IRef MakefileParseCache
makefileParseCache db vars =
mkIRefKey ("makefileParseCache_Schema.1:" <> MD5.hash (encode vars)) db
|
sinelaw/buildsome
|
src/Buildsome/Db.hs
|
gpl-2.0
| 5,924
| 0
| 16
| 1,141
| 1,711
| 953
| 758
| 145
| 1
|
module Type.CreateSprint
( CreateSprint (..)
) where
import Type.Core
import Type.Team (TeamIdent)
import Control.Monad.Reader (MonadReader, ask)
import qualified Type.Sprint as S (Sprint (..), SprintGeneric (..), Checkmark (..))
import Database.Persist.TH (derivePersistField)
data CreateSprint = CreateSprint
{ sprintPeople :: Int
, sprintWorkDays :: Int
, sprintVacationDays :: Int
, sprintInterruptHours :: Maybe Int
, sprintPlannedPoints :: Int
, sprintDeliveredPoints :: Maybe Int
} deriving (Eq, Generic, Show, Typeable)
instance JSONSchema CreateSprint where schema = gSchema
instance ToJSON CreateSprint
instance FromJSON CreateSprint
instance (MonadIO m, MonadReader TeamIdent m) => CreateAble m CreateSprint S.Sprint where
createFrom sprint = do
teamId <- ask
rid <- liftIO $ randomRid SprintR
return $ S.Sprint
{ S.sprintTeam = teamId
, S.sprintIdent = rid
, S.sprintNumber = 0 -- Don't know this yet
, S.sprintPeople = sprintPeople sprint
, S.sprintWorkDays = sprintWorkDays sprint
, S.sprintVacationDays = sprintVacationDays sprint
, S.sprintInterruptHours = sprintInterruptHours sprint
, S.sprintPlannedPoints = sprintPlannedPoints sprint
, S.sprintDeliveredPoints = sprintDeliveredPoints sprint
, S.sprintLatest = S.Inactive
}
|
orclev/sprint-logic-rest
|
Type/CreateSprint.hs
|
gpl-3.0
| 1,348
| 0
| 11
| 264
| 355
| 203
| 152
| -1
| -1
|
-- Copyright (C) 2013 Che-Liang Chiou.
module StringFilter (
Error(..),
FilterResult,
StringFilter,
runFilter,
withInput,
) where
import Control.Monad
newtype StringFilter resultType = StringFilter {
run :: StringFilterState -> Either Error (StringFilterState, resultType)
}
newtype StringFilterState = StringFilterState {
input :: String
} deriving (Show)
data Error = Err String
| NeedMoreInput
| NotMatch
deriving (Eq, Show)
type FilterResult resultType = Either Error (resultType, String)
runFilter :: StringFilter resultType -> String -> FilterResult resultType
runFilter packetFilter inputString =
fmap massage (run packetFilter $ StringFilterState inputString)
where massage (state, result) = (result, input state)
instance Monad StringFilter where
return result = StringFilter (\state -> Right (state, result))
fail message = StringFilter (\_ -> Left (Err message))
filter0 >>= makeFilter1 = StringFilter chainedFilter
where chainedFilter state0 =
case run filter0 state0 of
Right (state1, result) -> run (makeFilter1 result) state1
Left (Err reason) -> Left (Err reason)
Left NeedMoreInput -> Left NeedMoreInput
Left NotMatch -> Left NotMatch
instance MonadPlus StringFilter where
mzero = makeZero NotMatch
mplus filter0 filter1 = StringFilter chainedFilter
where chainedFilter state0 =
case run filter0 state0 of
success@(Right _) -> success
Left (Err reason) -> Left (Err reason)
Left NeedMoreInput -> Left NeedMoreInput
Left NotMatch -> run filter1 state0
makeZero :: Error -> StringFilter resultType
makeZero e = StringFilter (\_ -> Left e)
getState :: StringFilter StringFilterState
getState = StringFilter (\state -> Right (state, state))
putState :: StringFilterState -> StringFilter ()
putState state = StringFilter (\_ -> Right (state, ()))
withInput :: (String -> FilterResult resultType) -> StringFilter resultType
withInput func =
getState >>= \state ->
case func $ input state of
Right (result, rest) -> putState state{input=rest} >> return result
Left (Err reason) -> fail reason
Left NeedMoreInput -> makeZero NeedMoreInput
Left NotMatch -> makeZero NotMatch
|
clchiou/gwab
|
lib/StringFilter.hs
|
gpl-3.0
| 2,494
| 0
| 13
| 698
| 717
| 368
| 349
| 54
| 4
|
{-# LANGUAGE TypeFamilies, DeriveDataTypeable, FlexibleContexts, FlexibleInstances, TypeSynonymInstances #-}
module Main where
import Prelude (Int,undefined,Eq,Show,Ord,return,div)
import qualified Prelude as P
import Data.Typeable
import Hip.HipSpec
import Test.QuickCheck hiding (Prop)
import Control.Applicative
data ListP a = Cons a (ListP a) | Nil
deriving (Show,Eq,Ord,Typeable)
(++) :: ListP a -> ListP a -> ListP a
Cons x xs ++ ys = Cons x (xs ++ ys)
Nil ++ ys = ys
point :: a -> ListP a
point x = Cons x Nil
reverse :: ListP a -> ListP a
reverse (Cons x xs) = reverse xs ++ point x
reverse Nil = Nil
type List = ListP Int
prop_revrev :: ListP a -> ListP a -> Prop (ListP a)
prop_revrev xs ys = reverse xs ++ reverse ys =:= reverse (ys ++ xs)
prop_revinv :: ListP a -> Prop (ListP a)
prop_revinv xs = reverse (reverse xs) =:= xs
data SeqP a = NilS | NonNilS (NonNilSeqP a) deriving (Eq, Ord, Typeable)
(+++) :: SeqP a -> SeqP a -> SeqP a
NilS +++ x = x
x +++ NilS = x
NonNilS x +++ NonNilS y = NonNilS (x `Append` y)
prop_app :: SeqP a -> SeqP a -> Prop (ListP a)
prop_app x y = toList x ++ toList y =:= toList (x +++ y)
pointS :: a -> SeqP a
pointS x = NonNilS (Unit x)
prop_point :: a -> Prop (ListP a)
prop_point x = toList (pointS x) =:= point x
reverseS :: SeqP a -> SeqP a
reverseS NilS = NilS
reverseS (NonNilS x) = NonNilS (reverseSS x)
prop_reverse :: SeqP a -> Prop (ListP a)
prop_reverse x = toList (reverseS x) =:= reverse (toList x)
toList :: SeqP a -> ListP a
toList NilS = Nil
toList (NonNilS x) = toListS x
data NonNilSeqP a = Unit a | Append (NonNilSeqP a) (NonNilSeqP a) deriving (Eq, Ord, Typeable)
prop_unit :: a -> Prop (ListP a)
prop_unit x = toListS (Unit x) =:= point x
prop_appS :: NonNilSeqP a -> NonNilSeqP a -> Prop (ListP a)
prop_appS x y = toListS (x `Append` y) =:= toListS x ++ toListS y
reverseSS (Unit x) = Unit x
reverseSS (Append x y) = Append (reverseSS y) (reverseSS x)
prop_reverseSS :: NonNilSeqP a -> Prop (ListP a)
prop_reverseSS x = toListS (reverseSS x) =:= reverse (toListS x)
toListS :: NonNilSeqP a -> ListP a
toListS (Unit x) = point x
toListS (Append x y) = toListS x ++ toListS y
type Seq = SeqP Int
type NonNilSeq = NonNilSeqP Int
main = hipSpec "Lists.hs" conf 3
where conf = describe "Lists"
[ var "x" intType
, var "y" intType
, var "z" intType
, var "xs" seqType
, var "ys" seqType
, var "zs" seqType
, var "xs" seqSType
, var "ys" seqSType
, var "zs" seqSType
, var "xs" listType
, var "ys" listType
, var "zs" listType
, con "Nil" (Nil :: List)
, con "Cons" (Cons :: Int -> List -> List)
, con "point" (point :: Int -> List)
, con "++" ((++) :: List -> List -> List)
, con "reverse" (reverse :: List -> List)
, con "+++" ((+++) :: Seq -> Seq -> Seq)
, con "pointS" (pointS :: Int -> Seq)
, con "reverseS" (reverseS :: Seq -> Seq)
, con "Unit" (Unit :: Int -> NonNilSeq)
, con "Append" (Append :: NonNilSeq -> NonNilSeq -> NonNilSeq)
, con "reverseSS" (reverseSS :: NonNilSeq -> NonNilSeq)
, con "toList" (toList :: Seq -> List)
, con "toListS" (toListS :: NonNilSeq -> List)
]
where
intType = undefined :: Int
listType = undefined :: List
seqType = undefined :: Seq
seqSType = undefined :: NonNilSeq
instance Arbitrary List where
arbitrary = sized arbList
where
arbList s = frequency [(1,return Nil)
,(s,Cons <$> arbitrary <*> arbList (s `div` 2))
]
instance Classify List where
type Value List = List
evaluate = return
instance Arbitrary Seq where
arbitrary = sized arbSeqP
where
arbSeqP s = frequency [(1, return NilS),
(s, NonNilS <$> arbitrary)]
instance Classify Seq where
type Value Seq = Seq
evaluate = return
instance Arbitrary NonNilSeq where
arbitrary = sized arbSeqP
where
arbSeqP s = frequency [(1, Unit <$> arbitrary)
,(s, Append <$> arbSeqP (s `div` 2) <*> arbSeqP (s `div` 2))]
instance Classify NonNilSeq where
type Value NonNilSeq = NonNilSeq
evaluate = return
-- The tiny Hip Prelude
(=:=) = (=:=)
type Prop a = a
|
danr/hipspec
|
examples/old-examples/quickspec/Lists.hs
|
gpl-3.0
| 4,754
| 3
| 18
| 1,589
| 1,769
| 909
| 860
| 110
| 1
|
{-|
Description: Entry point for Courseography.
This module implements a 'main' method which takes a command-line
argument and executes the corresponding IO action.
If no argument is provided, the default action is 'server', which
starts the server.
-}
module Main where
import System.IO (stderr, hPutStrLn)
import System.Environment (getArgs)
import Data.Maybe (fromMaybe)
import Data.List (intercalate)
import qualified Data.Map.Strict as Map
-- internal dependencies
import Server (runServer)
import Database.Database (setupDatabase)
import Svg.Parser (parsePrebuiltSvgs)
import Css.Compiler (compileCSS)
import Util.Documentation (generateDocs)
-- | A map of command-line arguments to their corresponding IO actions.
taskMap :: Map.Map String (IO ())
taskMap = Map.fromList [
("server", runServer),
("database", setupDatabase),
("graphs", parsePrebuiltSvgs),
("css", compileCSS),
("docs", generateDocs)]
-- | Courseography entry point.
main :: IO ()
main = do
args <- getArgs
let taskName = if null args then "server" else head args
fromMaybe putUsage (Map.lookup taskName taskMap)
-- | Print usage message to user (when main gets an incorrect argument).
putUsage :: IO ()
putUsage = hPutStrLn stderr usageMsg
where
taskNames = Map.keys taskMap
usageMsg = "Unrecognized argument. Available arguments:\n" ++
intercalate "\n" taskNames
|
hermish/courseography
|
app/Main.hs
|
gpl-3.0
| 1,416
| 0
| 11
| 255
| 293
| 168
| 125
| 28
| 2
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
-- Module : Network.AWS.AutoScaling
-- Copyright : (c) 2013 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
-- | Auto Scaling is a web service designed to automatically launch or terminate
-- Amazon Elastic Compute Cloud (Amazon EC2) instances based on user-defined
-- policies, schedules, and health checks.
--
-- This service is used in conjunction with Amazon CloudWatch and
-- Elastic Load Balancing services.
module Network.AWS.AutoScaling
(
-- * Actions
-- ** CreateAutoScalingGroup
CreateAutoScalingGroup (..)
, CreateAutoScalingGroupResponse (..)
-- ** CreateLaunchConfiguration
, CreateLaunchConfiguration (..)
, CreateLaunchConfigurationResponse (..)
-- ** CreateOrUpdateTags
, CreateOrUpdateTags (..)
, CreateOrUpdateTagsResponse (..)
-- ** DeleteAutoScalingGroup
, DeleteAutoScalingGroup (..)
, DeleteAutoScalingGroupResponse (..)
-- ** DeleteLaunchConfiguration
, DeleteLaunchConfiguration (..)
, DeleteLaunchConfigurationResponse (..)
-- ** DeleteNotificationConfiguration
, DeleteNotificationConfiguration (..)
, DeleteNotificationConfigurationResponse (..)
-- ** DeletePolicy
, DeletePolicy (..)
, DeletePolicyResponse (..)
-- ** DeleteScheduledAction
, DeleteScheduledAction (..)
, DeleteScheduledActionResponse (..)
-- ** DeleteTags
, DeleteTags (..)
, DeleteTagsResponse (..)
-- ** DescribeAdjustmentTypes
, DescribeAdjustmentTypes (..)
, DescribeAdjustmentTypesResponse (..)
-- ** DescribeAutoScalingGroups
, DescribeAutoScalingGroups (..)
, DescribeAutoScalingGroupsResponse (..)
-- ** DescribeAutoScalingInstances
, DescribeAutoScalingInstances (..)
, DescribeAutoScalingInstancesResponse (..)
-- ** DescribeAutoScalingNotificationTypes
, DescribeAutoScalingNotificationTypes (..)
, DescribeAutoScalingNotificationTypesResponse (..)
-- ** DescribeLaunchConfigurations
, DescribeLaunchConfigurations (..)
, DescribeLaunchConfigurationsResponse (..)
-- ** DescribeMetricCollectionTypes
, DescribeMetricCollectionTypes (..)
, DescribeMetricCollectionTypesResponse (..)
-- ** DescribeNotificationConfigurations
, DescribeNotificationConfigurations (..)
, DescribeNotificationConfigurationsResponse (..)
-- ** DescribePolicies
, DescribePolicies (..)
, DescribePoliciesResponse (..)
-- ** DescribeScalingActivities
, DescribeScalingActivities (..)
, DescribeScalingActivitiesResponse (..)
-- ** DescribeScalingProcessTypes
, DescribeScalingProcessTypes (..)
, DescribeScalingProcessTypesResponse (..)
-- ** DescribeScheduledActions
, DescribeScheduledActions (..)
, DescribeScheduledActionsResponse (..)
-- ** DescribeTags
, DescribeTags (..)
, DescribeTagsResponse (..)
-- ** DescribeTerminationPolicyTypes
, DescribeTerminationPolicyTypes (..)
, DescribeTerminationPolicyTypesResponse (..)
-- ** DisableMetricsCollection
, DisableMetricsCollection (..)
, DisableMetricsCollectionResponse (..)
-- ** EnableMetricsCollection
, EnableMetricsCollection (..)
, EnableMetricsCollectionResponse (..)
-- ** ExecutePolicy
, ExecutePolicy (..)
, ExecutePolicyResponse (..)
-- ** PutNotificationConfiguration
, PutNotificationConfiguration (..)
, PutNotificationConfigurationResponse (..)
-- ** PutScalingPolicy
, PutScalingPolicy (..)
, PutScalingPolicyResponse (..)
-- ** PutScheduledUpdateGroupAction
, PutScheduledUpdateGroupAction (..)
, PutScheduledUpdateGroupActionResponse (..)
-- ** ResumeProcesses
, ResumeProcesses (..)
, ResumeProcessesResponse (..)
-- ** SetDesiredCapacity
, SetDesiredCapacity (..)
, SetDesiredCapacityResponse (..)
-- ** SetInstanceHealth
, SetInstanceHealth (..)
, SetInstanceHealthResponse (..)
-- ** SuspendProcesses
, SuspendProcesses (..)
, SuspendProcessesResponse (..)
-- ** TerminateInstanceInAutoScalingGroup
, TerminateInstanceInAutoScalingGroup (..)
, TerminateInstanceInAutoScalingGroupResponse (..)
-- ** UpdateAutoScalingGroup
, UpdateAutoScalingGroup (..)
, UpdateAutoScalingGroupResponse (..)
-- * Data Types
, module Network.AWS.AutoScaling.Types
-- * Common
, module Network.AWS
) where
import Data.Text (Text)
import Data.Time
import Network.AWS
import Network.AWS.AutoScaling.Types
import Network.AWS.Internal
import Network.HTTP.Types.Method
-- | Creates a new Auto Scaling group with the specified name and other
-- attributes. When the creation request is completed, the Auto Scaling group
-- is ready to be used in other calls. Note The Auto Scaling group name must
-- be unique within the scope of your AWS account.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_CreateAutoScalingGroup.html>
data CreateAutoScalingGroup = CreateAutoScalingGroup
{ casgAutoScalingGroupName :: !Text
-- ^ The name of the Auto Scaling group.
, casgAvailabilityZones :: Members AvailabilityZone
-- ^ A list of Availability Zones for the Auto Scaling group. This is
-- required unless you have specified subnets.
, casgDefaultCooldown :: Maybe Integer
-- ^ The amount of time, in seconds, between a successful scaling
-- activity and the succeeding scaling activity.
, casgDesiredCapacity :: Maybe Integer
-- ^ The number of Amazon EC2 instances that should be running in the
-- group. The desired capacity must be greater than or equal to the
-- minimum size and less than or equal to the maximum size specified
-- for the Auto Scaling group.
, casgHealthCheckGracePeriod :: Maybe Integer
-- ^ Length of time in seconds after a new Amazon EC2 instance comes
-- into service that Auto Scaling starts checking its health. During
-- this time any health check failure for the that instance is ignored.
, casgHealthCheckType :: Maybe Text
-- ^ The service you want the health checks from, Amazon EC2 or
-- Elastic Load Balancer. Valid values are EC2 or ELB.
, casgLaunchConfigurationName :: !Text
-- ^ The name of an existing launch configuration to use to launch new
-- instances.
, casgLoadBalancerNames :: Members Text
-- ^ A list of existing Elastic Load Balancing load balancers to use.
-- The load balancers must be associated with the AWS account.
, casgMaxSize :: !Integer
-- ^ The maximum size of the Auto Scaling group.
, casgMinSize :: !Integer
-- ^ The minimum size of the Auto Scaling group.
, casgPlacementGroup :: Maybe Text
-- ^ Physical location of an existing cluster placement group into
-- which you want to launch your instances. For information about
-- cluster placement group, see Using Cluster Instances
, casgTags :: Members Tag
-- ^ The tag to be created or updated. Each tag should be defined by
-- its resource type, resource ID, key, value, and a propagate flag.
-- Valid values: key=value, value=value, propagate=true or false.
-- Value and propagate are optional parameters.
, casgTerminationPolicies :: Members Text
-- ^ A standalone termination policy or a list of termination policies
-- used to select the instance to terminate. The policies are
-- executed in the order that they are listed.
, casgVPCZoneIdentifier :: Maybe Text
-- ^ A comma-separated list of subnet identifiers of Amazon Virtual
-- Private Clouds (Amazon VPCs).
} deriving (Eq, Show, Generic)
instance IsQuery CreateAutoScalingGroup
instance Rq CreateAutoScalingGroup where
type Er CreateAutoScalingGroup = AutoScalingErrorResponse
type Rs CreateAutoScalingGroup = CreateAutoScalingGroupResponse
request = query4 autoScaling GET "CreateAutoScalingGroup"
data CreateAutoScalingGroupResponse = CreateAutoScalingGroupResponse
{ casgrResponseMetadata :: !ResponseMetadata
} deriving (Eq, Show, Generic)
instance IsXML CreateAutoScalingGroupResponse where
xmlPickler = withNS autoScalingNS
-- | Creates a new launch configuration. The launch configuration name must be
-- unique within the scope of the client's AWS account.
--
-- The maximum limit of launch configurations, which by default is 100,
-- must not yet have been met; otherwise, the call will fail.
--
-- When created, the new launch configuration is available for immediate use.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_CreateLaunchConfiguration.html>
data CreateLaunchConfiguration = CreateLaunchConfiguration
{ clcBlockDeviceMappings :: Members BlockDeviceMapping
-- ^ A list of mappings that specify how block devices are exposed to
-- the instance. Each mapping is made up of a VirtualName, a
-- DeviceName, and an ebs data structure that contains information
-- about the associated Elastic Block Storage volume. For more
-- information about Amazon EC2 BlockDeviceMappings, go to Block
-- Device Mapping in the Amazon EC2 product documentation.
, clcEbsOptimized :: Maybe Bool
-- ^ Whether the instance is optimized for EBS I/O. The optimization
-- provides dedicated throughput to Amazon EBS and an optimized
-- configuration stack to provide optimal EBS I/O performance. This
-- optimization is not available with all instance types. Additional
-- usage charges apply when using an EBS Optimized instance. By
-- default the instance is not optimized for EBS I/O. For
-- information about EBS-optimized instances, go to EBS-Optimized
-- Instances in the Amazon Elastic Compute Cloud User Guide.
, clcIamInstanceProfile :: Maybe Text
-- ^ The name or the Amazon Resource Name (ARN) of the instance
-- profile associated with the IAM role for the instance.
, clcImageId :: !Text
-- ^ Unique ID of the Amazon Machine Image (AMI) you want to use to
-- launch your EC2 instances. For information about finding Amazon
-- EC2 AMIs, see Finding a Suitable AMI in the Amazon Elastic
-- Compute Cloud User Guide.
, clcInstanceMonitoring :: Maybe InstanceMonitoring
-- ^ Enables detailed monitoring if it is disabled. Detailed
-- monitoring is enabled by default.
, clcInstanceType :: !InstanceType
-- ^ The instance type of the Amazon EC2 instance. For information
-- about available Amazon EC2 instance types, see Available Instance
-- Types in the Amazon Elastic Cloud Compute User Guide.
, clcKernelId :: Maybe Text
-- ^ The ID of the kernel associated with the Amazon EC2 AMI.
, clcKeyName :: Maybe Text
-- ^ The name of the Amazon EC2 key pair. For more information, see
-- Getting a Key Pair in the Amazon Elastic Compute Cloud User Guide.
, clcLaunchConfigurationName :: !Text
-- ^ The name of the launch configuration to create.
, clcRamdiskId :: Maybe Text
-- ^ The ID of the RAM disk associated with the Amazon EC2 AMI.
, clcSecurityGroups :: Members Text
-- ^ The security groups with which to associate Amazon EC2 or Amazon
-- VPC instances.
, clcSpotPrice :: Maybe Text
-- ^ The maximum hourly price to be paid for any Spot Instance
-- launched to fulfill the request. Spot Instances are launched when
-- the price you specify exceeds the current Spot market price. For
-- more information on launching Spot Instances, see Using Auto
-- Scaling to Launch Spot Instances in the Auto Scaling Developer
-- Guide.
, clcUserData :: Maybe Text
-- ^ The user data to make available to the launched Amazon EC2
-- instances. For more information about Amazon EC2 user data, see
-- User Data Retrieval in the Amazon Elastic Compute Cloud User
-- Guide.
, clcClassicLinkVPCId :: Maybe Text
-- ^ The ID of a ClassicLink-enabled VPC to link the instances to.
, clcClassicLinkVPCSecurityGroups :: Members Text
-- ^ The IDs of one or more security groups for the specified
-- ClassicLink-enabled VPC.
} deriving (Eq, Show, Generic)
instance IsQuery CreateLaunchConfiguration
instance Rq CreateLaunchConfiguration where
type Er CreateLaunchConfiguration = AutoScalingErrorResponse
type Rs CreateLaunchConfiguration = CreateLaunchConfigurationResponse
request = query4 autoScaling GET "CreateLaunchConfiguration"
data CreateLaunchConfigurationResponse = CreateLaunchConfigurationResponse
{ clcrResponseMetadata :: !ResponseMetadata
} deriving (Eq, Show, Generic)
instance IsXML CreateLaunchConfigurationResponse where
xmlPickler = withNS autoScalingNS
-- | Creates new tags or updates existing tags for an Auto Scaling group. Note A
-- tag's definition is composed of a resource ID, resource type, key and
-- value, and the propagate flag. Value and the propagate flag are optional
-- parameters. See the Request Parameters for more information. For
-- information on creating tags for your Auto Scaling group, see Tag Your Auto
-- Scaling Groups and Amazon EC2 Instances.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_CreateOrUpdateTags.html>
data CreateOrUpdateTags = CreateOrUpdateTags
{ coutTags :: Members Tag
-- ^ The tag to be created or updated. Each tag should be defined by
-- its resource type, resource ID, key, value, and a propagate flag.
-- The resource type and resource ID identify the type and name of
-- resource for which the tag is created. Currently,
-- auto-scaling-group is the only supported resource type. The valid
-- value for the resource ID is groupname.
} deriving (Eq, Show, Generic)
instance IsQuery CreateOrUpdateTags
instance Rq CreateOrUpdateTags where
type Er CreateOrUpdateTags = AutoScalingErrorResponse
type Rs CreateOrUpdateTags = CreateOrUpdateTagsResponse
request = query4 autoScaling GET "CreateOrUpdateTags"
data CreateOrUpdateTagsResponse = CreateOrUpdateTagsResponse
{ coutrResponseMetadata :: !ResponseMetadata
} deriving (Eq, Show, Generic)
instance IsXML CreateOrUpdateTagsResponse where
xmlPickler = withNS autoScalingNS
-- | Deletes the specified Auto Scaling group if the group has no instances and
-- no scaling activities in progress. Note To remove all instances before
-- calling DeleteAutoScalingGroup, you can call UpdateAutoScalingGroup to set
-- the minimum and maximum size of the AutoScalingGroup to zero.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DeleteAutoScalingGroup.html>
data DeleteAutoScalingGroup = DeleteAutoScalingGroup
{ dasgAutoScalingGroupName :: !Text
-- ^ The name of the Auto Scaling group to delete.
, dasgForceDelete :: Maybe Bool
-- ^ Starting with API version 2011-01-01, specifies that the Auto
-- Scaling group will be deleted along with all instances associated
-- with the group, without waiting for all instances to be
-- terminated.
} deriving (Eq, Show, Generic)
instance IsQuery DeleteAutoScalingGroup
instance Rq DeleteAutoScalingGroup where
type Er DeleteAutoScalingGroup = AutoScalingErrorResponse
type Rs DeleteAutoScalingGroup = DeleteAutoScalingGroupResponse
request = query4 autoScaling GET "DeleteAutoScalingGroup"
data DeleteAutoScalingGroupResponse = DeleteAutoScalingGroupResponse
{ dasgrResponseMetadata :: !ResponseMetadata
} deriving (Eq, Show, Generic)
instance IsXML DeleteAutoScalingGroupResponse where
xmlPickler = withNS autoScalingNS
-- | Deletes the specified LaunchConfiguration. The specified launch
-- configuration must not be attached to an Auto Scaling group. When this call
-- completes, the launch configuration is no longer available for use.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DeleteLaunchConfiguration.html>
data DeleteLaunchConfiguration = DeleteLaunchConfiguration
{ dlcLaunchConfigurationName :: !Text
-- ^ The name of the launch configuration.
} deriving (Eq, Show, Generic)
instance IsQuery DeleteLaunchConfiguration
instance Rq DeleteLaunchConfiguration where
type Er DeleteLaunchConfiguration = AutoScalingErrorResponse
type Rs DeleteLaunchConfiguration = DeleteLaunchConfigurationResponse
request = query4 autoScaling GET "DeleteLaunchConfiguration"
data DeleteLaunchConfigurationResponse = DeleteLaunchConfigurationResponse
{ dlcrResponseMetadata :: !ResponseMetadata
} deriving (Eq, Show, Generic)
instance IsXML DeleteLaunchConfigurationResponse where
xmlPickler = withNS autoScalingNS
-- | Deletes notifications created by PutNotificationConfiguration.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DeleteNotificationConfiguration.html>
data DeleteNotificationConfiguration = DeleteNotificationConfiguration
{ dncAutoScalingGroupName :: !Text
-- ^ The name of the Auto Scaling group.
, dncTopicARN :: !Text
-- ^ The Amazon Resource Name (ARN) of the Amazon Simple Notification
-- Service (SNS) topic.
} deriving (Eq, Show, Generic)
instance IsQuery DeleteNotificationConfiguration
instance Rq DeleteNotificationConfiguration where
type Er DeleteNotificationConfiguration = AutoScalingErrorResponse
type Rs DeleteNotificationConfiguration = DeleteNotificationConfigurationResponse
request = query4 autoScaling GET "DeleteNotificationConfiguration"
data DeleteNotificationConfigurationResponse = DeleteNotificationConfigurationResponse
deriving (Eq, Read, Show, Generic)
instance IsXML DeleteNotificationConfigurationResponse where
xmlPickler = xpEmpty $ Just autoScalingNS
-- | Deletes a policy created by PutScalingPolicy.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DeletePolicy.html>
data DeletePolicy = DeletePolicy
{ dpAutoScalingGroupName :: Maybe Text
-- ^ The name of the Auto Scaling group.
, dpPolicyName :: !Text
-- ^ The name or PolicyARN of the policy you want to delete.
} deriving (Eq, Show, Generic)
instance IsQuery DeletePolicy
instance Rq DeletePolicy where
type Er DeletePolicy = AutoScalingErrorResponse
type Rs DeletePolicy = DeletePolicyResponse
request = query4 autoScaling GET "DeletePolicy"
data DeletePolicyResponse = DeletePolicyResponse
deriving (Eq, Read, Show, Generic)
instance IsXML DeletePolicyResponse where
xmlPickler = xpEmpty $ Just autoScalingNS
-- | Deletes a scheduled action previously created using the
-- PutScheduledUpdateGroupAction.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DeleteScheduledAction.html>
data DeleteScheduledAction = DeleteScheduledAction
{ dsaAutoScalingGroupName :: Maybe Text
-- ^ The name of the Auto Scaling group.
, dsaScheduledActionName :: !Text
-- ^ The name of the action you want to delete.
} deriving (Eq, Show, Generic)
instance IsQuery DeleteScheduledAction
instance Rq DeleteScheduledAction where
type Er DeleteScheduledAction = AutoScalingErrorResponse
type Rs DeleteScheduledAction = DeleteScheduledActionResponse
request = query4 autoScaling GET "DeleteScheduledAction"
data DeleteScheduledActionResponse = DeleteScheduledActionResponse
deriving (Eq, Read, Show, Generic)
instance IsXML DeleteScheduledActionResponse where
xmlPickler = xpEmpty $ Just autoScalingNS
-- | Removes the specified tags or a set of tags from a set of resources.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DeleteTags.html>
data DeleteTags = DeleteTags
{ dtTags :: Members Tag
-- ^ Each tag should be defined by its resource type, resource ID,
-- key, value, and a propagate flag. Valid values are: Resource type
-- = auto-scaling-group, Resource ID = AutoScalingGroupName,
-- key=value, value=value, propagate=true or false.
} deriving (Eq, Show, Generic)
instance IsQuery DeleteTags
instance Rq DeleteTags where
type Er DeleteTags = AutoScalingErrorResponse
type Rs DeleteTags = DeleteTagsResponse
request = query4 autoScaling GET "DeleteTags"
data DeleteTagsResponse = DeleteTagsResponse
deriving (Eq, Read, Show, Generic)
instance IsXML DeleteTagsResponse where
xmlPickler = xpEmpty $ Just autoScalingNS
-- | Returns policy adjustment types for use in the PutScalingPolicy action.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DescribeAdjustmentTypes.html>
data DescribeAdjustmentTypes = DescribeAdjustmentTypes
deriving (Eq, Show, Generic)
instance IsQuery DescribeAdjustmentTypes
instance Rq DescribeAdjustmentTypes where
type Er DescribeAdjustmentTypes = AutoScalingErrorResponse
type Rs DescribeAdjustmentTypes = DescribeAdjustmentTypesResponse
request = query4 autoScaling GET "DescribeAdjustmentTypes"
data DescribeAdjustmentTypesResponse = DescribeAdjustmentTypesResponse
{ datrDescribeAdjustmentTypesResult :: !DescribeAdjustmentTypesResult
} deriving (Eq, Show, Generic)
instance IsXML DescribeAdjustmentTypesResponse where
xmlPickler = withNS autoScalingNS
-- | Returns a full description of each Auto Scaling group in the given list.
-- This includes all Amazon EC2 instances that are members of the group. If a
-- list of names is not provided, the service returns the full details of all
-- Auto Scaling groups. This action supports pagination by returning a token
-- if there are more pages to retrieve. To get the next page, call this action
-- again with the returned token as the NextToken parameter.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DescribeAutoScalingGroups.html>
data DescribeAutoScalingGroups = DescribeAutoScalingGroups
{ dasgAutoScalingGroupNames :: Members Text
-- ^ A list of Auto Scaling group names.
, dasgMaxRecords :: Maybe Integer
-- ^ The maximum number of records to return.
, dasgNextToken :: Maybe Text
-- ^ A string that marks the start of the next batch of returned
-- results.
} deriving (Eq, Show, Generic)
instance IsQuery DescribeAutoScalingGroups
instance Rq DescribeAutoScalingGroups where
type Er DescribeAutoScalingGroups = AutoScalingErrorResponse
type Rs DescribeAutoScalingGroups = DescribeAutoScalingGroupsResponse
request = query4 autoScaling GET "DescribeAutoScalingGroups"
instance Pg DescribeAutoScalingGroups where
next dasg dasgr
| Just x <- tok = Just $ dasg { dasgNextToken = Just x }
| otherwise = Nothing
where
tok = dasgrNextToken (dashrDescribeAutoScalingGroupsResult dasgr)
data DescribeAutoScalingGroupsResponse = DescribeAutoScalingGroupsResponse
{ dashrDescribeAutoScalingGroupsResult :: !DescribeAutoScalingGroupsResult
} deriving (Eq, Show, Generic)
instance IsXML DescribeAutoScalingGroupsResponse where
xmlPickler = withNS autoScalingNS
-- | Returns a description of each Auto Scaling instance in the InstanceIds
-- list. If a list is not provided, the service returns the full details of
-- all instances up to a maximum of 50. By default, the service returns a list
-- of 20 items. This action supports pagination by returning a token if there
-- are more pages to retrieve. To get the next page, call this action again
-- with the returned token as the NextToken parameter.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DescribeAutoScalingInstances.html>
data DescribeAutoScalingInstances = DescribeAutoScalingInstances
{ dasiInstanceIds :: Members Text
-- ^ The list of Auto Scaling instances to describe. If this list is
-- omitted, all auto scaling instances are described. The list of
-- requested instances cannot contain more than 50 items. If unknown
-- instances are requested, they are ignored with no error.
, dasiMaxRecords :: Maybe Integer
-- ^ The maximum number of Auto Scaling instances to be described with
-- each call.
, dasiNextToken :: Maybe Text
-- ^ The token returned by a previous call to indicate that there is
-- more data available.
} deriving (Eq, Show, Generic)
instance IsQuery DescribeAutoScalingInstances
instance Rq DescribeAutoScalingInstances where
type Er DescribeAutoScalingInstances = AutoScalingErrorResponse
type Rs DescribeAutoScalingInstances = DescribeAutoScalingInstancesResponse
request = query4 autoScaling GET "DescribeAutoScalingInstances"
data DescribeAutoScalingInstancesResponse = DescribeAutoScalingInstancesResponse
{ dasirDescribeAutoScalingInstancesResult :: !DescribeAutoScalingInstancesResult
} deriving (Eq, Show, Generic)
instance IsXML DescribeAutoScalingInstancesResponse where
xmlPickler = withNS autoScalingNS
-- | Returns a list of all notification types that are supported by Auto
-- Scaling.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DescribeAutoScalingNotificationTypes.html>
data DescribeAutoScalingNotificationTypes = DescribeAutoScalingNotificationTypes
{ dasntAutoScalingNotificationTypes :: !Text
-- ^ Returns a list of all notification types supported by Auto
-- Scaling. They are:
} deriving (Eq, Show, Generic)
instance IsQuery DescribeAutoScalingNotificationTypes
instance Rq DescribeAutoScalingNotificationTypes where
type Er DescribeAutoScalingNotificationTypes = AutoScalingErrorResponse
type Rs DescribeAutoScalingNotificationTypes = DescribeAutoScalingNotificationTypesResponse
request = query4 autoScaling GET "DescribeAutoScalingNotificationTypes"
data DescribeAutoScalingNotificationTypesResponse = DescribeAutoScalingNotificationTypesResponse
{ dasntrDescribeAutoScalingNotificationTypesResult :: !DescribeAutoScalingNotificationTypesResult
} deriving (Eq, Show, Generic)
instance IsXML DescribeAutoScalingNotificationTypesResponse where
xmlPickler = withNS autoScalingNS
-- | Returns a full description of the launch configurations, or the specified
-- launch configurations, if they exist. If no name is specified, then the
-- full details of all launch configurations are returned.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DescribeLaunchConfigurations.html>
data DescribeLaunchConfigurations = DescribeLaunchConfigurations
{ dlcLaunchConfigurationNames :: Members Text
-- ^ A list of launch configuration names.
, dlcMaxRecords :: Maybe Integer
-- ^ The maximum number of launch configurations. The default is 100.
, dlcNextToken :: Maybe Text
-- ^ A string that marks the start of the next batch of returned
-- results.
} deriving (Eq, Show, Generic)
instance IsQuery DescribeLaunchConfigurations
instance Rq DescribeLaunchConfigurations where
type Er DescribeLaunchConfigurations = AutoScalingErrorResponse
type Rs DescribeLaunchConfigurations = DescribeLaunchConfigurationsResponse
request = query4 autoScaling GET "DescribeLaunchConfigurations"
data DescribeLaunchConfigurationsResponse = DescribeLaunchConfigurationsResponse
{ dldrDescribeLaunchConfigurationsResult :: !DescribeLaunchConfigurationsResult
} deriving (Eq, Show, Generic)
instance IsXML DescribeLaunchConfigurationsResponse where
xmlPickler = withNS autoScalingNS
-- | Returns a list of metrics and a corresponding list of granularities for
-- each metric.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DescribeMetricCollectionTypes.html>
data DescribeMetricCollectionTypes = DescribeMetricCollectionTypes
deriving (Eq, Show, Generic)
instance IsQuery DescribeMetricCollectionTypes
instance Rq DescribeMetricCollectionTypes where
type Er DescribeMetricCollectionTypes = AutoScalingErrorResponse
type Rs DescribeMetricCollectionTypes = DescribeMetricCollectionTypesResponse
request = query4 autoScaling GET "DescribeMetricCollectionTypes"
data DescribeMetricCollectionTypesResponse = DescribeMetricCollectionTypesResponse
{ dmctDescribeMetricCollectionTypesResult :: !DescribeMetricCollectionTypesResult
} deriving (Eq, Show, Generic)
instance IsXML DescribeMetricCollectionTypesResponse where
xmlPickler = withNS autoScalingNS
-- | Returns a list of notification actions associated with Auto Scaling groups
-- for specified events.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DescribeNotificationConfigurations.html>
data DescribeNotificationConfigurations = DescribeNotificationConfigurations
{ dncAutoScalingGroupNames :: Members Text
-- ^ The name of the Auto Scaling group.
, dncMaxRecords :: Maybe Integer
-- ^ Maximum number of records to be returned.
, dncNextToken :: Maybe Text
-- ^ A string that is used to mark the start of the next batch of
-- returned results for pagination.
} deriving (Eq, Show, Generic)
instance IsQuery DescribeNotificationConfigurations
instance Rq DescribeNotificationConfigurations where
type Er DescribeNotificationConfigurations = AutoScalingErrorResponse
type Rs DescribeNotificationConfigurations = DescribeNotificationConfigurationsResponse
request = query4 autoScaling GET "DescribeNotificationConfigurations"
data DescribeNotificationConfigurationsResponse = DescribeNotificationConfigurationsResponse
{ dndrDescribeNotificationConfigurationsResult :: !DescribeNotificationConfigurationsResult
} deriving (Eq, Show, Generic)
instance IsXML DescribeNotificationConfigurationsResponse where
xmlPickler = withNS autoScalingNS
-- | Returns descriptions of what each policy does. This action supports
-- pagination. If the response includes a token, there are more records
-- available. To get the additional records, repeat the request with the
-- response token as the NextToken parameter.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DescribePolicies.html>
data DescribePolicies = DescribePolicies
{ dqAutoScalingGroupName :: Maybe Text
-- ^ The name of the Auto Scaling group.
, dqMaxRecords :: Maybe Integer
-- ^ The maximum number of policies that will be described with each
-- call.
, dqNextToken :: Maybe Text
-- ^ A string that is used to mark the start of the next batch of
-- returned results for pagination.
, dqPolicyNames :: Members Text
-- ^ A list of policy names or policy ARNs to be described. If this
-- list is omitted, all policy names are described. If an auto
-- scaling group name is provided, the results are limited to that
-- group. The list of requested policy names cannot contain more
-- than 50 items. If unknown policy names are requested, they are
-- ignored with no error.
} deriving (Eq, Show, Generic)
instance IsQuery DescribePolicies
instance Rq DescribePolicies where
type Er DescribePolicies = AutoScalingErrorResponse
type Rs DescribePolicies = DescribePoliciesResponse
request = query4 autoScaling GET "DescribePolicies"
data DescribePoliciesResponse = DescribePoliciesResponse
{ dqrDescribePoliciesResult :: !DescribePoliciesResult
} deriving (Eq, Show, Generic)
instance IsXML DescribePoliciesResponse where
xmlPickler = withNS autoScalingNS
-- | Returns the scaling activities for the specified Auto Scaling group. If the
-- specified ActivityIds list is empty, all the activities from the past six
-- weeks are returned. Activities are sorted by completion time. Activities
-- still in progress appear first on the list. This action supports
-- pagination. If the response includes a token, there are more records
-- available. To get the additional records, repeat the request with the
-- response token as the NextToken parameter.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DescribeScalingActivities.html>
data DescribeScalingActivities = DescribeScalingActivities
{ dsbActivityIds :: Members Text
-- ^ A list containing the activity IDs of the desired scaling
-- activities. If this list is omitted, all activities are
-- described. If an AutoScalingGroupName is provided, the results
-- are limited to that group. The list of requested activities
-- cannot contain more than 50 items. If unknown activities are
-- requested, they are ignored with no error.
, dsbAutoScalingGroupName :: Maybe Text
-- ^ The name of the AutoScalingGroup.
, dsbMaxRecords :: Maybe Integer
-- ^ The maximum number of scaling activities to return.
, dsbNextToken :: Maybe Text
-- ^ A string that marks the start of the next batch of returned
-- results for pagination.
} deriving (Eq, Show, Generic)
instance IsQuery DescribeScalingActivities
instance Rq DescribeScalingActivities where
type Er DescribeScalingActivities = AutoScalingErrorResponse
type Rs DescribeScalingActivities = DescribeScalingActivitiesResponse
request = query4 autoScaling GET "DescribeScalingActivities"
data DescribeScalingActivitiesResponse = DescribeScalingActivitiesResponse
{ dsbrDescribeScalingActivitiesResult :: !DescribeScalingActivitiesResult
} deriving (Eq, Show, Generic)
instance IsXML DescribeScalingActivitiesResponse where
xmlPickler = withNS autoScalingNS
-- | Returns scaling process types for use in the ResumeProcesses and
-- SuspendProcesses actions.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DescribeScalingProcessTypes.html>
data DescribeScalingProcessTypes = DescribeScalingProcessTypes
{ dsptProcesses :: !ProcessType
-- ^ A list of ProcessType names.
} deriving (Eq, Show, Generic)
instance IsQuery DescribeScalingProcessTypes
instance Rq DescribeScalingProcessTypes where
type Er DescribeScalingProcessTypes = AutoScalingErrorResponse
type Rs DescribeScalingProcessTypes = DescribeScalingProcessTypesResponse
request = query4 autoScaling GET "DescribeScalingProcessTypes"
data DescribeScalingProcessTypesResponse = DescribeScalingProcessTypesResponse
{ dsptrDescribeScalingProcessTypesResult :: !DescribeScalingProcessTypesResult
} deriving (Eq, Show, Generic)
instance IsXML DescribeScalingProcessTypesResponse where
xmlPickler = withNS autoScalingNS
-- | Lists all the actions scheduled for your Auto Scaling group that haven't
-- been executed. To see a list of actions already executed, see the activity
-- record returned in DescribeScalingActivities.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DescribeScheduledActions.html>
data DescribeScheduledActions = DescribeScheduledActions
{ dscAutoScalingGroupName :: Maybe Text
-- ^ The name of the Auto Scaling group.
, dscEndTime :: Maybe UTCTime
-- ^ The latest scheduled start time to return. If scheduled action
-- names are provided, this field is ignored.
, dscMaxRecords :: Maybe Integer
-- ^ The maximum number of scheduled actions to return.
, dscNextToken :: Maybe Text
-- ^ A string that marks the start of the next batch of returned
-- results.
, dscScheduledActionNames :: Members Text
-- ^ A list of scheduled actions to be described. If this list is
-- omitted, all scheduled actions are described. The list of
-- requested scheduled actions cannot contain more than 50 items. If
-- an auto scaling group name is provided, the results are limited
-- to that group. If unknown scheduled actions are requested, they
-- are ignored with no error.
, dscStartTime :: Maybe UTCTime
-- ^ The earliest scheduled start time to return. If scheduled action
-- names are provided, this field will be ignored.
} deriving (Eq, Show, Generic)
instance IsQuery DescribeScheduledActions
instance Rq DescribeScheduledActions where
type Er DescribeScheduledActions = AutoScalingErrorResponse
type Rs DescribeScheduledActions = DescribeScheduledActionsResponse
request = query4 autoScaling GET "DescribeScheduledActions"
data DescribeScheduledActionsResponse = DescribeScheduledActionsResponse
{ dscrDescribeScheduledActionsResult :: !DescribeScheduledActionsResult
} deriving (Eq, Show, Generic)
instance IsXML DescribeScheduledActionsResponse where
xmlPickler = withNS autoScalingNS
-- | Lists the Auto Scaling group tags. You can use filters to limit results
-- when describing tags. For example, you can query4 autoScaling for tags of a particular
-- Auto Scaling group. You can specify multiple values for a filter. A tag
-- must match at least one of the specified values for it to be included in
-- the results. You can also specify multiple filters. The result includes
-- information for a particular tag only if it matches all your filters. If
-- there's no match, no special message is returned.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DescribeTags.html>
data DescribeTags = DescribeTags
{ dtFilters :: Members Filter
-- ^ The value of the filter type used to identify the tags to be
-- returned. For example, you can filter so that tags are returned
-- according to Auto Scaling group, the key and value, or whether
-- the new tag will be applied to instances launched after the tag
-- is created (PropagateAtLaunch).
, dtMaxRecords :: Maybe Integer
-- ^ The maximum number of records to return.
, dtNextToken :: Maybe Text
-- ^ A string that marks the start of the next batch of returned
-- results.
} deriving (Eq, Show, Generic)
instance IsQuery DescribeTags
instance Rq DescribeTags where
type Er DescribeTags = AutoScalingErrorResponse
type Rs DescribeTags = DescribeTagsResponse
request = query4 autoScaling GET "DescribeTags"
instance Pg DescribeTags where
next rq rs
| Just x <- dtrNextToken (dtrDescribeTagsResult rs) = Just $ rq { dtNextToken = Just x }
| otherwise = Nothing
data DescribeTagsResponse = DescribeTagsResponse
{ dtrDescribeTagsResult :: !DescribeTagsResult
} deriving (Eq, Show, Generic)
instance IsXML DescribeTagsResponse where
xmlPickler = withNS autoScalingNS
-- | Returns a list of all termination policies supported by Auto Scaling.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DescribeTerminationPolicyTypes.html>
data DescribeTerminationPolicyTypes = DescribeTerminationPolicyTypes
{ dtptTerminationPolicyTypes :: !Text
-- ^ Termination policies supported by Auto Scaling. They are:
-- OldestInstance, OldestLaunchConfiguration, NewestInstance,
-- ClosestToNextInstanceHour, Default
} deriving (Eq, Show, Generic)
instance IsQuery DescribeTerminationPolicyTypes
instance Rq DescribeTerminationPolicyTypes where
type Er DescribeTerminationPolicyTypes = AutoScalingErrorResponse
type Rs DescribeTerminationPolicyTypes = DescribeTerminationPolicyTypesResponse
request = query4 autoScaling GET "DescribeTerminationPolicyTypes"
data DescribeTerminationPolicyTypesResponse = DescribeTerminationPolicyTypesResponse
{ dtptrDescribeTerminationPolicyTypesResult :: !DescribeTerminationPolicyTypesResult
} deriving (Eq, Show, Generic)
instance IsXML DescribeTerminationPolicyTypesResponse where
xmlPickler = withNS autoScalingNS
-- | Disables monitoring of group metrics for the Auto Scaling group specified
-- in AutoScalingGroupName. You can specify the list of affected metrics with
-- the Metrics parameter.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DisableMetricsCollection.html>
data DisableMetricsCollection = DisableMetricsCollection
{ dmcAutoScalingGroupName :: !Text
-- ^ The name or ARN of the Auto Scaling Group.
, dmcMetrics :: Members Text
-- ^ The list of metrics to disable. If no metrics are specified, all
-- metrics are disabled. The following metrics are supported:
} deriving (Eq, Show, Generic)
instance IsQuery DisableMetricsCollection
instance Rq DisableMetricsCollection where
type Er DisableMetricsCollection = AutoScalingErrorResponse
type Rs DisableMetricsCollection = DisableMetricsCollectionResponse
request = query4 autoScaling GET "DisableMetricsCollection"
data DisableMetricsCollectionResponse = DisableMetricsCollectionResponse
{ dmcrResponseMetadata :: !ResponseMetadata
} deriving (Eq, Show, Generic)
instance IsXML DisableMetricsCollectionResponse where
xmlPickler = withNS autoScalingNS
-- | Enables monitoring of group metrics for the Auto Scaling group specified in
-- AutoScalingGroupName. You can specify the list of enabled metrics with the
-- Metrics parameter. Auto Scaling metrics collection can be turned on only if
-- the InstanceMonitoring flag, in the Auto Scaling group's launch
-- configuration, is set to True.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_EnableMetricsCollection.html>
data EnableMetricsCollection = EnableMetricsCollection
{ emcAutoScalingGroupName :: !Text
-- ^ The name or ARN of the Auto Scaling group.
, emcGranularity :: !Text
-- ^ The granularity to associate with the metrics to collect.
-- Currently, the only legal granularity is "1Minute".
, emcMetrics :: Members Text
-- ^ The list of metrics to collect. If no metrics are specified, all
-- metrics are enabled. The following metrics are supported:
} deriving (Eq, Show, Generic)
instance IsQuery EnableMetricsCollection
instance Rq EnableMetricsCollection where
type Er EnableMetricsCollection = AutoScalingErrorResponse
type Rs EnableMetricsCollection = EnableMetricsCollectionResponse
request = query4 autoScaling GET "EnableMetricsCollection"
data EnableMetricsCollectionResponse = EnableMetricsCollectionResponse
{ emcrResponseMetadata :: !ResponseMetadata
} deriving (Eq, Show, Generic)
instance IsXML EnableMetricsCollectionResponse where
xmlPickler = withNS autoScalingNS
-- | Executes the specified policy.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_ExecutePolicy.html>
data ExecutePolicy = ExecutePolicy
{ epAutoScalingGroupName :: Maybe Text
-- ^ The name or the Amazon Resource Name (ARN) of the Auto Scaling
-- group.
, epHonorCooldown :: Maybe Bool
-- ^ Set to True if you want Auto Scaling to wait for the cooldown
-- period associated with the Auto Scaling group to complete before
-- executing the policy.
, epPolicyName :: !Text
-- ^ The name or ARN of the policy you want to run.
} deriving (Eq, Show, Generic)
instance IsQuery ExecutePolicy
instance Rq ExecutePolicy where
type Er ExecutePolicy = AutoScalingErrorResponse
type Rs ExecutePolicy = ExecutePolicyResponse
request = query4 autoScaling GET "ExecutePolicy"
data ExecutePolicyResponse = ExecutePolicyResponse
{ eprResponseMetadata :: !ResponseMetadata
} deriving (Eq, Show, Generic)
instance IsXML ExecutePolicyResponse where
xmlPickler = withNS autoScalingNS
-- | Configures an Auto Scaling group to send notifications when specified
-- events take place. Subscribers to this topic can have messages for events
-- delivered to an endpoint such as a web server or email address. For more
-- information see Get Email Notifications When Your Auto Scaling Group
-- Changes A new PutNotificationConfiguration overwrites an existing
-- configuration.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_PutNotificationConfiguration.html>
data PutNotificationConfiguration = PutNotificationConfiguration
{ pncAutoScalingGroupName :: !Text
-- ^ The name of the Auto Scaling group.
, pncNotificationTypes :: Members Text
-- ^ The type of event that will cause the notification to be sent.
-- For details about notification types supported by Auto Scaling,
-- see DescribeAutoScalingNotificationTypes.
, pncTopicARN :: !Text
-- ^ The Amazon Resource Name (ARN) of the Amazon Simple Notification
-- Service (SNS) topic.
} deriving (Eq, Show, Generic)
instance IsQuery PutNotificationConfiguration
instance Rq PutNotificationConfiguration where
type Er PutNotificationConfiguration = AutoScalingErrorResponse
type Rs PutNotificationConfiguration = PutNotificationConfigurationResponse
request = query4 autoScaling GET "PutNotificationConfiguration"
data PutNotificationConfigurationResponse = PutNotificationConfigurationResponse
{ pncrResponseMetadata :: !ResponseMetadata
} deriving (Eq, Show, Generic)
instance IsXML PutNotificationConfigurationResponse where
xmlPickler = withNS autoScalingNS
-- | Creates or updates a policy for an Auto Scaling group. To update an
-- existing policy, use the existing policy name and set the parameter(s) you
-- want to change. Any existing parameter not changed in an update to an
-- existing policy is not changed in this update request.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_PutScalingPolicy.html>
data PutScalingPolicy = PutScalingPolicy
{ pspAdjustmentType :: !Text
-- ^ Specifies whether the ScalingAdjustment is an absolute number or
-- a percentage of the current capacity. Valid values are
-- ChangeInCapacity, ExactCapacity, and PercentChangeInCapacity.
, pspAutoScalingGroupName :: !Text
-- ^ The name or ARN of the Auto Scaling group.
, pspCooldown :: Maybe Integer
-- ^ The amount of time, in seconds, after a scaling activity
-- completes and before the next scaling acitvity can start.
, pspMinAdjustmentStep :: Maybe Integer
-- ^ Used with AdjustmentType with the value PercentChangeInCapacity,
-- the scaling policy changes the DesiredCapacity of the Auto
-- Scaling group by at least the number of instances specified in
-- the value.
, pspPolicyName :: !Text
-- ^ The name of the policy you want to create or update.
, pspScalingAdjustment :: !Integer
-- ^ The number of instances by which to scale. AdjustmentType
-- determines the interpretation of this number (e.g., as an
-- absolute number or as a percentage of the existing Auto Scaling
-- group size). A positive increment adds to the current capacity
-- and a negative value removes from the current capacity.
} deriving (Eq, Show, Generic)
instance IsQuery PutScalingPolicy
instance Rq PutScalingPolicy where
type Er PutScalingPolicy = AutoScalingErrorResponse
type Rs PutScalingPolicy = PutScalingPolicyResponse
request = query4 autoScaling GET "PutScalingPolicy"
data PutScalingPolicyResponse = PutScalingPolicyResponse
{ psprPutScalingPolicyResult :: !PutScalingPolicyResult
} deriving (Eq, Show, Generic)
instance IsXML PutScalingPolicyResponse where
xmlPickler = withNS autoScalingNS
-- | Creates or updates a scheduled scaling action for an Auto Scaling group.
-- When updating a scheduled scaling action, if you leave a parameter
-- unspecified, the corresponding value remains unchanged in the affected Auto
-- Scaling group. For information on creating or updating a scheduled action
-- for your Auto Scaling group, see Scale Based on a Schedule. Note Auto
-- Scaling supports the date and time expressed in "YYYY-MM-DDThh:mm:ssZ"
-- format in UTC/GMT only.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_PutScheduledUpdateGroupAction.html>
data PutScheduledUpdateGroupAction = PutScheduledUpdateGroupAction
{ psugaAutoScalingGroupName :: !Text
-- ^ The name or ARN of the Auto Scaling group.
, psugaDesiredCapacity :: Maybe Integer
-- ^ The number of Amazon EC2 instances that should be running in the
-- group.
, psugaEndTime :: Maybe UTCTime
-- ^ The time for this action to end.
, psugaMaxSize :: Maybe Integer
-- ^ The maximum size for the Auto Scaling group.
, psugaMinSize :: Maybe Integer
-- ^ The minimum size for the new Auto Scaling group.
, psugaRecurrence :: Maybe Text
-- ^ The time when recurring future actions will start. Start time is
-- specified by the user following the Unix cron syntax format. For
-- information about cron syntax, go to Wikipedia, The Free
-- Encyclopedia.
, psugaScheduledActionName :: !Text
-- ^ The name of this scaling action.
, psugaStartTime :: Maybe UTCTime
-- ^ The time for this action to start, as in --start-time
-- 2010-06-01T00:00:00Z.
, psugaTime :: Maybe UTCTime
-- ^ Time is deprecated.
} deriving (Eq, Show, Generic)
instance IsQuery PutScheduledUpdateGroupAction
instance Rq PutScheduledUpdateGroupAction where
type Er PutScheduledUpdateGroupAction = AutoScalingErrorResponse
type Rs PutScheduledUpdateGroupAction = PutScheduledUpdateGroupActionResponse
request = query4 autoScaling GET "PutScheduledUpdateGroupAction"
data PutScheduledUpdateGroupActionResponse = PutScheduledUpdateGroupActionResponse
{ psugarResponseMetadata :: !ResponseMetadata
} deriving (Eq, Show, Generic)
instance IsXML PutScheduledUpdateGroupActionResponse where
xmlPickler = withNS autoScalingNS
-- | Resumes all suspended Auto Scaling processes for an Auto Scaling group. For
-- information on suspending and resuming Auto Scaling process, see Suspend
-- and Resume Auto Scaling Process.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_ResumeProcesses.html>
data ResumeProcesses = ResumeProcesses
{ rpAutoScalingGroupName :: !Text
-- ^ The name or Amazon Resource Name (ARN) of the Auto Scaling group.
, rpScalingProcesses :: Members Text
-- ^ The processes that you want to suspend or resume, which can
-- include one or more of the following:
} deriving (Eq, Show, Generic)
instance IsQuery ResumeProcesses
instance Rq ResumeProcesses where
type Er ResumeProcesses = AutoScalingErrorResponse
type Rs ResumeProcesses = ResumeProcessesResponse
request = query4 autoScaling GET "ResumeProcesses"
data ResumeProcessesResponse = ResumeProcessesResponse
{ rprResponseMetadata :: !ResponseMetadata
} deriving (Eq, Show, Generic)
instance IsXML ResumeProcessesResponse where
xmlPickler = withNS autoScalingNS
-- | Sets the desired size of the specified AutoScalingGroup.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_SetDesiredCapacity.html>
data SetDesiredCapacity = SetDesiredCapacity
{ sdcAutoScalingGroupName :: !Text
-- ^ The name of the Auto Scaling group.
, sdcDesiredCapacity :: !Integer
-- ^ The new capacity setting for the Auto Scaling group.
, sdcHonorCooldown :: Maybe Bool
-- ^ By default, SetDesiredCapacity overrides any cooldown period
-- associated with the Auto Scaling group. Set to True if you want
-- Auto Scaling to wait for the cooldown period associated with the
-- Auto Scaling group to complete before initiating a scaling
-- activity to set your Auto Scaling group to the new capacity
-- setting.
} deriving (Eq, Show, Generic)
instance IsQuery SetDesiredCapacity
instance Rq SetDesiredCapacity where
type Er SetDesiredCapacity = AutoScalingErrorResponse
type Rs SetDesiredCapacity = SetDesiredCapacityResponse
request = query4 autoScaling GET "SetDesiredCapacity"
data SetDesiredCapacityResponse = SetDesiredCapacityResponse
{ sdcrResponseMetadata :: !ResponseMetadata
} deriving (Eq, Show, Generic)
instance IsXML SetDesiredCapacityResponse where
xmlPickler = withNS autoScalingNS
-- | Sets the health status of a specified instance that belongs to any of your
-- Auto Scaling groups. For more information, see Configure Health Checks for
-- Your Auto Scaling group.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_SetInstanceHealth.html>
data SetInstanceHealth = SetInstanceHealth
{ sihHealthStatus :: !Text
-- ^ The health status of the instance. Set to Healthy if you want the
-- instance to remain in service. Set to Unhealthy if you want the
-- instance to be out of service. Auto Scaling will terminate and
-- replace the unhealthy instance.
, sihInstanceId :: !Text
-- ^ The identifier of the Amazon EC2 instance.
, sihShouldRespectGracePeriod :: Maybe Bool
-- ^ If the Auto Scaling group of the specified instance has a
-- HealthCheckGracePeriod specified for the group, by default, this
-- call will respect the grace period. Set this to False, if you do
-- not want the call to respect the grace period associated with the
-- group.
} deriving (Eq, Show, Generic)
instance IsQuery SetInstanceHealth
instance Rq SetInstanceHealth where
type Er SetInstanceHealth = AutoScalingErrorResponse
type Rs SetInstanceHealth = SetInstanceHealthResponse
request = query4 autoScaling GET "SetInstanceHealth"
data SetInstanceHealthResponse = SetInstanceHealthResponse
{ sihrResponseMetadata :: !ResponseMetadata
} deriving (Eq, Show, Generic)
instance IsXML SetInstanceHealthResponse where
xmlPickler = withNS autoScalingNS
-- | Suspends Auto Scaling processes for an Auto Scaling group. To suspend
-- specific process types, specify them by name with the
-- ScalingProcesses.member.N parameter. To suspend all process types, omit the
-- ScalingProcesses.member.N parameter. Important Suspending either of the two
-- primary process types, Launch or Terminate, can prevent other process types
-- from functioning properly. To resume processes that have been suspended,
-- use ResumeProcesses For more information on suspending and resuming Auto
-- Scaling process, see Suspend and Resume Auto Scaling Process.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_SuspendProcesses.html>
data SuspendProcesses = SuspendProcesses
{ spAutoScalingGroupName :: !Text
-- ^ The name or Amazon Resource Name (ARN) of the Auto Scaling group.
, spScalingProcesses :: Members Text
-- ^ The processes that you want to suspend or resume, which can
-- include one or more of the following:
} deriving (Eq, Show, Generic)
instance IsQuery SuspendProcesses
instance Rq SuspendProcesses where
type Er SuspendProcesses = AutoScalingErrorResponse
type Rs SuspendProcesses = SuspendProcessesResponse
request = query4 autoScaling GET "SuspendProcesses"
data SuspendProcessesResponse = SuspendProcessesResponse
{ sprResponseMetadata :: !ResponseMetadata
} deriving (Eq, Show, Generic)
instance IsXML SuspendProcessesResponse where
xmlPickler = withNS autoScalingNS
-- | Terminates the specified instance. Optionally, the desired group size can
-- be adjusted. Note This call simply registers a termination request. The
-- termination of the instance cannot happen immediately.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_TerminateInstanceInAutoScalingGroup.html>
data TerminateInstanceInAutoScalingGroup = TerminateInstanceInAutoScalingGroup
{ tiiasgInstanceId :: !Text
-- ^ The ID of the Amazon EC2 instance to be terminated.
, tiiasgShouldDecrementDesiredCapacity :: !Bool
-- ^ Specifies whether (true) or not (false) terminating this instance
-- should also decrement the size of the AutoScalingGroup.
} deriving (Eq, Show, Generic)
instance IsQuery TerminateInstanceInAutoScalingGroup
instance Rq TerminateInstanceInAutoScalingGroup where
type Er TerminateInstanceInAutoScalingGroup = AutoScalingErrorResponse
type Rs TerminateInstanceInAutoScalingGroup = TerminateInstanceInAutoScalingGroupResponse
request = query4 autoScaling GET "TerminateInstanceInAutoScalingGroup"
data TerminateInstanceInAutoScalingGroupResponse = TerminateInstanceInAutoScalingGroupResponse
{ tiiasgrResponseMetadata :: !ResponseMetadata
, tiiasgrTerminateInstanceInAutoScalingGroupResult :: !TerminateInstanceInAutoScalingGroupResult
} deriving (Eq, Show, Generic)
instance IsXML TerminateInstanceInAutoScalingGroupResponse where
xmlPickler = withNS autoScalingNS
-- | Updates the configuration for the specified AutoScalingGroup.
--
-- Note: To update an Auto Scaling group with a launch configuration that has the
-- InstanceMonitoring flag set to False, you must first ensure that collection
-- of group metrics is disabled. Otherwise, calls to UpdateAutoScalingGroup
-- will fail. If you have previously enabled group metrics collection, you can
-- disable collection of all group metrics by calling
-- DisableMetricsCollection. The new settings are registered upon the
-- completion of this call. Any launch configuration settings take effect on
-- any triggers after this call returns.
--
-- <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_UpdateAutoScalingGroup.html>
data UpdateAutoScalingGroup = UpdateAutoScalingGroup
{ uasgAutoScalingGroupName :: !Text
-- ^ The name of the Auto Scaling group.
, uasgAvailabilityZones :: Members AvailabilityZone
-- ^ Availability Zones for the group.
, uasgDefaultCooldown :: Maybe Integer
-- ^ The amount of time, in seconds, after a scaling activity
-- completes before any further scaling activities can start. For
-- more information, see Cooldown Period.
, uasgDesiredCapacity :: Maybe Integer
-- ^ The desired capacity for the Auto Scaling group.
, uasgHealthCheckGracePeriod :: Maybe Integer
-- ^ The length of time that Auto Scaling waits before checking an
-- instance's health status. The grace period begins when an
-- instance comes into service.
, uasgHealthCheckType :: Maybe Text
-- ^ The type of health check for the instances in the Auto Scaling
-- group. The health check type can either be EC2 for Amazon EC2 or
-- ELB for Elastic Load Balancing.
, uasgLaunchConfigurationName :: Maybe Text
-- ^ The name of the launch configuration.
, uasgMaxSize :: Maybe Integer
-- ^ The maximum size of the Auto Scaling group.
, uasgMinSize :: Maybe Integer
-- ^ The minimum size of the Auto Scaling group.
, uasgPlacementGroup :: Maybe Text
-- ^ The name of the cluster placement group, if applicable. For more
-- information, go to Using Cluster Instances in the Amazon EC2 User
-- Guide.
, uasgTerminationPolicies :: Members Text
-- ^ A standalone termination policy or a list of termination policies
-- used to select the instance to terminate. The policies are
-- executed in the order that they are listed.
, uasgVPCZoneIdentifier :: Maybe Text
-- ^ The subnet identifier for the Amazon VPC connection, if
-- applicable. You can specify several subnets in a comma-separated
-- list.
} deriving (Eq, Show, Generic)
instance IsQuery UpdateAutoScalingGroup
instance Rq UpdateAutoScalingGroup where
type Er UpdateAutoScalingGroup = AutoScalingErrorResponse
type Rs UpdateAutoScalingGroup = UpdateAutoScalingGroupResponse
request = query4 autoScaling GET "UpdateAutoScalingGroup"
data UpdateAutoScalingGroupResponse = UpdateAutoScalingGroupResponse
{ uasgrResponseMetadata :: !ResponseMetadata
} deriving (Eq, Show, Generic)
instance IsXML UpdateAutoScalingGroupResponse where
xmlPickler = withNS autoScalingNS
|
zinfra/khan
|
amazonka-limited/src/Network/AWS/AutoScaling.hs
|
mpl-2.0
| 62,010
| 0
| 12
| 12,928
| 6,163
| 3,613
| 2,550
| 753
| 0
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.YouTube.Comments.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns a list of comments that match the API request parameters.
--
-- /See:/ <https://developers.google.com/youtube/v3 YouTube Data API Reference> for @youtube.comments.list@.
module Network.Google.Resource.YouTube.Comments.List
(
-- * REST Resource
CommentsListResource
-- * Creating a Request
, commentsList
, CommentsList
-- * Request Lenses
, cllPart
, cllId
, cllPageToken
, cllTextFormat
, cllMaxResults
, cllParentId
) where
import Network.Google.Prelude
import Network.Google.YouTube.Types
-- | A resource alias for @youtube.comments.list@ method which the
-- 'CommentsList' request conforms to.
type CommentsListResource =
"youtube" :>
"v3" :>
"comments" :>
QueryParam "part" Text :>
QueryParam "id" Text :>
QueryParam "pageToken" Text :>
QueryParam "textFormat" CommentsListTextFormat :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "parentId" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] CommentListResponse
-- | Returns a list of comments that match the API request parameters.
--
-- /See:/ 'commentsList' smart constructor.
data CommentsList = CommentsList'
{ _cllPart :: !Text
, _cllId :: !(Maybe Text)
, _cllPageToken :: !(Maybe Text)
, _cllTextFormat :: !CommentsListTextFormat
, _cllMaxResults :: !(Textual Word32)
, _cllParentId :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'CommentsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cllPart'
--
-- * 'cllId'
--
-- * 'cllPageToken'
--
-- * 'cllTextFormat'
--
-- * 'cllMaxResults'
--
-- * 'cllParentId'
commentsList
:: Text -- ^ 'cllPart'
-> CommentsList
commentsList pCllPart_ =
CommentsList'
{ _cllPart = pCllPart_
, _cllId = Nothing
, _cllPageToken = Nothing
, _cllTextFormat = HTML
, _cllMaxResults = 20
, _cllParentId = Nothing
}
-- | The part parameter specifies a comma-separated list of one or more
-- comment resource properties that the API response will include.
cllPart :: Lens' CommentsList Text
cllPart = lens _cllPart (\ s a -> s{_cllPart = a})
-- | The id parameter specifies a comma-separated list of comment IDs for the
-- resources that are being retrieved. In a comment resource, the id
-- property specifies the comment\'s ID.
cllId :: Lens' CommentsList (Maybe Text)
cllId = lens _cllId (\ s a -> s{_cllId = a})
-- | The pageToken parameter identifies a specific page in the result set
-- that should be returned. In an API response, the nextPageToken property
-- identifies the next page of the result that can be retrieved. Note: This
-- parameter is not supported for use in conjunction with the id parameter.
cllPageToken :: Lens' CommentsList (Maybe Text)
cllPageToken
= lens _cllPageToken (\ s a -> s{_cllPageToken = a})
-- | This parameter indicates whether the API should return comments
-- formatted as HTML or as plain text.
cllTextFormat :: Lens' CommentsList CommentsListTextFormat
cllTextFormat
= lens _cllTextFormat
(\ s a -> s{_cllTextFormat = a})
-- | The maxResults parameter specifies the maximum number of items that
-- should be returned in the result set. Note: This parameter is not
-- supported for use in conjunction with the id parameter.
cllMaxResults :: Lens' CommentsList Word32
cllMaxResults
= lens _cllMaxResults
(\ s a -> s{_cllMaxResults = a})
. _Coerce
-- | The parentId parameter specifies the ID of the comment for which replies
-- should be retrieved. Note: YouTube currently supports replies only for
-- top-level comments. However, replies to replies may be supported in the
-- future.
cllParentId :: Lens' CommentsList (Maybe Text)
cllParentId
= lens _cllParentId (\ s a -> s{_cllParentId = a})
instance GoogleRequest CommentsList where
type Rs CommentsList = CommentListResponse
type Scopes CommentsList =
'["https://www.googleapis.com/auth/youtube.force-ssl"]
requestClient CommentsList'{..}
= go (Just _cllPart) _cllId _cllPageToken
(Just _cllTextFormat)
(Just _cllMaxResults)
_cllParentId
(Just AltJSON)
youTubeService
where go
= buildClient (Proxy :: Proxy CommentsListResource)
mempty
|
rueshyna/gogol
|
gogol-youtube/gen/Network/Google/Resource/YouTube/Comments/List.hs
|
mpl-2.0
| 5,366
| 0
| 17
| 1,277
| 724
| 426
| 298
| 101
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.