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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
-- Typeclass
class BasicEq a where
isEqual :: a -> a -> Bool
instance BasicEq Bool where
isEqual True True = True
isEqual False False = True
isEqual _ _ = False
| EricYT/Haskell | src/chapter-6-1.hs | apache-2.0 | 177 | 0 | 8 | 47 | 62 | 31 | 31 | 6 | 0 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Transaction where
import Control.Lens
import Control.Lens.TH
import Data.Function
import Data.Hashable
import Commutating
import TransactionState
newtype TransactionID = TransactionID Int deriving(Eq, Ord, Hashable)
data Transaction a = Transaction {
_id :: TransactionID
, _operation :: a
, _transactionState :: TransactionState
}
makeLenses ''Transaction
(^&^) :: Getting a c a -> (a -> a -> b) -> (c -> c -> b)
(^&^) x y = y `on` view x
onId = (^&^) Transaction.id
onOperation = (^&^) operation
instance Eq (Transaction a) where
(==) = onId (==)
instance Ord (Transaction a) where
compare = onId compare
instance (Commutating a) => Commutating (Transaction a) where
commutates = onOperation commutates
create :: TransactionID -> TransactionState -> a -> Transaction a
create transactionID transactionState operation =
Transaction transactionID operation transactionState | kdkeyser/halvin | src/halvin/Transaction.hs | apache-2.0 | 987 | 0 | 9 | 163 | 297 | 166 | 131 | 28 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE BangPatterns #-}
module Score
( Score
, Input(..)
, Choice(..)
, score
, positive
#ifdef TEST
, minimum
#endif
) where
import Control.Applicative
import Control.Monad
import Data.Maybe (mapMaybe)
import Data.Text (Text)
import qualified Data.Text as Text
import Prelude hiding (minimum)
newtype Score = Score Double deriving (Show, Eq, Ord)
instance Bounded Score where
minBound = Score 0.0
maxBound = Score 1.0
newtype Input = Input Text deriving (Show, Eq)
newtype Choice = Choice Text deriving (Show, Eq)
score :: Input -> Choice -> Score
score (Input q) (Choice c)
| Nothing <- Text.uncons (Text.toLower q) = maxBound
| Just (x, xs) <- Text.uncons (Text.toLower q)
, Just ml <- sub x xs (Text.toLower c) = Score ((fi ql / fi ml) / fi cl)
| otherwise = minBound
where
fi = fromIntegral
ql = Text.length q
cl = Text.length c
-- | The shortest substring match length
sub :: Char -> Text -> Text -> Maybe Int
sub q qs = minimum . mapMaybe (rec qs <=< Text.stripPrefix (Text.singleton q)) . Text.tails
rec :: Text -> Text -> Maybe Int
rec = go 0
where
go !len xs bs = case Text.uncons xs of
Nothing -> Just len
Just (a, as) -> case Text.findIndex (== a) bs of
Nothing -> Nothing
Just i -> go (len + i) as (Text.drop (i + 1) bs)
-- | The score is at least a little bit greater than the absolute minimum
--
-- This means it will be presented to user, even if at the bottom of the list
positive :: Score -> Bool
positive n = n > minBound
minimum :: Ord a => [a] -> Maybe a
minimum = foldr (\x a -> liftA2 min (Just x) a <|> Just x) Nothing
| supki/wybor | src/Score.hs | bsd-2-clause | 1,706 | 0 | 17 | 434 | 635 | 334 | 301 | 42 | 3 |
{-# LANGUAGE DeriveDataTypeable #-}
module Data.Mathematica.Type where
import System.Console.CmdArgs
data Mathematica_data = Test
deriving (Show,Data,Typeable)
test :: Mathematica_data
test = Test
mode = modes [test]
| wavewave/mathematica-data | lib/Data/Mathematica/Type.hs | bsd-2-clause | 240 | 0 | 6 | 48 | 57 | 34 | 23 | 8 | 1 |
module Application.DiagramDrawer.Verbatim where
import Language.Haskell.TH.Quote
import Language.Haskell.TH.Lib
verbatim :: QuasiQuoter
verbatim = QuasiQuoter { quoteExp = litE . stringL
, quotePat = undefined
, quoteType = undefined
, quoteDec = undefined
}
| wavewave/diagdrawer | lib/Application/DiagramDrawer/Verbatim.hs | bsd-2-clause | 357 | 0 | 7 | 130 | 61 | 40 | 21 | 8 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeFamilies #-}
-- |
-- Module: $HEADER$
-- Description: TODO
-- Copyright: (c) 2016, Peter Trško
-- License: BSD3
--
-- Maintainer: [email protected]
-- Stability: experimental
-- Portability: MultiParamTypeClasses, NoImplicitPrelude, TypeFamilies
--
-- TODO
module DataAnalysis.Decode
( module DataAnalysis.Decode.Class
, module DataAnalysis.Decode.Aeson
, module DataAnalysis.Decode.Cassava
, decodeFile
, decodeFileStrict
)
where
import Control.Monad ((>=>))
import System.IO (IO, FilePath)
import qualified Data.ByteString as Strict.ByteString
import qualified Data.ByteString.Lazy as Lazy.ByteString
import DataAnalysis.Decode.Aeson hiding
( aesonDecode
, aesonDecodeStrict
, aesonEitherDecode
, aesonEitherDecodeStrict
)
import DataAnalysis.Decode.Cassava hiding
( cassavaEitherDecode
, cassavaEitherDecodeNamed
)
import DataAnalysis.Decode.Class
decodeFile
:: Decode e c
=> proxy e
-> DecodingParams e
-> FilePath
-> IO c
decodeFile proxy params = Lazy.ByteString.readFile >=> decodeIO proxy params
decodeFileStrict
:: Decode e c
=> proxy e
-> DecodingParams e
-> FilePath
-> IO c
decodeFileStrict proxy params =
Strict.ByteString.readFile >=> decodeStrictIO proxy params
| trskop/data-analysis | src/DataAnalysis/Decode.hs | bsd-3-clause | 1,404 | 0 | 9 | 281 | 251 | 151 | 100 | 37 | 1 |
module Entity.Bound where
import qualified Data.List as L
import qualified Gamgine.Math.BoxTree as BT
import qualified Gamgine.Math.Box as B
import qualified GameData.Entity as E
import qualified GameData.Animation as A
import qualified Entity.Position as EP
bound :: E.Entity -> E.Bound
bound E.Player {E.playerPosition = pos, E.playerBound = bound} =
bound `BT.moveBy` pos
bound [email protected] {E.enemyBound = bound} =
BT.Leaf (bound `B.moveBy` EP.currentPosition e) E.Whatever
bound [email protected] {E.platformBound = bound} =
BT.Leaf (bound `B.moveBy` EP.currentPosition p) E.Whatever
bound E.Star {E.starPosition = pos, E.starBound = bound} =
BT.Leaf (bound `B.moveBy` pos) E.Whatever
| dan-t/layers | src/Entity/Bound.hs | bsd-3-clause | 699 | 0 | 9 | 105 | 253 | 149 | 104 | 16 | 1 |
module Connection where
import Prelude ()
import Prelude.MH
import Brick.BChan
import Control.Concurrent ( forkIO, threadDelay )
import qualified Control.Concurrent.STM as STM
import Control.Exception ( SomeException, catch )
import qualified Data.HashMap.Strict as HM
import Data.Int (Int64)
import Data.Semigroup ( Max(..) )
import qualified Data.Text as T
import Data.Time ( UTCTime(..), secondsToDiffTime, getCurrentTime
, diffUTCTime )
import Data.Time.Calendar ( Day(..) )
import Network.Mattermost.Types ( ChannelId )
import qualified Network.Mattermost.WebSocket as WS
import Constants
import Types
connectWebsockets :: MH ()
connectWebsockets = do
st <- use id
session <- getSession
logger <- mhGetIOLogger
liftIO $ do
let shunt (Left msg) = writeBChan (st^.csResources.crEventQueue) (WebsocketParseError msg)
shunt (Right e) = writeBChan (st^.csResources.crEventQueue) (WSEvent e)
runWS = WS.mmWithWebSocket session shunt $ \ws -> do
writeBChan (st^.csResources.crEventQueue) WebsocketConnect
processWebsocketActions st ws 1 HM.empty
void $ forkIO $ runWS `catch` handleTimeout logger 1 st
`catch` handleError logger 5 st
-- | Take websocket actions from the websocket action channel in the ChatState and
-- | send them to the server over the websocket.
-- | Takes and propagates the action sequence number which in incremented for
-- | each successful send.
-- | Keeps and propagates a map of channel id to last user_typing notification send time
-- | so that the new user_typing actions are throttled to be send only once in two seconds.
processWebsocketActions :: ChatState -> WS.MMWebSocket -> Int64 -> HashMap ChannelId (Max UTCTime) -> IO ()
processWebsocketActions st ws s userTypingLastNotifTimeMap = do
action <- STM.atomically $ STM.readTChan (st^.csResources.crWebsocketActionChan)
if (shouldSendAction action)
then do
WS.mmSendWSAction (st^.csResources.crConn) ws $ convert action
now <- getCurrentTime
processWebsocketActions st ws (s + 1) $ userTypingLastNotifTimeMap' action now
else do
processWebsocketActions st ws s userTypingLastNotifTimeMap
where
convert (UserTyping _ cId pId) = WS.UserTyping s cId pId
shouldSendAction (UserTyping ts cId _) =
diffUTCTime ts (userTypingLastNotifTime cId) >= (userTypingExpiryInterval / 2 - 0.5)
userTypingLastNotifTime cId = getMax $ HM.lookupDefault (Max zeroTime) cId userTypingLastNotifTimeMap
zeroTime = UTCTime (ModifiedJulianDay 0) (secondsToDiffTime 0)
userTypingLastNotifTimeMap' (UserTyping _ cId _) now =
HM.insertWith (<>) cId (Max now) userTypingLastNotifTimeMap
handleTimeout :: (LogCategory -> Text -> IO ()) -> Int -> ChatState -> WS.MMWebSocketTimeoutException -> IO ()
handleTimeout logger seconds st e = do
logger LogWebsocket $ T.pack $ "Websocket timeout exception: " <> show e
reconnectAfter seconds st
handleError :: (LogCategory -> Text -> IO ()) -> Int -> ChatState -> SomeException -> IO ()
handleError logger seconds st e = do
logger LogWebsocket $ T.pack $ "Websocket error: " <> show e
reconnectAfter seconds st
reconnectAfter :: Int -> ChatState -> IO ()
reconnectAfter seconds st = do
writeBChan (st^.csResources.crEventQueue) WebsocketDisconnect
threadDelay (seconds * 1000 * 1000)
writeBChan (st^.csResources.crEventQueue) RefreshWebsocketEvent
| aisamanra/matterhorn | src/Connection.hs | bsd-3-clause | 3,589 | 0 | 20 | 783 | 957 | 494 | 463 | -1 | -1 |
{-# OPTIONS_GHC -Wall -fno-warn-unused-do-bind #-}
module Parse.Type where
import Data.List (intercalate)
import Text.Parsec ((<|>), (<?>), char, many1, string, try)
import Parse.Helpers
import qualified Reporting.Annotation as A
import AST.V0_16
tvar :: IParser Type
tvar =
addLocation
(TypeVariable <$> lowVar <?> "a type variable")
tuple :: IParser Type
tuple =
addLocation $
do types <- parens'' expr
case types of
Left comments ->
return $ UnitType comments
Right [] ->
return $ UnitType []
Right [Commented [] t []] ->
return $ A.drop t
Right [t] ->
return $ TypeParens t
Right types' ->
return $ TupleType types'
record :: IParser Type
record =
addLocation $
do char '{'
pushNewlineContext
(_, pre) <- whitespace
body <- extended <|> normal
post <- dumbWhitespace
char '}'
sawNewline <- popNewlineContext
return $ body pre post sawNewline
where
normal =
do
fields <- commaSep field
return $ \pre post sawNewline ->
case fields pre post of
[] ->
EmptyRecordType (pre ++ post)
fields' ->
RecordType fields' sawNewline
-- extended record types require at least one field
extended =
do (ext, postBase) <-
try $
do
ext <- lowVar
(_, postBase) <- whitespace
_ <- string "|"
return (ext, postBase)
(_, preFields) <- whitespace
fields <- commaSep1 field
return $ \pre post sawNewline ->
RecordExtensionType
(Commented pre ext postBase)
(fields preFields post)
sawNewline
field =
do pushNewlineContext
lbl <- rLabel
(_, postLbl) <- whitespace
_ <- hasType
(_, preExpr) <- whitespace
val <- expr
sawNewline <- popNewlineContext
return $ \preLbl postExpr ->
( Commented preLbl lbl postLbl
, Commented preExpr val postExpr
, sawNewline
)
capTypeVar :: IParser String
capTypeVar =
intercalate "." <$> dotSep1 capVar
constructor0 :: IParser TypeConstructor
constructor0 =
do name <- capTypeVar
return (NamedConstructor name)
constructor0' :: IParser Type
constructor0' =
addLocation $
do ctor <- capTypeVar
return (TypeVariable ctor)
term :: IParser Type
term =
tuple <|> record <|> tvar <|> constructor0'
tupleCtor :: IParser TypeConstructor
tupleCtor =
do ctor <- parens' (many1 (char ','))
return (TupleConstructor (length ctor + 1))
app :: IParser Type
app =
addLocation $
do f <- constructor0 <|> try tupleCtor <?> "a type constructor"
args <- spacePrefix term
return $ TypeConstruction f args
expr :: IParser Type
expr =
do
result <- separated rightArrow (app <|> term)
return $
case result of
Left t ->
t
Right (region, first, rest, final) ->
A.A region $ FunctionType first rest final
constructor :: IParser (String, [(Comments, Type)])
constructor =
(,) <$> (capTypeVar <?> "another type constructor")
<*> spacePrefix term
| fredcy/elm-format | parser/src/Parse/Type.hs | bsd-3-clause | 3,357 | 0 | 16 | 1,143 | 979 | 486 | 493 | 112 | 5 |
{- Copyright (c) 2008 David Roundy
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the author nor the names of his contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE. -}
{-# OPTIONS_GHC -fomit-interface-pragmas #-}
module Distribution.Franchise.SplitFile
( splitFile, mapDirectory, mapDirectory_ )
where
import Data.List ( isSuffixOf )
import Distribution.Franchise.Buildable
import Distribution.Franchise.ConfigureState
import Distribution.Franchise.Util
-- | Create a build target for test suites.
splitFile :: String -> (String -> [(FilePath, String)]) -> C [FilePath]
splitFile fn _ | ".splits" `isSuffixOf` fn = return []
splitFile fn _ | "~" `isSuffixOf` fn = return []
splitFile fn splitfun =
whenC (isFile fn) $
do withd <- rememberDirectory
rule [fnsplits] [fn] $ withd splitf
processFilePath fnsplits >>= build' CannotModifyState
ss <- readSplits
case ss of
[] -> return ()
(s:_) -> do addTarget $ ss :< [fn,fnsplits]
|<- defaultRule { make = const $ withd $ splitf }
processFilePath s >>= build' CannotModifyState
return ss
where fnsplits = fn++".splits"
splitf = do x <- cat fn
let splits = splitfun x
mapM (uncurry writeF) splits
-- we use writeFile rather than writeF because
-- we want the timestamp always to change, so we
-- won't have to re-run this next time.
fnsplits' <- processFilePath fnsplits
io $ writeFile fnsplits' $ show $ map fst splits
readSplits = do x <- cat fnsplits
case reads x of
[(y,"")] -> return y
_ -> fail $ "unable to read "++fnsplits
-- | Run the provided action on each file in the specified directory.
mapDirectory :: (FilePath -> C a) -> FilePath -> C [a]
mapDirectory f d = withDirectory d $ do xs <- ls "."
mapM f xs
mapDirectory_ :: (FilePath -> C a) -> FilePath -> C ()
mapDirectory_ f d = withDirectory d $ do xs <- ls "."
mapM_ f xs
| droundy/franchise | Distribution/Franchise/SplitFile.hs | bsd-3-clause | 3,540 | 0 | 17 | 977 | 571 | 283 | 288 | 38 | 3 |
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
import Language.Haskell.Liquid.Prelude
--------------------------------------------------------------------
-------------- Defining A List Type --------------------------------
--------------------------------------------------------------------
[lq| data List [llen] a <p :: x0:a -> x1:a -> Prop>
= Nil
| Cons (h :: a) (t :: List <p> (a <p h>))
|]
[lq| measure llen :: (List a) -> Int
llen(Nil) = 0
llen(Cons x xs) = 1 + (llen xs)
|]
[lq| invariant {v:(List a) | ((llen v) >= 0)} |]
data List a
= Nil
| Cons a (List a)
checkSort Nil
= True
checkSort (_ `Cons` Nil)
= True
checkSort (x1 `Cons` (x2 `Cons` xs))
= liquidAssertB (x1 <= x2) && checkSort (x2 `Cons` xs)
xs0 :: List Int
xs0 = Nil
prop0 = checkSort xs0
xs1 = 4 `Cons` Nil
prop1 = checkSort xs1
xs2 = 2 `Cons` (4 `Cons` Nil)
prop2 = checkSort xs2
----------------------------------------------------------------
----------------- Insertion Sort -------------------------------
----------------------------------------------------------------
insert y Nil
= y `Cons` Nil
insert y (Cons x xs)
| y <= x = y `Cons` (x `Cons` xs)
| otherwise = x `Cons` (insert y xs)
insertSort = foldr insert Nil
bar3 = insertSort $ map choose [1 .. 10]
prop3 = checkSort bar3
| spinda/liquidhaskell | tests/gsoc15/unknown/pos/ListISort-LType.hs | bsd-3-clause | 1,395 | 3 | 9 | 324 | 327 | 188 | 139 | 30 | 1 |
module Text.Roundtrip.Classes where
import Prelude hiding ((<*>), pure)
import Data.Eq (Eq)
import Data.Char (Char)
import Data.Text as T
import Data.XML.Types (Name(..), Content)
import Control.Isomorphism.Partial (IsoFunctor)
infixl 3 <|>
infixl 3 <||>
infixr 6 <*>
class ProductFunctor f where
(<*>) :: f alpha -> f beta -> f (alpha, beta)
class Alternative f where
-- one token lookahead for lhs
(<|>) :: f alpha -> f alpha -> f alpha
x <|> y = x <||> y
-- infinite lookahead for lhs
(<||>) :: f alpha -> f alpha -> f alpha
empty :: f alpha
class (IsoFunctor delta, ProductFunctor delta, Alternative delta)
=> Syntax delta where
-- (<$>) :: Iso alpha beta -> delta alpha -> delta beta
-- (<*>) :: delta alpha -> delta beta -> delta (alpha, beta)
-- (<|>) :: delta alpha -> delta alpha -> delta alpha
-- empty :: delta alpha
pure :: Eq alpha => alpha -> delta alpha
rule :: String -> delta beta -> delta alpha -> delta alpha
rule _ _ x = x
ruleInfix :: String -> delta beta -> delta gamma -> delta alpha -> delta alpha
ruleInfix _ _ _ x = x
class Syntax delta => StringSyntax delta where
token :: (Char -> Bool) -> delta Char
anyToken :: delta Char
anyToken = token (const True)
type Attribute = (Name, [Content])
class Syntax delta => XmlSyntax delta where
xmlBeginDoc :: delta ()
xmlEndDoc :: delta ()
xmlBeginElem :: Name -> delta ()
xmlEndElem :: Name -> delta ()
xmlAttrValue :: Name -> delta T.Text -- FIXME: parser for attr value
xmlTextNotEmpty :: delta T.Text
| skogsbaer/roundtrip | src/Text/Roundtrip/Classes.hs | bsd-3-clause | 1,566 | 0 | 11 | 361 | 512 | 271 | 241 | 36 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
module Ticket.Site
( routes
) where
import Data.ByteString (ByteString)
import Data.ByteString.Char8 (unpack)
import Snap.Core
import Snap.Snaplet
import Snap.Snaplet.Auth
import Snap.Snaplet.PostgresqlSimple (Only (..), execute, query,
query_)
import Text.Read
import Application
import Data.Aeson (decode')
import Layout (renderWithLayout)
import Ticket.Query (allClients, allProductAreas,
allTickets, createTicket,
deleteTicket, ticketById,
updateTicket)
import Ticket.Types (Client (..), Ticket (..),
formatTargetDate)
import Ticket.View (ticketIndexView)
import Ticket.View.Form (ticketForm)
index :: Handler App (AuthManager App) ()
index = do
tickets <- query_ allTickets
renderWithLayout $ ticketIndexView tickets
new :: Handler App (AuthManager App) ()
new = do
clients <- query_ allClients
productAreas <- query_ allProductAreas
renderWithLayout $ ticketForm clients productAreas Nothing
create :: Handler App (AuthManager App) ()
create = do
ticketObject <- readRequestBody tenKBytes
let maybeTicket = (decode' ticketObject :: Maybe Ticket)
case maybeTicket of
Nothing -> modifyResponse $ setResponseStatus 400 "Bad Data"
Just (Ticket{..}) -> do
execute createTicket ( ticketTitle
, ticketDescription
, clientName ticketClient
, clientName ticketClient
, formatTargetDate $ ticketTargetDate
, ticketURL
, show ticketProductArea
)
modifyResponse $ setResponseStatus 200 "Successfully Created Ticket"
where
tenKBytes = 10 * 1000
update :: Handler App (AuthManager App) ()
update = do
ticketObject <- readRequestBody tenKBytes
let maybeTicket = (decode' ticketObject :: Maybe Ticket)
case maybeTicket of
Nothing -> modifyResponse $ setResponseStatus 400 "Bad Data"
Just ticket -> do
execute updateTicket ticket
modifyResponse $ setResponseStatus 200 "Successfully Updated Ticket"
where
tenKBytes = 10 * 1000
edit :: Handler App (AuthManager App) ()
edit = do
maybeTicketIdParam <- getParam "ticketId"
case (maybeTicketIdParam >>= readMaybe . unpack) of
Nothing -> modifyResponse $ setResponseStatus 400 "Invalid Request Parameter"
Just ticketIdParam -> do
[ticket] <- query ticketById (Only (ticketIdParam :: Int))
clients <- query_ allClients
productAreas <- query_ allProductAreas
renderWithLayout $ ticketForm clients productAreas (Just ticket)
delete :: Handler App (AuthManager App) ()
delete = do
maybeTicketIdParam <- getParam "ticketId"
case (maybeTicketIdParam >>= readMaybe . unpack) of
Nothing -> modifyResponse $ setResponseStatus 400 "Invalid Request Parameter"
Just ticketId -> do
execute deleteTicket (Only (ticketId :: Int))
redirect "/tickets/index"
routes :: [(ByteString, Handler App App ())]
routes = [ ("/tickets/index", with auth index)
, ("/tickets/new", with auth new)
, ("/tickets/create", with auth create)
, ("/tickets/:ticketId/edit", with auth edit)
, ("/tickets/update", with auth update)
, ("/tickets/:ticketId/delete", with auth delete)
]
| ExternalReality/features | src/Ticket/Site.hs | bsd-3-clause | 3,927 | 0 | 16 | 1,326 | 916 | 475 | 441 | 84 | 2 |
module SyntaxHighlighting.AsLatexPt where
import Utils.Utils
import Data.Char
import TypeSystem
import SyntaxHighlighting.Coloring
import SyntaxHighlighting.Renderer
import Text.PrettyPrint.ANSI.Leijen
data LatexRenderer = LatexRenderer FullColoring SyntaxStyle
instance Renderer LatexRenderer where
create = LatexRenderer
name _ = "LaTeX"
renderParseTree pt (LatexRenderer fc style)
= text $ renderPT fc style pt
renderParseTree' pt (LatexRenderer fc style)
= text $ renderPT fc style (deAnnot pt)
renderParseTreeDebug pt (LatexRenderer fc style)
= error "RenderPTDebug not supported"
renderString styleName str (LatexRenderer fc _)
= text $ renderWithStyle fc styleName str
supported _ = effects |> fst
renderPT :: FullColoring -> SyntaxStyle -> ParseTree -> String
renderPT fc style pt
= determineStyle' style pt
||>> renderWithStyle fc & cascadeAnnot (renderWithStyle fc "")
& _renderPart & wrapper
wrapper :: String -> String
wrapper str
= "{\\setlength{\\fboxsep}{0pt}"++str++"}"
_renderPart :: ParseTreeA (String -> String) -> String
_renderPart (MLiteral effect _ conts)
= conts & escape & effect
_renderPart (MInt effect inf i)
= _renderPart (MLiteral effect inf $ show i)
_renderPart (PtSeq effect _ pts)
= pts |> _renderPart & unwords & effect
renderWithStyle :: FullColoring -> Name -> String -> String
renderWithStyle fc style str
= let effect = effects |> runProp fc style & chain in
effect str
runProp :: FullColoring -> Name -> (Name, Either Int String -> String -> String) -> String -> String
runProp _ _ _ "" = ""
runProp _ _ _ " " = " "
runProp fc style (key, effect) contents
= let mval = getProperty fc style key
contValue
= maybe contents (`effect` contents) mval
in
contValue
effects :: [(Name, Either Int String -> String -> String)]
effects
= [ ("foreground-color", \value contents -> "\\color[HTML]{" ++ color value ++ "}"++contents)
, ("background-color", \value contents -> "\\colorbox[HTML]{"++ color value ++ "}{"++contents++"}")
, ("font-decoration", fontdecoration)
, ("font-style", fontstyle)
, ("font-size", fontsize)
, ("special", special)
]
special :: Either Int String -> String -> String
special (Right "hline") _
= "\\rule"
special _ str
= str
fontsize :: Either Int String -> String -> String
fontsize (Left i) str
= let commands = fontsizes & filter ((<=) i . fst)
command = if null commands then "Huge" else head commands & snd in
"\\"++command++"{"++str++"}"
fontsize _ str = str
fontsizes
= [ (6, "tiny")
, (8, "scriptsize")
, (10, "footnotesize")
, (11, "small")
, (12, "normalsize")
, (14, "large")
, (17, "Large")
, (21, "LARGE")
, (25, "huge")
]
fontstyle :: Either Int String -> String -> String
fontstyle (Right ('"':v)) str
= fontstyle (Right $ init v) str
fontstyle (Right "bold") str
= "\\textbf{"++str++"}"
fontstyle (Right "italic") str
= "\\emph{"++str++"}"
fontstyle (Right "monospace") str
= "\\texttt{"++str++"}"
fontstyle (Right []) str
= str
fontstyle (Right vals) str
= let (prop, rest) = break (==',') vals in
fontstyle (Right prop) $ fontstyle (Right $ dropWhile (`elem` " ,") rest) str
fontstyle _ str
= str
fontdecoration :: Either Int String -> String -> String
fontdecoration (Right "underline") str
= "\\underline{"++str++"}"
fontdecoration _ str
= str
color :: Either Int String -> String
color (Left i)
= intAsColor i
color (Right s)
= s & tail |> toUpper
escape :: String -> String
escape "" = ""
escape ('\\':str)
= "\\textbackslash" ++ escape str
escape ('{':str)
= "\\{" ++ escape str
escape ('}':str)
="\\}" ++ escape str
escape (c:str)
= c : escape str
| pietervdvn/ALGT | src/SyntaxHighlighting/AsLatexPt.hs | bsd-3-clause | 3,663 | 129 | 13 | 678 | 1,527 | 796 | 731 | 112 | 2 |
module Crete.Product.Product where
import Text.ParserCombinators.Parsec (parse)
import Data.Maybe (catMaybes)
import Data.Either (partitionEithers)
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Crete.Product.ProductParser as PP
import Crete.Store.StoreTypes (ProductMap, Product(..))
import Crete.Utility (trimm, readMaybe)
newtype ProductError = ProductError (Maybe [String]) deriving (Show)
parseProduct :: FilePath -> String -> ([String], ProductMap)
parseProduct file input =
case parse (PP.csvFile ',') file input of
Right res ->
let (ls, rs) = partitionEithers (map f res)
in (catMaybes ls, Map.fromList rs)
Left msg -> (["Irgendwas lief schief! Prüfen Sie das Format Ihrer Produktlisten ...", show msg], Map.empty)
where g ',' = '.'
g x = x
f xs@[name, qty, desc, pic, unit, price] =
case (readMaybe qty, readMaybe (map g price)) of
(Just q, Just p) ->
Right $ (,)
(trimm name)
(Product q (trimm desc) (trimm pic) (trimm unit) p)
_ -> Left $ errorLine xs
f [] = Left Nothing
f xs = Left $ errorLine xs
errorLine xs = Just $ '"' : List.intercalate "\", \"" xs ++ ['"'] | fphh/crete | src/Crete/Product/Product.hs | bsd-3-clause | 1,298 | 0 | 15 | 352 | 457 | 250 | 207 | 29 | 6 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Time.TimeZone.Parse
( parseTimezone
) where
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Data.String
import Data.Text (Text)
import Data.Time (TimeZone(..))
import Prelude
-- `TimeZone` reads anything but only accepts timezones known
-- from the provided locale.
parseTimezone :: Text -> Maybe TimeZone
parseTimezone x = HashMap.lookup x tzs
tzs :: HashMap Text TimeZone
tzs = HashMap.fromList
[ ( "YEKT", TimeZone 300 False "YEKT" )
, ( "YEKST", TimeZone 360 True "YEKST" )
, ( "YAKT", TimeZone 540 False "YAKT" )
, ( "YAKST", TimeZone 600 True "YAKST" )
, ( "WITA", TimeZone 480 False "WITA" )
, ( "WIT", TimeZone 420 False "WIT" )
, ( "WIB", TimeZone 420 False "WIB" )
, ( "WGT", TimeZone (-180) False "WGT" )
, ( "WGST", TimeZone (-120) True "WGST" )
, ( "WFT", TimeZone 720 False "WFT" )
, ( "WET", TimeZone 0 False "WET" )
, ( "WEST", TimeZone 60 True "WEST" )
, ( "WAT", TimeZone 60 False "WAT" )
, ( "WAST", TimeZone 120 True "WAST" )
, ( "VUT", TimeZone 660 False "VUT" )
, ( "VLAT", TimeZone 660 False "VLAT" )
, ( "VLAST", TimeZone 660 True "VLAST" )
, ( "VET", TimeZone (-270) False "VET" )
, ( "UZT", TimeZone 300 False "UZT" )
, ( "UYT", TimeZone (-180) False "UYT" )
, ( "UYST", TimeZone (-120) True "UYST" )
, ( "UTC", TimeZone 0 False "UTC" )
, ( "ULAT", TimeZone 480 False "ULAT" )
, ( "TVT", TimeZone 720 False "TVT" )
, ( "TMT", TimeZone 300 False "TMT" )
, ( "TLT", TimeZone 540 False "TLT" )
, ( "TKT", TimeZone 780 False "TKT" )
, ( "TJT", TimeZone 300 False "TJT" )
, ( "TFT", TimeZone 300 False "TFT" )
, ( "TAHT", TimeZone (-600) False "TAHT" )
, ( "SST", TimeZone (-660) False "SST" )
, ( "SRT", TimeZone (-180) False "SRT" )
, ( "SGT", TimeZone 480 False "SGT" )
, ( "SCT", TimeZone 240 False "SCT" )
, ( "SBT", TimeZone 660 False "SBT" )
, ( "SAST", TimeZone 120 False "SAST" )
, ( "SAMT", TimeZone 300 False "SAMT" )
, ( "RET", TimeZone 240 False "RET" )
, ( "PYT", TimeZone (-240) False "PYT" )
, ( "PYST", TimeZone (-180) True "PYST" )
, ( "PWT", TimeZone (-420) True "PWT" )
, ( "PST", TimeZone (-480) False "PST" )
, ( "PONT", TimeZone 660 False "PONT" )
, ( "PMST", TimeZone (-180) False "PMST" )
, ( "PMDT", TimeZone (-120) True "PMDT" )
, ( "PKT", TimeZone 300 False "PKT" )
, ( "PHT", TimeZone 480 False "PHT" )
, ( "PHOT", TimeZone 780 False "PHOT" )
, ( "PGT", TimeZone 600 False "PGT" )
, ( "PETT", TimeZone 720 False "PETT" )
, ( "PETST", TimeZone 720 True "PETST" )
, ( "PET", TimeZone (-300) False "PET" )
, ( "PDT", TimeZone (-420) False "PDT" )
, ( "OMST", TimeZone 360 False "OMST" )
, ( "OMSST", TimeZone 420 True "OMSST" )
, ( "NZST", TimeZone 720 False "NZST" )
, ( "NZDT", TimeZone 780 False "NZDT" )
, ( "NUT", TimeZone (-660) False "NUT" )
, ( "NST", TimeZone (-660) False "NST" )
, ( "NPT", TimeZone (-600) True "NPT" )
, ( "NOVT", TimeZone 360 False "NOVT" )
, ( "NOVST", TimeZone 420 True "NOVST" )
, ( "NFT", TimeZone 690 False "NFT" )
, ( "NDT", TimeZone (-150) True "NDT" )
, ( "NCT", TimeZone 660 False "NCT" )
, ( "MYT", TimeZone 480 False "MYT" )
, ( "MVT", TimeZone 300 False "MVT" )
, ( "MUT", TimeZone 240 False "MUT" )
, ( "MST", TimeZone (-420) False "MST" )
, ( "MSK", TimeZone 180 False "MSK" )
, ( "MSD", TimeZone 240 True "MSD" )
, ( "MMT", TimeZone 390 False "MMT" )
, ( "MHT", TimeZone 720 False "MHT" )
, ( "MDT", TimeZone (-360) True "MDT" )
, ( "MAWT", TimeZone 300 False "MAWT" )
, ( "MART", TimeZone (-570) False "MART" )
, ( "MAGT", TimeZone 600 False "MAGT" )
, ( "MAGST", TimeZone 720 True "MAGST" )
, ( "LINT", TimeZone 840 False "LINT" )
, ( "LHST", TimeZone 630 False "LHST" )
, ( "LHDT", TimeZone 660 True "LHDT" )
, ( "KUYT", TimeZone 180 False "KUYT" )
, ( "KST", TimeZone 540 False "KST" )
, ( "KRAT", TimeZone 420 False "KRAT" )
, ( "KRAST", TimeZone 480 True "KRAST" )
, ( "KGT", TimeZone 360 False "KGT" )
, ( "JST", TimeZone 540 False "JST" )
, ( "IST", TimeZone 330 False "IST" )
, ( "IRST", TimeZone 210 False "IRST" )
, ( "IRKT", TimeZone 480 False "IRKT" )
, ( "IRKST", TimeZone 540 True "IRKST" )
, ( "IRDT", TimeZone 270 True "IRDT" )
, ( "IOT", TimeZone 360 False "IOT" )
, ( "IDT", TimeZone 180 True "IDT" )
, ( "ICT", TimeZone 420 False "ICT" )
, ( "HOVT", TimeZone 420 False "HOVT" )
, ( "HKT", TimeZone 480 False "HKT" )
, ( "GYT", TimeZone (-240) False "GYT" )
, ( "GST", TimeZone 240 False "GST" )
, ( "GMT", TimeZone 0 False "GMT" )
, ( "GILT", TimeZone 720 False "GILT" )
, ( "GFT", TimeZone (-180) False "GFT" )
, ( "GET", TimeZone 240 False "GET" )
, ( "GAMT", TimeZone (-540) False "GAMT" )
, ( "GALT", TimeZone (-360) False "GALT" )
, ( "FNT", TimeZone (-120) False "FNT" )
, ( "FKT", TimeZone (-240) False "FKT" )
, ( "FKST", TimeZone (-180) False "FKST" )
, ( "FJT", TimeZone 720 False "FJT" )
, ( "FJST", TimeZone 780 True "FJST" )
, ( "EST", TimeZone (-300) False "EST" )
, ( "EGT", TimeZone (-60) False "EGT" )
, ( "EGST", TimeZone 0 True "EGST" )
, ( "EET", TimeZone 120 False "EET" )
, ( "EEST", TimeZone 180 True "EEST" )
, ( "EDT", TimeZone (-240) True "EDT" )
, ( "ECT", TimeZone (-300) False "ECT" )
, ( "EAT", TimeZone 180 False "EAT" )
, ( "EAST", TimeZone (-300) False "EAST" )
, ( "EASST", TimeZone (-300) True "EASST" )
, ( "DAVT", TimeZone 420 False "DAVT" )
, ( "ChST", TimeZone 600 False "ChST" )
, ( "CXT", TimeZone 420 False "CXT" )
, ( "CVT", TimeZone (-60) False "CVT" )
, ( "CST", TimeZone (-360) False "CST" )
, ( "COT", TimeZone (-300) False "COT" )
, ( "CLT", TimeZone (-180) False "CLT" )
, ( "CLST", TimeZone (-180) True "CLST" )
, ( "CKT", TimeZone (-600) False "CKT" )
, ( "CHAST", TimeZone 765 False "CHAST" )
, ( "CHADT", TimeZone 825 True "CHADT" )
, ( "CET", TimeZone 60 False "CET" )
, ( "CEST", TimeZone 120 True "CEST" )
, ( "CDT", TimeZone (-300) True "CDT" )
, ( "CCT", TimeZone 390 False "CCT" )
, ( "CAT", TimeZone 120 False "CAT" )
, ( "CAST", TimeZone 180 True "CAST" )
, ( "BTT", TimeZone 360 False "BTT" )
, ( "BST", TimeZone 60 False "BST" )
, ( "BRT", TimeZone (-180) False "BRT" )
, ( "BRST", TimeZone (-120) True "BRST" )
, ( "BOT", TimeZone (-240) False "BOT" )
, ( "BNT", TimeZone 480 False "BNT" )
, ( "AZT", TimeZone 240 False "AZT" )
, ( "AZST", TimeZone 300 True "AZST" )
, ( "AZOT", TimeZone (-60) False "AZOT" )
, ( "AZOST", TimeZone 0 True "AZOST" )
, ( "AWST", TimeZone 480 False "AWST" )
, ( "AWDT", TimeZone 540 True "AWDT" )
, ( "AST", TimeZone (-240) False "AST" )
, ( "ART", TimeZone (-180) False "ART" )
, ( "AQTT", TimeZone 300 False "AQTT" )
, ( "ANAT", TimeZone 720 False "ANAT" )
, ( "ANAST", TimeZone 720 True "ANAST" )
, ( "AMT", TimeZone 240 False "AMT" )
, ( "AMST", TimeZone 300 True "AMST" )
, ( "ALMT", TimeZone 360 False "ALMT" )
, ( "AKST", TimeZone (-540) False "AKST" )
, ( "AKDT", TimeZone (-480) True "AKDT" )
, ( "AFT", TimeZone 270 False "AFT" )
, ( "AEST", TimeZone 600 False "AEST" )
, ( "AEDT", TimeZone 660 True "AEDT" )
, ( "ADT", TimeZone (-180) True "ADT" )
, ( "ACST", TimeZone 570 False "ACST" )
, ( "ACDT", TimeZone 630 True "ACDT" )
]
| facebookincubator/duckling | Duckling/Time/TimeZone/Parse.hs | bsd-3-clause | 7,587 | 0 | 10 | 1,760 | 3,020 | 1,715 | 1,305 | 178 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
module Error
(
PullE(..),
CommandError(..),
putErr
)
where
import System.IO
import System.Exit (ExitCode(..))
import Data.Typeable
import Control.Exception
import Data.ConfigFile
data CommandError =
ProjectExist
| NoProject
| PatchingError
| DiffError ExitCode
| NothingToCommit
| ServerAlreadyStarted
| ServerNotStarted
| CanNotConnect (String, String)
deriving (Eq, Typeable)
data PullE =
UncommitedChanges
| MergeError
| PatchError
| OtherError
deriving (Eq, Typeable)
instance Exception PullE
instance Exception CommandError
instance Exception CPErrorData
instance Show PullE where
show UncommitedChanges = "Uncommited Changes."
show MergeError = "The pulled commit create conflicts."
show PatchError = "An error occured while patching a pulled commit."
show _ = "An error occured."
instance Show CommandError where
show ProjectExist = "Project already exist."
show NoProject = "No Project here."
show PatchingError = "An error occured while patching commits."
show (DiffError x) = case x of
ExitFailure 1 -> "Differences were found."
ExitFailure _ -> "An error occured."
show NothingToCommit = "No change to commit."
show ServerAlreadyStarted = "A server has already been started."
show ServerNotStarted = "No server has been started."
show (CanNotConnect (ip, port)) = "Can not connect to " ++ ip ++ ":" ++ port
show _ = "An error occured."
putErr :: String -> IO ()
putErr = hPutStrLn stderr | lambda-zorn/det | src/Error.hs | bsd-3-clause | 1,519 | 0 | 9 | 287 | 349 | 190 | 159 | 49 | 1 |
{-# LANGUAGE RecordWildCards #-}
module Material where
import Control.Monad (when)
import Foreign.Ptr
import Graphics.GL
import Graphics.GL.Ext.EXT.TextureFilterAnisotropic
import Prelude hiding (any, ceiling)
import Util
import qualified Codec.Picture as JP
import qualified Codec.Picture.Types as JP
import qualified Data.Vector.Storable as SV
newtype GLTextureObject =
GLTextureObject {unGLTextureObject :: GLuint}
data Material =
Material {matDiffuse :: GLTextureObject
,matNormalMap :: GLTextureObject}
data ColorSpace
= SRGB
| Linear
loadTexture :: FilePath -> ColorSpace -> IO GLTextureObject
loadTexture path colorSpace =
do x <- JP.readImage path
case x of
Right dimg ->
do t <- overPtr (glGenTextures 1)
glBindTexture GL_TEXTURE_2D t
glTexParameteri GL_TEXTURE_2D GL_TEXTURE_MIN_FILTER GL_LINEAR_MIPMAP_LINEAR
glTexParameteri GL_TEXTURE_2D GL_TEXTURE_MAG_FILTER GL_LINEAR
glPixelStorei GL_UNPACK_LSB_FIRST 0
glPixelStorei GL_UNPACK_SWAP_BYTES 0
glPixelStorei GL_UNPACK_ROW_LENGTH 0
glPixelStorei GL_UNPACK_IMAGE_HEIGHT 0
glPixelStorei GL_UNPACK_SKIP_ROWS 0
glPixelStorei GL_UNPACK_SKIP_PIXELS 0
glPixelStorei GL_UNPACK_SKIP_IMAGES 0
glPixelStorei GL_UNPACK_ALIGNMENT 1
let width =
fromIntegral (JP.dynamicMap JP.imageWidth dimg)
height =
fromIntegral (JP.dynamicMap JP.imageHeight dimg)
glTexStorage2D
GL_TEXTURE_2D
(floor (logBase (2 :: Float)
(fromIntegral (max width height))))
(case colorSpace of
SRGB -> GL_SRGB8
Linear -> GL_RGB32F)
width
height
case dimg of
JP.ImageRGB8 (JP.Image _ _ d) ->
SV.unsafeWith
d
(glTexSubImage2D GL_TEXTURE_2D 0 0 0 width height GL_RGB GL_UNSIGNED_BYTE .
castPtr)
JP.ImageRGBA8 (JP.Image _ _ d) ->
SV.unsafeWith
d
(glTexSubImage2D GL_TEXTURE_2D 0 0 0 width height GL_RGBA GL_UNSIGNED_BYTE .
castPtr)
JP.ImageYCbCr8 img ->
let toRgb8 =
JP.convertPixel :: JP.PixelYCbCr8 -> JP.PixelRGB8
in case JP.pixelMap toRgb8 img of
JP.Image _ _ d ->
SV.unsafeWith
d
(glTexSubImage2D GL_TEXTURE_2D
0
0
0
width
height
GL_RGB
GL_UNSIGNED_BYTE .
castPtr)
_ -> error "Unknown image format"
glGenerateMipmap GL_TEXTURE_2D
when gl_EXT_texture_filter_anisotropic
(glTexParameterf GL_TEXTURE_2D GL_TEXTURE_MAX_ANISOTROPY_EXT 16)
return (GLTextureObject t)
Left e -> error e
activateMaterial :: Material -> IO ()
activateMaterial Material{..} =
do glActiveTexture GL_TEXTURE0
glBindTexture GL_TEXTURE_2D
(unGLTextureObject matDiffuse)
glActiveTexture GL_TEXTURE2
glBindTexture GL_TEXTURE_2D
(unGLTextureObject matNormalMap)
| ocharles/hadoom | hadoom/Material.hs | bsd-3-clause | 3,629 | 0 | 23 | 1,463 | 723 | 355 | 368 | 90 | 6 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Program.Strip
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- This module provides an library interface to the @strip@ program.
module Distribution.Simple.Program.Strip (stripLib, stripExe)
where
import Prelude ()
import Distribution.Compat.Prelude
import Distribution.Simple.Program
import Distribution.Simple.Utils
import Distribution.System
import Distribution.Verbosity
import Distribution.Version
import System.FilePath (takeBaseName)
runStrip :: Verbosity -> ProgramDb -> FilePath -> [String] -> IO ()
runStrip verbosity progDb path args =
case lookupProgram stripProgram progDb of
Just strip -> runProgram verbosity strip (path:args)
Nothing -> unless (buildOS == Windows) $
-- Don't bother warning on windows, we don't expect them to
-- have the strip program anyway.
warn verbosity $ "Unable to strip executable or library '"
++ (takeBaseName path)
++ "' (missing the 'strip' program)"
stripExe :: Verbosity -> Platform -> ProgramDb -> FilePath -> IO ()
stripExe verbosity (Platform _arch os) progdb path =
runStrip verbosity progdb path args
where
args = case os of
OSX -> ["-x"] -- By default, stripping the ghc binary on at least
-- some OS X installations causes:
-- HSbase-3.0.o: unknown symbol `_environ'"
-- The -x flag fixes that.
_ -> []
stripLib :: Verbosity -> Platform -> ProgramDb -> FilePath -> IO ()
stripLib verbosity (Platform arch os) progdb path = do
case os of
OSX -> -- '--strip-unneeded' is not supported on OS X, iOS, AIX, or
-- Solaris. See #1630.
return ()
IOS -> return ()
AIX -> return ()
Solaris -> return ()
Windows -> -- Stripping triggers a bug in 'strip.exe' for
-- libraries with lots identically named modules. See
-- #1784.
return()
Linux | arch == I386 ->
-- Versions of 'strip' on 32-bit Linux older than 2.18 are
-- broken. See #2339.
let okVersion = orLaterVersion (Version [2,18] [])
in case programVersion =<< lookupProgram stripProgram progdb of
Just v | withinRange v okVersion ->
runStrip verbosity progdb path args
_ -> warn verbosity $ "Unable to strip library '"
++ (takeBaseName path)
++ "' (version of 'strip' too old; "
++ "requires >= 2.18 on 32-bit Linux)"
_ -> runStrip verbosity progdb path args
where
args = ["--strip-unneeded"]
| sopvop/cabal | Cabal/Distribution/Simple/Program/Strip.hs | bsd-3-clause | 2,855 | 0 | 20 | 871 | 541 | 283 | 258 | 44 | 8 |
{-# LANGUAGE DeriveDataTypeable, DeriveFoldable, DeriveTraversable, DeriveFunctor #-}
module Language.Haskell.AST.Exts.HSX
where
import Data.Data
import Data.Foldable (Foldable)
import Data.Traversable (Traversable)
import Language.Haskell.AST.Core hiding ( Module, Pat, Exp )
-- | XML extenstions to the @GModule@ type
data Module bind tydecl classreldecl declext mpragext exp id l
= XmlPage l (ModuleName id l) [ModulePragma mpragext id l] (XName id l) [XAttr exp id l] (Maybe (exp id l)) [exp id l]
-- ^ a module consisting of a single XML document. The ModuleName never appears in the source
-- but is needed for semantic purposes, it will be the same as the file name.
| XmlHybrid l (Maybe (ModuleHead id l)) [ModulePragma mpragext id l] [ImportDecl id l] [Decl bind tydecl classreldecl declext id l]
(XName id l) [XAttr exp id l] (Maybe (exp id l)) [exp id l]
-- ^ a hybrid module combining an XML document with an ordinary module
deriving (Eq,Ord,Show,Typeable,Data,Foldable,Traversable,Functor)
-- | XML extensions to the @Pat@ type
data Pat pat id l
= PXTag l (XName id l) [PXAttr pat id l] (Maybe (pat id l)) [pat id l]
-- ^ XML element pattern
| PXETag l (XName id l) [PXAttr pat id l] (Maybe (pat id l))
-- ^ XML singleton element pattern
| PXPcdata l String -- ^ XML PCDATA pattern
| PXPatTag l (pat id l) -- ^ XML embedded pattern
deriving (Eq,Ord,Show,Typeable,Data,Foldable,Traversable,Functor)
-- | An XML attribute in a pattern.
data PXAttr pat id l = PXAttr l (XName id l) (pat id l)
deriving (Eq,Ord,Show,Typeable,Data,Foldable,Traversable,Functor)
-- | The name of an xml element or attribute,
-- possibly qualified with a namespace.
data XName id l
= XName l String -- <name ...
| XDomName l String String -- <dom:name ...
deriving (Eq,Ord,Show,Typeable,Data,Foldable,Traversable,Functor)
-- | An xml attribute, which is a name-expression pair.
data XAttr exp id l = XAttr l (XName id l) (exp id l)
deriving (Eq,Ord,Show,Typeable,Data,Foldable,Traversable,Functor)
-- | XML extensions to the @GExt@ type
data Exp exp id l
= XTag l (XName id l) [XAttr exp id l] (Maybe (exp id l)) [exp id l]
-- ^ xml element, with attributes and children
| XETag l (XName id l) [XAttr exp id l] (Maybe (exp id l))
-- ^ empty xml element, with attributes
| XPcdata l String -- ^ PCDATA child element
| XExpTag l (exp id l) -- ^ escaped haskell expression inside xml
| XChildTag l [exp id l] -- ^ children of an xml element
deriving (Eq,Ord,Show,Typeable,Data,Foldable,Traversable,Functor)
instance Annotated (Module bind tydecl classreldecl declext mpragext exp id) where
ann (XmlPage l _ _ _ _ _ _) = l
ann (XmlHybrid l _ _ _ _ _ _ _ _) = l
instance Annotated (Pat pat id) where
ann p = case p of
PXTag l _ _ _ _ -> l
PXETag l _ _ _ -> l
PXPcdata l _ -> l
PXPatTag l _ -> l
instance Annotated (PXAttr pat id) where
ann (PXAttr l _ _) = l
instance Annotated (XName id) where
ann (XName l _) = l
ann (XDomName l _ _) = l
instance Annotated (XAttr exp id) where
ann (XAttr l _ _) = l
instance Annotated (Exp exp id) where
ann e = case e of
XTag l _ _ _ _ -> l
XETag l _ _ _ -> l
XPcdata l _ -> l
XExpTag l _ -> l
XChildTag l _ -> l
| jcpetruzza/haskell-ast | src/Language/Haskell/AST/Exts/HSX.hs | bsd-3-clause | 3,682 | 0 | 10 | 1,117 | 1,205 | 639 | 566 | 55 | 0 |
module Lava.Smv
( smv
)
where
import Lava.Signal
import Lava.Netlist
import Lava.Generic
import Lava.Sequent
import Lava.Property
import Lava.Error
import Lava.LavaDir
import Lava.Verification
import Data.List
( intersperse
, nub
)
import System.IO
( openFile
, IOMode(..)
, hPutStr
, hClose
)
import Lava.IOBuffering
( noBuffering
)
import Data.IORef
import System.Cmd (system)
import System.Exit (ExitCode(..))
----------------------------------------------------------------
-- smv
smv :: Checkable a => a -> IO ProofResult
smv a =
do checkVerifyDir
noBuffering
(props,_) <- properties a
proveFile defsFile (writeDefinitions defsFile props)
where
defsFile = verifyDir ++ "/circuit.smv"
----------------------------------------------------------------
-- definitions
writeDefinitions :: FilePath -> [Signal Bool] -> IO ()
writeDefinitions file props =
do firstHandle <- openFile firstFile WriteMode
secondHandle <- openFile secondFile WriteMode
var <- newIORef 0
hPutStr firstHandle $ unlines $
[ "-- Generated by Lava"
, ""
, "MODULE main"
]
let new =
do n <- readIORef var
let n' = n+1; v = "w" ++ show n'
n' `seq` writeIORef var n'
return v
define v s =
case s of
Bool True -> op0 "1"
Bool False -> op0 "0"
Inv x -> op1 "!" x
And [] -> define v (Bool True)
And [x] -> op0 x
And xs -> opl "&" xs
Or [] -> define v (Bool False)
Or [x] -> op0 x
Or xs -> opl "|" xs
Xor [] -> define v (Bool False)
Xor xs -> op0 (xor xs)
VarBool s -> do op0 s
hPutStr firstHandle ("VAR " ++ s ++ " : boolean;\n")
DelayBool x y -> delay x y
_ -> wrong Lava.Error.NoArithmetic
where
w i = v ++ "_" ++ show i
op0 s =
hPutStr secondHandle $
"DEFINE " ++ v ++ " := " ++ s ++ ";\n"
op1 op s =
op0 (op ++ "(" ++ s ++ ")")
opl op xs =
op0 (concat (intersperse (" " ++ op ++ " ") xs))
xor [x] = x
xor [x,y] = "!(" ++ x ++ " <-> " ++ y ++ ")"
xor (x:xs) = "(" ++ x ++ " & !("
++ concat (intersperse " | " xs)
++ ") | (!" ++ x ++ " & (" ++ xor xs ++ ")))"
delay x y =
do hPutStr firstHandle ("VAR " ++ v ++ " : boolean;\n")
hPutStr secondHandle $
"ASSIGN init(" ++ v ++ ") := " ++ x ++ ";\n"
++ "ASSIGN next(" ++ v ++ ") := " ++ y ++ ";\n"
outvs <- netlistIO new define (struct props)
hPutStr secondHandle $ unlines $
[ "SPEC AG " ++ outv
| outv <- flatten outvs
]
hClose firstHandle
hClose secondHandle
system ("cat " ++ firstFile ++ " " ++ secondFile ++ " > " ++ file)
system ("rm " ++ firstFile ++ " " ++ secondFile)
return ()
where
firstFile = file ++ "-1"
secondFile = file ++ "-2"
----------------------------------------------------------------
-- primitive proving
proveFile :: FilePath -> IO () -> IO ProofResult
proveFile file before =
do putStr "Smv: "
before
putStr "... "
lavadir <- getLavaDir
x <- system ( lavadir
++ "/Scripts/smv.wrapper "
++ file
++ " -showTime"
)
let res = case x of
ExitSuccess -> Valid
ExitFailure 1 -> Indeterminate
ExitFailure _ -> Falsifiable
putStrLn (show res ++ ".")
return res
----------------------------------------------------------------
-- the end.
| dfordivam/lava | Lava/Smv.hs | bsd-3-clause | 3,975 | 0 | 24 | 1,546 | 1,196 | 583 | 613 | 106 | 16 |
module Database.TokyoCabinet.Sequence where
import Foreign.Ptr
import Foreign.Storable (peek)
import Foreign.Marshal (alloca, mallocBytes, copyBytes)
import Foreign.ForeignPtr
import Database.TokyoCabinet.List.C
import Database.TokyoCabinet.Storable
class Sequence a where
withList :: (Storable s) => a s -> (Ptr LIST -> IO b) -> IO b
peekList' :: (Storable s) => Ptr LIST -> IO (a s)
empty :: (Storable s) => IO (a s)
smap :: (Storable s1, Storable s2) => (s1 -> s2) -> a s1 -> IO (a s2)
instance Sequence List where
withList xs action = withForeignPtr (unTCList xs) action
peekList' tcls = List `fmap` newForeignPtr tclistFinalizer tcls
empty = List `fmap` (c_tclistnew >>= newForeignPtr tclistFinalizer)
smap f tcls =
withForeignPtr (unTCList tcls) $ \tcls' ->
alloca $ \sizbuf ->
do num <- c_tclistnum tcls'
vals <- c_tclistnew
loop tcls' 0 num sizbuf vals
where
loop tcls' n num sizbuf acc
| n < num = do vbuf <- c_tclistval tcls' n sizbuf
vsiz <- peek sizbuf
buf <- mallocBytes (fromIntegral vsiz)
copyBytes buf vbuf (fromIntegral vsiz)
val <- f `fmap` peekPtrLen (buf, vsiz)
withPtrLen val $ uncurry (c_tclistpush acc)
loop tcls' (n+1) num sizbuf acc
| otherwise = List `fmap` newForeignPtr tclistFinalizer acc
instance Sequence [] where
withList xs action =
do list <- c_tclistnew
mapM_ (push list) xs
result <- action list
c_tclistdel list
return result
where
push list val = withPtrLen val $ uncurry (c_tclistpush list)
peekList' tcls = do
vals <- peekList'' tcls []
c_tclistdel tcls
return vals
where
peekList'' lis acc =
alloca $ \sizbuf ->
do val <- c_tclistpop lis sizbuf
siz <- peek sizbuf
if val == nullPtr
then return acc
else do elm <- peekPtrLen (val, siz)
peekList'' lis (elm:acc)
empty = return []
smap f = return . (map f)
| tom-lpsd/tokyocabinet-haskell | Database/TokyoCabinet/Sequence.hs | bsd-3-clause | 2,356 | 0 | 17 | 897 | 754 | 368 | 386 | 53 | 0 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiParamTypeClasses #-} --these two for Isomorphic class
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-} -- necessary for Shapely Generics instances
{-# LANGUAGE TypeOperators #-} -- for our cons synonym
{-# LANGUAGE StandaloneDeriving #-} -- these two for deriving AlsoNormal instances
module Data.Shapely.Classes
where
-- internal module to avoid circular dependencies
import Data.Shapely.Normal.Exponentiation
-- | Instances of the 'Shapely' class have a 'Normal' form representation,
-- made up of @(,)@, @()@ and @Either@, and functions to convert 'from' @a@ and
-- back 'to' @a@ again.
class (Exponent (Normal a))=> Shapely a where
-- | A @Shapely@ instances \"normal form\" representation, consisting of
-- nested product, sum and unit types. Types with a single constructor will
-- be given a 'Product' Normal representation, where types with more than
-- one constructor will be 'Sum's.
--
-- See the documentation for 'Data.Shapely.TH.deriveShapely', and the
-- instances defined here for details.
type Normal a
-- NOTE: the naming here seems backwards but is what's in GHC.Generics
from :: a -> Normal a
to :: Normal a -> a
to na = let a = fanin (constructorsOf a) na in a
-- | Return a structure capable of rebuilding a type @a@ from its 'Normal'
-- representation (via 'fanin').
--
-- This structure is simply the data constructor (or a 'Product' of
-- constructors for 'Sum's), e.g. for @Either@:
--
-- > constructorsOf _ = (Left,(Right,()))
--
-- Satisfies:
--
-- > fanin (constructorsOf a) (from a) == a
constructorsOf :: a -> Normal a :=>-> a
-- Here I walk-through the ways we define 'Shapely' instances; you can also see
-- the documentation for mkShapely for a description.
--
-- Syntactically we can think of the type constructor (in this case (), but
-- usually, e.g. "Foo") becoming (), and getting pushed to the bottom of the
-- stack of its terms (in this case there aren't any).
instance Shapely () where
type Normal () = ()
from = id
--to = id
constructorsOf _ = ()
-- And data constructor arguments appear on the 'fst' positions of nested
-- tuples, finally terminated by a () in the 'snd' place.
-- | Note, the normal form for a tuple is not itself
instance Shapely (x,y) where
type Normal (x,y) = (x,(y,()))
from (x,y) = (x,(y,()))
--to (x,(y,())) = (x,y)
constructorsOf _ = (,)
-- Here, again syntactically, both constructors Left and Right become `()`, and
-- we replace `|` with `Either` creating a sum of products.
instance Shapely (Either x y) where
type Normal (Either x y) = Either (x,()) (y,())
from = let f = flip (,) () in either (Left . f) (Right . f)
--to = either (Left . fst) (Right . fst)
constructorsOf _ = (Left,(Right,()))
-- The Normal form of a type is just a simple unpacking of the constructor
-- terms, and doesn't do anything to express recursive structure. But this
-- simple type function gives us what we need to make use of recursive
-- structure, e.g. in Isomorphic, or by converting to a pattern functor that
-- can be turned into a fixed point with with FunctorOn.
instance Shapely [a] where
-- NOTE: data [] a = [] | a : [a] -- Defined in `GHC.Types'
type Normal [a] = Either () (a,([a],()))
from [] = Left ()
from ((:) a as) = Right (a, (as, ()))
constructorsOf _ = ([],((:),()))
---- Additional instances are derived automatically in Data.Shapely
{-
-- | A wrapper for recursive child occurences of a 'Normal'-ized type
newtype AlsoNormal a = Also { normal :: Normal a }
deriving instance (Show (Normal a))=> Show (AlsoNormal a)
deriving instance (Eq (Normal a))=> Eq (AlsoNormal a)
deriving instance (Ord (Normal a))=> Ord (AlsoNormal a)
deriving instance (Read (Normal a))=> Read (AlsoNormal a)
-}
| jberryman/shapely-data | src/Data/Shapely/Classes.hs | bsd-3-clause | 3,973 | 0 | 13 | 853 | 532 | 319 | 213 | 32 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Database.MetaStorage.Spec (metaStorageSpec) where
import Test.Hspec
import Test.QuickCheck
import Filesystem.Path.CurrentOS
import Crypto.Hash
import Filesystem
import Database.MetaStorage
import Database.MetaStorage.Types
metaStorageSpec :: Spec
metaStorageSpec = do
describe "MetaStorage.mkMetaStorage" $ do
it "creates a new storage in FilePath" $ example $ do
(st, _) <- (mkMetaStorageDefault fp)
st `shouldBe` (MetaStorage fp)
it "throws an exception on invalid filepath" $ example $ do
let ms = (mkMetaStorageDefault invalidPath)
ms `shouldThrow` anyException
context "when given an non existing dir" $ do
it "the new directory will be created" $ example $ do
removeTree fp
(_, ds) <- (mkMetaStorageDefault fp)
isDir <- isDirectory fp
isDir `shouldBe` True
it "returns an empty list " $ example $ do
removeTree fp
(_, ds) <- (mkMetaStorageDefault fp)
ds `shouldBe` []
it "returns a list of the hashes of existing items" $ example $ do
pendingWith "no tests implemented yet"
describe "MetaStorage.ms_basedir" $ do
it "returns the basedir of the MetaStorage" $ do
(st, _) <- (mkMetaStorageDefault fp)
pending --ms_basedir st `shouldBe` fp
describe "MetaStorage.ms_getFilePath" $ do
it "returns an absolute FilePath for a given digest" $
pendingWith "unimplemented test"
where fpbase = "/tmp"
fp = fpbase </> fromText "mstesttmp"
invalidPath = empty
| alios/metastorage | Database/MetaStorage/Spec.hs | bsd-3-clause | 1,588 | 0 | 18 | 390 | 382 | 188 | 194 | 40 | 1 |
module Network.Tangaroa.Byzantine.Server
( runRaftServer
) where
import Data.Binary
import Control.Concurrent.Chan.Unagi
import Control.Lens
import qualified Data.Set as Set
import Network.Tangaroa.Byzantine.Handler
import Network.Tangaroa.Byzantine.Types
import Network.Tangaroa.Byzantine.Util
import Network.Tangaroa.Byzantine.Timer
runRaftServer :: (Binary nt, Binary et, Binary rt, Ord nt) => Config nt -> RaftSpec nt et rt mt -> IO ()
runRaftServer rconf spec = do
let qsize = getQuorumSize $ 1 + (Set.size $ rconf ^. otherNodes)
(ein, eout) <- newChan
runRWS_
raft
(RaftEnv rconf qsize ein eout (liftRaftSpec spec))
initialRaftState
raft :: (Binary nt, Binary et, Binary rt, Ord nt) => Raft nt et rt mt ()
raft = do
fork_ messageReceiver
resetElectionTimer
handleEvents
| chrisnc/tangaroa | src/Network/Tangaroa/Byzantine/Server.hs | bsd-3-clause | 808 | 0 | 14 | 134 | 268 | 145 | 123 | 23 | 1 |
{-# LANGUAGE ApplicativeDo #-}
{-# LANGUAGE EmptyCase #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
module TensorOps.Backend.BTensor
( BTensor
, BTensorL, BTensorV
, HMat
, HMatD
) where
import Control.Applicative
import Control.DeepSeq
import Data.Distributive
import Data.Kind
import Data.List.Util
import Data.Monoid
import Data.Nested hiding (unScalar, unVector, gmul')
import Data.Singletons
import Data.Singletons.Prelude hiding (Reverse, Head, sReverse, (:-))
import Data.Type.Combinator
import Data.Type.Combinator.Util
import Data.Type.Length as TCL
import Data.Type.Length.Util as TCL
import Data.Type.Nat
import Data.Type.Product as TCP
import Data.Type.Product.Util as TCP
import Data.Type.Sing
import Data.Type.Uniform
import Statistics.Distribution
import TensorOps.BLAS
import TensorOps.BLAS.HMat
import TensorOps.NatKind
import TensorOps.Types
import Type.Class.Higher
import Type.Class.Higher.Util
import Type.Class.Witness
import Type.Family.List
import Type.Family.List.Util
import Type.Family.Nat
import qualified Data.Type.Vector as TCV
import qualified Data.Type.Vector.Util as TCV
import qualified Data.Vector.Sized as VS
data BTensor :: (k -> Type -> Type) -> (BShape k -> Type) -> [k] -> Type where
BTS :: { unScalar :: !(ElemB b) } -> BTensor v b '[]
BTV :: { unVector :: !(b ('BV n)) } -> BTensor v b '[n]
BTM :: { unMatrix :: !(b ('BM n m)) } -> BTensor v b '[n,m]
BTN :: { unNested :: !(v n (BTensor v b (o ': m ': ns))) }
-> BTensor v b (n ': o ': m ': ns)
type BTensorL = BTensor (Flip2 TCV.VecT I)
type BTensorV = BTensor (Flip2 VS.VectorT I)
instance (Nesting Proxy Show v, Show1 b, Show (ElemB b)) => Show (BTensor v b s) where
showsPrec p = \case
BTS x -> showParen (p > 10) $ showString "BTS "
. showsPrec 11 x
BTV xs -> showParen (p > 10) $ showString "BTV "
. showsPrec1 11 xs
BTM xs -> showParen (p > 10) $ showString "BTM "
. showsPrec1 11 xs
BTN xs -> showParen (p > 10) $ showString "BTN "
. showsPrec' 11 xs
where
showsPrec' :: forall n s'. Int -> v n (BTensor v b s') -> ShowS
showsPrec' p' xs = showsPrec p' xs
\\ (nesting Proxy :: Show (BTensor v b s')
:- Show (v n (BTensor v b s'))
)
instance (Nesting Proxy Show v, Show1 b, Show (ElemB b)) => Show1 (BTensor v b)
instance (NFData (ElemB b), NFData1 b, Nesting Proxy NFData v) => Nesting1 Proxy NFData (BTensor v b) where
nesting1 _ = Wit
instance (NFData (ElemB b), NFData1 b, Nesting Proxy NFData v) => NFData (BTensor v b js) where
rnf = \case
BTS x -> rnf x
BTV xs -> rnf1 xs
BTM xs -> rnf1 xs
BTN (xs :: v n (BTensor v b (o ': m ': ns))) ->
rnf xs \\ (nesting Proxy :: NFData (BTensor v b (o ': m ': ns))
:- NFData (v n (BTensor v b (o ': m ': ns)))
)
instance (NFData (ElemB b), NFData1 b, Nesting Proxy NFData v) => NFData1 (BTensor v b)
instance ( BLAS b
, Vec v
, Nesting1 Proxy Functor v
, Nesting1 Sing Applicative v
, SingI ns
, Num (ElemB b)
)
=> Num (BTensor v b ns) where
(+) = zipBase sing
(+)
(\_ xs ys -> axpy 1 xs (Just ys))
(\(SBM _ sM) xs ys -> gemm 1 xs (eye sM) (Just (1, ys)))
{-# INLINE (+) #-}
(-) = zipBase sing
(-)
(\_ xs ys -> axpy (-1) ys (Just xs))
(\(SBM _ sM) xs ys -> gemm 1 xs (eye sM) (Just (-1, ys)))
{-# INLINE (-) #-}
(*) = zipBTensorElems sing (*)
{-# INLINE (*) #-}
negate = mapBase sing
negate
(\_ xs -> axpy (-1) xs Nothing)
(\(SBM _ sM) xs -> gemm 1 xs (eye sM) Nothing)
{-# INLINE negate #-}
abs = mapBTensorElems abs
{-# INLINE abs #-}
signum = mapBTensorElems signum
{-# INLINE signum #-}
fromInteger i = genBTensor sing $ \_ -> fromInteger i
{-# INLINE fromInteger #-}
-- | TODO: add RULES pragmas so that this can be done without checking
-- lengths at runtime in the common case that the lengths are known at
-- compile-time.
--
-- Also, totally forgot about matrix-scalar multiplication here, but there
-- isn't really any way of making it work without a lot of empty cases.
-- should probably handle one level up.
dispatchBLAS
:: forall b ms os ns v. (RealFloat (ElemB b), BLAS b)
=> MaxLength N1 ms
-> MaxLength N1 os
-> MaxLength N1 ns
-> BTensor v b (ms ++ os)
-> BTensor v b (Reverse os ++ ns)
-> BTensor v b (ms ++ ns)
dispatchBLAS lM lO lN v r = case (lM, lO, lN) of
(MLZ , MLZ , MLZ ) -> case (v, r) of
-- scalar-scalar
(BTS x, BTS y) -> BTS $ x * y
(MLZ , MLZ , MLS MLZ) -> case (v, r) of
-- scalar-vector
(BTS x, BTV y) -> BTV $ axpy x y Nothing
(MLZ , MLS MLZ, MLZ ) -> case (v, r) of
-- dot
(BTV x, BTV y) -> BTS $ x `dot` y
(MLZ , MLS MLZ, MLS MLZ) -> case (v, r) of
-- vector-matrix
-- TODO: transpose?
(BTV x, BTM y) -> BTV $ gemv 1 (transpB y) x Nothing
(MLS MLZ, MLZ , MLZ ) -> case (v, r) of
-- vector-scalar
(BTV x, BTS y) -> BTV $ axpy y x Nothing
(MLS MLZ, MLZ , MLS MLZ) -> case (v, r) of
-- vector-scalar
(BTV x, BTV y) -> BTM $ ger x y
(MLS MLZ, MLS MLZ, MLZ ) -> case (v, r) of
-- matrx-vector
(BTM x, BTV y) -> BTV $ gemv 1 x y Nothing
(MLS MLZ, MLS MLZ, MLS MLZ) -> case (v, r) of
-- matrix-matrix
(BTM x, BTM y) -> BTM $ gemm 1 x y Nothing
{-# INLINE dispatchBLAS #-}
mapRowsBTensor
:: forall k (v :: k -> Type -> Type) ns ms os b. (Vec v, BLAS b)
=> Sing ns
-> Length os
-> (BTensor v b ms -> BTensor v b os)
-> BTensor v b (ns ++ ms)
-> BTensor v b (ns ++ os)
mapRowsBTensor sN lO f = getI . bRows sN lO (I . f)
{-# INLINE mapRowsBTensor #-}
bRows
:: forall k (v :: k -> Type -> Type) ns ms os b f. (Applicative f, Vec v, BLAS b)
=> Sing ns
-> Length os
-> (BTensor v b ms -> f (BTensor v b os))
-> BTensor v b (ns ++ ms)
-> f (BTensor v b (ns ++ os))
bRows sN lO f = bIxRows sN lO (\_ -> f)
{-# INLINE bRows #-}
mapIxRows
:: forall k (v :: k -> Type -> Type) ns ms os b. (Vec v, BLAS b)
=> Sing ns
-> Length os
-> (Prod (IndexN k) ns -> BTensor v b ms -> BTensor v b os)
-> BTensor v b (ns ++ ms)
-> BTensor v b (ns ++ os)
mapIxRows sN lO f = getI . bIxRows sN lO (\i -> I . f i)
{-# INLINE mapIxRows #-}
foldMapIxRows
:: forall k (v :: k -> Type -> Type) ns ms m b. (Vec v, Monoid m, BLAS b)
=> Sing ns
-> (Prod (IndexN k) ns -> BTensor v b ms -> m)
-> BTensor v b (ns ++ ms)
-> m
foldMapIxRows s f = getConst . bIxRows s LZ (\i -> Const . f i)
{-# INLINE foldMapIxRows #-}
bIxRows
:: forall k (v :: k -> Type -> Type) ns ms os b f. (Applicative f, Vec v, BLAS b)
=> Sing ns
-> Length os
-> (Prod (IndexN k) ns -> BTensor v b ms -> f (BTensor v b os))
-> BTensor v b (ns ++ ms)
-> f (BTensor v b (ns ++ os))
bIxRows = \case
SNil -> \_ f -> f Ø
s `SCons` ss -> \lO f -> \case
BTV xs -> case ss of
-- ns ~ '[n]
-- ms ~ '[]
SNil -> case lO of
-- ns ++ os ~ '[n]
LZ -> BTV <$> iElemsB (\i -> fmap unScalar . f (pbvProd i) . BTS) xs
-- ns ++ os ~ '[n,m]
LS LZ -> BTM <$> bgenRowsA (\i -> unVector <$> f (i :< Ø) (BTS $ indexB (PBV i) xs))
\\ s
LS (LS _) -> BTN <$> vGenA s (\i -> f (i :< Ø) (BTS $ indexB (PBV i) xs))
BTM xs -> case ss of
-- ns ~ '[n]
-- ms ~ '[m]
SNil -> case lO of
-- ns ++ os ~ '[n]
LZ -> BTV <$> bgenA (SBV s) (\(PBV i) -> unScalar <$> f (i :< Ø) (BTV (indexRowB i xs)))
-- ns ++ os ~ '[n,o]
LS LZ -> BTM <$> iRowsB (\i -> fmap unVector . f (i :< Ø) . BTV) xs
LS (LS _) -> BTN <$> vGenA s (\i -> f (i :< Ø) (BTV (indexRowB i xs)))
-- ns ~ '[n,m]
-- ms ~ '[]
s' `SCons` ss' -> (\\ s') $ case ss' of
SNil -> case lO of
LZ -> BTM <$> iElemsB (\i -> fmap unScalar . f (pbmProd i) . BTS) xs
LS _ -> BTN <$>
vGenA s (\i ->
btn lO <$>
vGenA s' (\j ->
f (i :< j :< Ø) (BTS (indexB (PBM i j) xs))
)
)
BTN xs -> (\\ s) $
fmap (btn (singLength ss `TCL.append'` lO))
. vITraverse (\i -> bIxRows ss lO (\is -> f (i :< is)))
$ xs
indexRowBTensor
:: forall k (b :: BShape k -> Type) v ns ms.
( BLAS b
, Vec v
)
=> Prod (IndexN k) ns
-> BTensor v b (ns ++ ms)
-> BTensor v b ms
indexRowBTensor = \case
Ø -> id
i :< is -> \case
BTV xs -> case is of
Ø -> BTS $ indexB (PBV i) xs
BTM xs -> case is of
Ø -> BTV $ indexRowB i xs
j :< Ø -> BTS $ indexB (PBM i j) xs
BTN xs -> indexRowBTensor is (vIndex i xs)
{-# INLINE indexRowBTensor #-}
mapBTensorElems
:: (Vec v, BLAS b)
=> (ElemB b -> ElemB b)
-> BTensor v b ns
-> BTensor v b ns
mapBTensorElems f = getI . bTensorElems (I . f)
{-# INLINE mapBTensorElems #-}
bTensorElems
:: forall k (v :: k -> Type -> Type) ns b f. (Applicative f, Vec v, BLAS b)
=> (ElemB b -> f (ElemB b))
-> BTensor v b ns
-> f (BTensor v b ns)
bTensorElems f = \case
BTS x -> BTS <$> f x
BTV xs -> BTV <$> elemsB f xs
BTM xs -> BTM <$> elemsB f xs
BTN xs -> BTN <$> vITraverse (\_ x -> bTensorElems f x) xs
{-# INLINE bTensorElems #-}
ifoldMapBTensor
:: forall k (v :: k -> Type -> Type) ns m b. (Monoid m, Vec v, BLAS b)
=> (Prod (IndexN k) ns -> ElemB b -> m)
-> BTensor v b ns
-> m
ifoldMapBTensor f = getConst . bTensorIxElems (\i -> Const . f i)
{-# INLINE ifoldMapBTensor #-}
bTensorIxElems
:: forall k (v :: k -> Type -> Type) ns b f. (Applicative f, Vec v, BLAS b)
=> (Prod (IndexN k) ns -> ElemB b -> f (ElemB b))
-> BTensor v b ns
-> f (BTensor v b ns)
bTensorIxElems f = \case
BTS x -> BTS <$> f Ø x
BTV xs -> BTV <$> iElemsB (f . pbvProd) xs
BTM xs -> BTM <$> iElemsB (f . pbmProd) xs
BTN xs -> BTN <$> vITraverse (\i -> bTensorIxElems (\is -> f (i :< is))) xs
{-# INLINE bTensorIxElems #-}
zipBTensorElems
:: forall v b ns. (BLAS b, Nesting1 Sing Applicative v)
=> Sing ns
-> (ElemB b -> ElemB b -> ElemB b)
-> BTensor v b ns
-> BTensor v b ns
-> BTensor v b ns
zipBTensorElems = \case
SNil -> \f -> \case
BTS x -> \case
BTS y -> BTS (f x y)
sN `SCons` SNil -> \f -> \case
BTV xs -> \case
BTV ys -> BTV (zipB (SBV sN) f xs ys)
sN `SCons` (sM `SCons` SNil) -> \f -> \case
BTM xs -> \case
BTM ys -> BTM (zipB (SBM sN sM) f xs ys)
(s :: Sing k) `SCons` ss@(_ `SCons` (_ `SCons` _)) -> \f -> \case
BTN xs -> \case
BTN ys -> BTN (zipBTensorElems ss f <$> xs <*> ys)
\\ (nesting1 s :: Wit (Applicative (v k)))
{-# INLINE zipBTensorElems #-}
liftBTensor
:: forall v b ns n.
( BLAS b
, Nesting1 Proxy Functor v
, Nesting1 Sing Distributive v
)
=> Sing ns
-> (TCV.Vec n (ElemB b) -> ElemB b)
-> TCV.Vec n (BTensor v b ns)
-> BTensor v b ns
liftBTensor = \case
SNil -> \f xs ->
let xs' = unScalar <$> xs
in BTS $ f xs'
sN `SCons` SNil -> \f xs ->
let xs' = unVector <$> xs
in BTV $ liftB (SBV sN) f xs'
sN `SCons` (sM `SCons` SNil) -> \f xs ->
let xs' = unMatrix <$> xs
in BTM $ liftB (SBM sN sM) f xs'
(s :: Sing k) `SCons` ss@(_ `SCons` (_ `SCons` _)) -> \f xs ->
let xs' = unNested <$> xs
in BTN $ TCV.liftVecD (liftBTensor ss f) xs'
\\ (nesting1 s :: Wit (Distributive (v k)))
{-# INLINE liftBTensor #-}
mapBTM
:: forall k (v :: k -> Type -> Type) ns n m ms b. (Vec v, BLAS b)
=> Sing ns
-> Length ms
-> (b ('BM n m) -> BTensor v b ms)
-> BTensor v b (ns ++ [n,m])
-> BTensor v b (ns ++ ms)
mapBTM sN lM f = getI . traverseBTM sN lM (I . f)
{-# INLINE mapBTM #-}
foldMapBTM
:: (Monoid a, Vec v, BLAS b)
=> Length ns
-> (b ('BM n m) -> a)
-> BTensor v b (ns ++ [n,m])
-> a
foldMapBTM l f = ifoldMapBTM l (\_ -> f)
{-# INLINE foldMapBTM #-}
traverseBTM
:: forall k (v :: k -> Type -> Type) ns n m ms b f. (Applicative f, Vec v, BLAS b)
=> Sing ns
-> Length ms
-> (b ('BM n m) -> f (BTensor v b ms))
-> BTensor v b (ns ++ [n,m])
-> f (BTensor v b (ns ++ ms))
traverseBTM = \case
SNil -> \_ f -> \case
BTM x -> f x
s `SCons` ss -> \lM f -> \case
BTV _ -> case ss of
BTM _ -> case ss of
BTN xs -> (\\ s) $
fmap (btn (singLength ss `TCL.append'` lM))
. vITraverse (\_ -> traverseBTM ss lM f)
$ xs
{-# INLINE traverseBTM #-}
imapBTM
:: forall k (v :: k -> Type -> Type) ns n m ms b. (Vec v, BLAS b)
=> Sing ns
-> Length ms
-> (Prod (IndexN k) ns -> b ('BM n m) -> BTensor v b ms)
-> BTensor v b (ns ++ [n,m])
-> BTensor v b (ns ++ ms)
imapBTM sN lM f = getI . itraverseBTM sN lM (\i -> I . f i)
{-# INLINE imapBTM #-}
ifoldMapBTM
:: (Vec v, Monoid a, BLAS b)
=> Length ns
-> (Prod (IndexN k) ns -> b ('BM n m) -> a)
-> BTensor v b (ns ++ [n,m])
-> a
ifoldMapBTM = \case
LZ -> \f -> \case
BTM xs -> f Ø xs
LS l -> \f -> \case
BTV _ -> case l of
BTM _ -> case l of
BTN xs -> vIFoldMap (\i -> ifoldMapBTM l (\is -> f (i :< is))) xs
{-# INLINE ifoldMapBTM #-}
itraverseBTM
:: forall k (v :: k -> Type -> Type) ns n m ms b f. (Applicative f, Vec v, BLAS b)
=> Sing ns
-> Length ms
-> (Prod (IndexN k) ns -> b ('BM n m) -> f (BTensor v b ms))
-> BTensor v b (ns ++ [n,m])
-> f (BTensor v b (ns ++ ms))
itraverseBTM = \case
SNil -> \_ f -> \case
BTM x -> f Ø x
s `SCons` ss -> \lM f -> \case
BTV _ -> case ss of
BTM _ -> case ss of
BTN xs -> (\\ s) $
fmap (btn (singLength ss `TCL.append'` lM))
. vITraverse (\i -> itraverseBTM ss lM (\is ys -> f (i :< is) ys))
$ xs
{-# INLINE itraverseBTM #-}
mapBase
:: forall v b ns. (Nesting1 Proxy Functor v)
=> Sing ns
-> (ElemB b -> ElemB b)
-> (forall n. Sing n -> b ('BV n) -> b ('BV n))
-> (forall n m. Sing ('BM n m) -> b ('BM n m) -> b ('BM n m))
-> BTensor v b ns
-> BTensor v b ns
mapBase = \case
SNil -> \f _ _ -> \case
BTS x -> BTS (f x)
sN `SCons` SNil -> \_ g _ -> \case
BTV xs -> BTV (g sN xs)
sN `SCons` (sM `SCons` SNil) -> \_ _ h -> \case
BTM xs -> BTM (h (SBM sN sM) xs)
(_ :: Sing k) `SCons` ss@(_ `SCons` (_ `SCons` _)) -> \f g h -> \case
BTN xs -> BTN (mapBase ss f g h <$> xs)
\\ (nesting1 Proxy :: Wit (Functor (v k)))
{-# INLINE mapBase #-}
zipBase
:: forall v b ns. (Nesting1 Sing Applicative v)
=> Sing ns
-> (ElemB b -> ElemB b -> ElemB b)
-> (forall n. Sing n -> b ('BV n) -> b ('BV n) -> b ('BV n))
-> (forall n m. Sing ('BM n m) -> b ('BM n m) -> b ('BM n m) -> b ('BM n m))
-> BTensor v b ns
-> BTensor v b ns
-> BTensor v b ns
zipBase = \case
SNil -> \f _ _ -> \case
BTS x -> \case
BTS y -> BTS (f x y)
sN `SCons` SNil -> \_ g _ -> \case
BTV xs -> \case
BTV ys -> BTV (g sN xs ys)
sN `SCons` (sM `SCons` SNil) -> \_ _ h -> \case
BTM xs -> \case
BTM ys -> BTM (h (SBM sN sM) xs ys)
(s :: Sing k) `SCons` ss@(_ `SCons` (_ `SCons` _)) -> \f g h -> \case
BTN xs -> \case
BTN ys -> BTN $ zipBase ss f g h <$> xs <*> ys
\\ (nesting1 s :: Wit (Applicative (v k)))
{-# INLINE zipBase #-}
genBTensorA
:: forall k (b :: BShape k -> Type) v (ns :: [k]) f. (Applicative f, BLAS b, Vec v)
=> Sing ns
-> (Prod (IndexN k) ns -> f (ElemB b))
-> f (BTensor v b ns)
genBTensorA = \case
SNil -> \f ->
BTS <$> f Ø
sN `SCons` SNil -> \f ->
BTV <$> bgenA (SBV sN) (f . pbvProd)
sN `SCons` (sM `SCons` SNil) -> \f ->
BTM <$> bgenA (SBM sN sM) (f . pbmProd)
s `SCons` ss@(_ `SCons` (_ `SCons` _)) -> \f ->
BTN <$> vGenA s (\i -> genBTensorA ss (\is -> f (i :< is)))
{-# INLINE genBTensorA #-}
genBTensor
:: forall k (b :: BShape k -> Type) v (ns :: [k]). (BLAS b, Vec v)
=> Sing ns
-> (Prod (IndexN k) ns -> ElemB b)
-> BTensor v b ns
genBTensor s f = getI $ genBTensorA s (I . f)
{-# INLINE genBTensor #-}
indexBTensor
:: forall k (b :: BShape k -> Type) v ns. (BLAS b, Vec v)
=> Prod (IndexN k) ns
-> BTensor v b ns
-> ElemB b
indexBTensor = \case
Ø -> \case
BTS x -> x
i :< Ø -> \case
BTV xs -> indexB (PBV i) xs
i :< j :< Ø -> \case
BTM xs -> indexB (PBM i j) xs
i :< js@(_ :< _ :< _) -> \case
BTN xs -> indexBTensor js (vIndex i xs)
{-# INLINE indexBTensor #-}
btn :: (BLAS b, Vec v, SingI n)
=> Length ns
-> v n (BTensor v b ns)
-> BTensor v b (n ': ns)
btn = \case
LZ -> \xs ->
BTV $ bgen sing (unScalar . (`vIndex` xs) . unPBV)
LS LZ -> \xs ->
BTM $ bgenRows (unVector . (`vIndex` xs))
LS (LS _) -> BTN
{-# INLINE btn #-}
gmul'
:: forall v b ms os ns.
( SingI (ms ++ ns)
, RealFloat (ElemB b)
, Vec v
, Nesting1 Proxy Functor v
, Nesting1 Sing Applicative v
, BLAS b
)
=> Length ms
-> Length os
-> Length ns
-> BTensor v b (ms ++ os)
-> BTensor v b (Reverse os ++ ns)
-> BTensor v b (ms ++ ns)
gmul' lM lO lN = gmulB sM lO lN \\ sN
where
sM :: Sing ms
sN :: Sing ns
(sM, sN) = splitSing lM sing
{-# INLINE[0] gmul' #-}
{-# RULES
"gmul'/SS" gmul' = dispatchSS
"gmul'/SV" gmul' = dispatchSV
"gmul'/dot" gmul' = dispatchDot
"gmul'/VM" gmul' = dispatchVM
"gmul'/VS" gmul' = dispatchVS
"gmul'/out" gmul' = dispatchOut
"gmul'/MV" gmul' = dispatchMV
"gmul'/MM" gmul' = dispatchMM
#-}
-- | General strategy:
--
-- * We can only outsource to BLAS (using 'dispatchBLAS') in the case
-- that @os@ and @ns@ have length 0 or 1. Anything else, fall back to
-- the basic reverse-indexing method in "Data.Nested".
-- * If @ms@ is length 2 or higher, "traverse down" to the length 0 or
-- 1 tail...and then sum them up.
gmulB
:: forall k (b :: BShape k -> Type) v ms os ns.
( RealFloat (ElemB b)
, SingI ns
, BLAS b
, Vec v
, Nesting1 Proxy Functor v
, Nesting1 Sing Applicative v
)
=> Sing ms
-> Length os
-> Length ns
-> BTensor v b (ms ++ os)
-> BTensor v b (Reverse os ++ ns)
-> BTensor v b (ms ++ ns)
gmulB sM lO lN v r = case splitting (S_ Z_) (lengthProd lN) of
Fewer mlN _ -> case splittingEnd (S_ (S_ Z_)) (lengthProd lO) of
FewerEnd MLZ _ -> gmulBLAS sM MLZ mlN v r
FewerEnd (MLS MLZ) _ -> gmulBLAS sM (MLS MLZ) mlN v r
FewerEnd (MLS (MLS MLZ)) _ -> case mlN of
MLZ -> case r of
BTM ys -> mapBTM sM LZ (\xs -> BTS $ traceB (gemm 1 xs ys Nothing)) v
MLS MLZ -> naiveGMul sM lO lN v r
SplitEnd _ _ _ -> naiveGMul sM lO lN v r
Split _ _ _ -> naiveGMul sM lO lN v r
{-# INLINE[0] gmulB #-}
-- | Naive implementation of 'gmul' (based on the implementation for
-- 'NTensor') that does not utilize any BLAS capabilities.
naiveGMul
:: forall k (b :: BShape k -> Type) v ms os ns.
( BLAS b
, Vec v
, Num (ElemB b)
, Nesting1 Proxy Functor v
, Nesting1 Sing Applicative v
, SingI ns
)
=> Sing ms
-> Length os
-> Length ns
-> BTensor v b (ms ++ os)
-> BTensor v b (Reverse os ++ ns)
-> BTensor v b (ms ++ ns)
naiveGMul sM _ lN v r =
mapRowsBTensor sM lN (getSum . ifoldMapBTensor (\i -> Sum . f i)) v
where
f :: Prod (IndexN k) os
-> ElemB b
-> BTensor v b ns
f is x = mapBase sing
(x *)
(\_ ys -> scaleB x ys)
(\_ ys -> scaleB x ys)
(indexRowBTensor (TCP.reverse' is) r)
-- | A 'gmul' that runs my dispatching BLAS commands when it can.
-- Contains the type-level constraint that @os@ and @ns@ have to have
-- either length 0 or 1.
--
-- TODO: no longer needs Sing ms
gmulBLAS
:: forall b ms os ns v.
( RealFloat (ElemB b)
, BLAS b
, Vec v
, SingI ns
, Nesting1 Proxy Functor v
, Nesting1 Sing Applicative v
)
=> Sing ms
-> MaxLength N1 os
-> MaxLength N1 ns
-> BTensor v b (ms ++ os)
-> BTensor v b (Reverse os ++ ns)
-> BTensor v b (ms ++ ns)
gmulBLAS sM mlO mlN v r = case mlO of
MLZ -> case splittingEnd (S_ (S_ Z_)) spM of
FewerEnd MLZ _ -> dispatchBLAS MLZ mlO mlN v r
FewerEnd (MLS MLZ) _ -> dispatchBLAS (MLS MLZ) mlO mlN v r
FewerEnd (MLS (MLS MLZ)) _ -> case v of
BTM xs -> case mlN of
MLZ -> case r of
BTS y -> BTM $ scaleB y xs
-- TODO: can this be made non-naive?
-- ms ~ '[m1,m2]
-- os ~ '[]
-- ns ~ '[n]
MLS MLZ -> naiveGMul sM LZ (fromMaxLength mlN) v r
SplitEnd (ELS (ELS ELZ)) spM0 spM1 -> case mlN of
MLZ -> case r of
BTS y -> mapBTM (prodSing spM0)
(prodLength spM1)
(\xs -> BTM $ scaleB y xs)
v
\\ appendNil lM
-- TODO: can this be made non-naive?
-- ms ~ (ms0 ++ '[m1,m2])
-- os ~ '[]
-- ns ~ '[n]
MLS MLZ -> naiveGMul sM LZ (fromMaxLength mlN) v r
MLS MLZ -> case splittingEnd (S_ Z_) spM of
FewerEnd mlM _ -> dispatchBLAS mlM mlO mlN v r
SplitEnd (ELS ELZ) spM0 spM1 ->
let sM0 = prodSing spM0
lM0 = prodLength spM0
lM1 = prodLength spM1
in (\\ appendAssoc (TCL.tail' lM0)
lM1
(LS LZ :: Length os)
) $ case mlN of
MLZ -> case r of
BTV ys -> mapBTM sM0 lM1 (\xs -> BTV $ gemv 1 xs ys Nothing) v
\\ appendNil lM
MLS MLZ -> case r of
BTM ys -> mapBTM sM0
(lM1 `TCL.append'` (LS LZ :: Length ns))
(\xs -> BTM $ gemm 1 xs ys Nothing)
v
\\ appendAssoc (TCL.tail' lM0)
lM1
(LS LZ :: Length ns)
where
spM = singProd sM
lM = singLength sM
diagBTensor
:: forall k (b :: BShape k -> Type) v n ns.
( SingI (n ': ns)
, BLAS b
, Vec v
, Num (ElemB b)
, Eq (IndexN k n)
)
=> Uniform n ns
-> BTensor v b '[n]
-> BTensor v b (n ': ns)
diagBTensor = \case
UØ -> id
US UØ -> \case
BTV xs -> BTM $ diagB xs
u@(US (US _)) -> \(BTV xs) ->
genBTensor sing (\i -> case TCV.uniformVec (prodToVec I (US u) i) of
Nothing -> 0
Just (I i') -> indexB (PBV i') xs
)
{-# INLINE diagBTensor #-}
transpBTensor
:: (BLAS b, Vec v)
=> Sing ns
-> BTensor v b ns
-> BTensor v b (Reverse ns)
transpBTensor s = \case
BTS x -> BTS x
BTV xs -> BTV xs
BTM xs -> BTM $ transpB xs
xs@(BTN _) -> (\\ reverseReverse (singLength s)) $
genBTensor (sReverse s) $ \i ->
indexBTensor (TCP.reverse' i) xs
{-# INLINE transpBTensor #-}
sumBTensor
:: forall v b n ns.
( BLAS b
, Vec v
, Num (ElemB b)
, Foldable (v n)
, SingI ns
, SingI n
, Nesting1 Proxy Functor v
, Nesting1 Sing Applicative v
)
=> BTensor v b (n ': ns)
-> BTensor v b ns
sumBTensor = \case
BTV xs -> BTS $ sumB xs
BTM (xs :: b ('BM n m))
-> BTV $ gemv 1 (transpB xs)
(bgen (SBV (sing :: Sing n)) (\_ -> 1))
Nothing
BTN xs -> sum xs
instance
( Vec (v :: k -> Type -> Type)
, BLAS b
, RealFloat (ElemB b)
, Nesting1 Proxy Functor v
, Nesting1 Proxy Foldable v
, Nesting1 Sing Applicative v
, Nesting1 Sing Distributive v
, Eq1 (IndexN k)
)
=> Tensor (BTensor v b) where
type ElemT (BTensor v b) = ElemB b
liftT
:: SingI ns
=> (TCV.Vec n (ElemB b) -> ElemB b)
-> TCV.Vec n (BTensor v b ns)
-> BTensor v b ns
liftT = liftBTensor sing
{-# INLINE liftT #-}
sumT = sum'
{-# INLINE sumT #-}
scaleT α = mapBase sing (α*) (\_ -> scaleB α) (\_ -> scaleB α)
{-# INLINE scaleT #-}
gmul
:: forall ms os ns. SingI (ms ++ ns)
=> Length ms
-> Length os
-> Length ns
-> BTensor v b (ms ++ os)
-> BTensor v b (Reverse os ++ ns)
-> BTensor v b (ms ++ ns)
gmul = gmul'
{-# INLINE gmul #-}
diag
:: forall n ns. SingI (n ': ns)
=> Uniform n ns
-> BTensor v b '[n]
-> BTensor v b (n ': ns)
diag = diagBTensor
\\ (produceEq1 :: Eq1 (IndexN k) :- Eq (IndexN k n))
{-# INLINE diag #-}
getDiag
:: SingI n
=> Uniform n ns
-> BTensor v b (n ': n ': ns)
-> BTensor v b '[n]
getDiag = \case
UØ -> \case
BTM xs -> BTV $ getDiagB xs
u@(US _) -> \xs ->
genBTensor sing $ \(i :< Ø) ->
indexBTensor (TCP.replicate i (US (US u))) xs
{-# INLINE getDiag #-}
transp = transpBTensor sing
{-# INLINE transp #-}
generateA = genBTensorA sing
{-# INLINE generateA #-}
genRand d g = generateA (\_ -> realToFrac <$> genContVar d g)
{-# INLINE genRand #-}
ixRows
:: forall f ms os ns. (Applicative f, SingI (ms ++ os))
=> Length ms
-> Length os
-> (Prod (IndexN k) ms -> BTensor v b ns -> f (BTensor v b os))
-> BTensor v b (ms ++ ns)
-> f (BTensor v b (ms ++ os))
ixRows lM lO = bIxRows sM lO
where
sM :: Sing ms
sM = takeSing lM lO (sing :: Sing (ms ++ os))
{-# INLINE ixRows #-}
(!) = flip indexBTensor
{-# INLINE (!) #-}
sumRows
:: forall n ns. (SingI (n ': ns), SingI ns)
=> BTensor v b (n ': ns)
-> BTensor v b ns
sumRows = sumBTensor
\\ (nesting1 Proxy :: Wit (Foldable (v n)))
\\ sHead (sing :: Sing (n ': ns))
{-# INLINE sumRows #-}
mapRows :: forall ns ms. SingI (ns ++ ms)
=> Length ns
-> (BTensor v b ms -> BTensor v b ms)
-> BTensor v b (ns ++ ms)
-> BTensor v b (ns ++ ms)
mapRows l f = mapRowsBTensor sN (singLength sM) f
where
sN :: Sing ns
sM :: Sing ms
(sN, sM) = splitSing l (sing :: Sing (ns ++ ms))
{-# INLINE mapRows #-}
-- * Boring dispatches
dispatchSS
:: Num (ElemB b)
=> Length '[]
-> Length '[]
-> Length '[]
-> BTensor v b '[]
-> BTensor v b '[]
-> BTensor v b '[]
dispatchSS _ _ _ (BTS x) (BTS y) = BTS (x * y)
{-# INLINE dispatchSS #-}
dispatchSV
:: BLAS b
=> Length '[]
-> Length '[]
-> Length '[n]
-> BTensor v b '[]
-> BTensor v b '[n]
-> BTensor v b '[n]
dispatchSV _ _ _ (BTS x) (BTV y) = BTV $ axpy x y Nothing
{-# INLINE dispatchSV #-}
dispatchDot
:: BLAS b
=> Length '[]
-> Length '[n]
-> Length '[]
-> BTensor v b '[n]
-> BTensor v b '[n]
-> BTensor v b '[]
dispatchDot _ _ _ (BTV x) (BTV y) = BTS $ x `dot` y
{-# INLINE dispatchDot #-}
dispatchVM
:: (Num (ElemB b), BLAS b)
=> Length '[]
-> Length '[n]
-> Length '[m]
-> BTensor v b '[n]
-> BTensor v b '[n,m]
-> BTensor v b '[m]
dispatchVM _ _ _ (BTV x) (BTM y) = BTV $ gemv 1 (transpB y) x Nothing
{-# INLINE dispatchVM #-}
dispatchVS
:: BLAS b
=> Length '[n]
-> Length '[]
-> Length '[]
-> BTensor v b '[n]
-> BTensor v b '[]
-> BTensor v b '[n]
dispatchVS _ _ _ (BTV x) (BTS y) = BTV $ axpy y x Nothing
{-# INLINE dispatchVS #-}
dispatchOut
:: BLAS b
=> Length '[n]
-> Length '[]
-> Length '[m]
-> BTensor v b '[n]
-> BTensor v b '[m]
-> BTensor v b '[n,m]
dispatchOut _ _ _ (BTV x) (BTV y) = BTM $ ger x y
{-# INLINE dispatchOut #-}
dispatchMV
:: (Num (ElemB b), BLAS b)
=> Length '[n]
-> Length '[m]
-> Length '[]
-> BTensor v b '[n,m]
-> BTensor v b '[m]
-> BTensor v b '[n]
dispatchMV _ _ _ (BTM x) (BTV y) = BTV $ gemv 1 x y Nothing
{-# INLINE dispatchMV #-}
dispatchMM
:: (Num (ElemB b), BLAS b)
=> Length '[m]
-> Length '[o]
-> Length '[n]
-> BTensor v b '[m,o]
-> BTensor v b '[o,n]
-> BTensor v b '[m,n]
dispatchMM _ _ _ (BTM x) (BTM y) = BTM $ gemm 1 x y Nothing
{-# INLINE dispatchMM #-}
| mstksg/tensor-ops | src/TensorOps/Backend/BTensor.hs | bsd-3-clause | 30,700 | 0 | 36 | 11,375 | 13,033 | 6,750 | 6,283 | -1 | -1 |
-- | this module contains the defs of common data types and type classes
module Text.Regex.Deriv.Common
( Range(..), range, minRange, maxRange
, Letter
, PosEpsilon (..)
, IsEpsilon (..)
, IsPhi (..)
, Simplifiable (..)
, myHash
, myLookup
, GFlag (..)
, IsGreedy (..)
, nub2
, nub3
, preBinder
, preBinder_
, subBinder
, mainBinder
) where
import Data.Char (ord)
import qualified Data.IntMap as IM
-- | (sub)words represent by range
-- type Range = (Int,Int)
data Range = Range !Int !Int deriving (Show, Ord)
instance Eq Range where
(==) (Range x y) (Range w z) = (x == w) && (y == z)
range :: Int -> Int -> Range
range = Range
minRange :: (Int, Int) -> Int
minRange = fst
maxRange :: (Int, Int) -> Int
maxRange = snd
-- | a character and its index (position)
type Letter = (Char,Int)
-- | test for 'epsilon \in a' epsilon-possession
class PosEpsilon a where
posEpsilon :: a -> Bool
-- | test for epsilon == a
class IsEpsilon a where
isEpsilon :: a -> Bool
-- | test for \phi == a
class IsPhi a where
isPhi :: a -> Bool
class Simplifiable a where
simplify :: a -> a
myHash :: Int -> Char -> Int
myHash i x = ord x + 256 * i
-- the lookup function
myLookup :: Int -> Char -> IM.IntMap [Int] -> [Int]
myLookup i x dict = case IM.lookup (myHash i x) dict of
Just ys -> ys
Nothing -> []
-- | The greediness flag
data GFlag = Greedy -- ^ greedy
| NotGreedy -- ^ not greedy
deriving (Eq,Ord)
instance Show GFlag where
show Greedy = ""
show NotGreedy = "?"
class IsGreedy a where
isGreedy :: a -> Bool
-- remove duplications in a list of pairs, using the first components as key.
nub2 :: [(Int,a)] -> [(Int,a)]
nub2 [] = []
nub2 [x] = [x]
nub2 ls = nub2sub IM.empty ls
nub2sub :: IM.IntMap () -> [(IM.Key, t)] -> [(IM.Key, t)]
nub2sub _ [] = []
nub2sub im (x@(k,_):xs) =
case IM.lookup k im of
Just _ -> xs `seq` nub2sub im xs
Nothing -> let im' = IM.insert k () im
in im' `seq` xs `seq` x:nub2sub im' xs
nub3 :: [(Int,a,Int)] -> [(Int,a,Int)]
nub3 [] = []
nub3 [x] = [x]
nub3 ls = nub3subsimple IM.empty ls
nub3subsimple :: IM.IntMap () -> [(Int,a,Int)] -> [(Int,a,Int)]
nub3subsimple _ [] = []
nub3subsimple _ [ x ] = [ x ]
nub3subsimple im (x@(_,_,0):xs) = x:(nub3subsimple im xs)
nub3subsimple im (x@(k,_,1):xs) = let im' = IM.insert k () im
in im' `seq` x:(nub3subsimple im' xs)
nub3subsimple im (x@(k,_,_):xs) = case IM.lookup k im of
Just _ -> nub3subsimple im xs
Nothing -> let im' = IM.insert k () im
in im' `seq` xs `seq` x:(nub3subsimple im' xs)
-- The smallest binder index capturing the prefix of the unanchored regex
preBinder :: Int
preBinder = -1
preBinder_ :: Int
preBinder_ = -2
-- The largest binder index capturing for the suffix of the unanchored regex
subBinder :: Int
subBinder = 2147483647
-- The binder index capturing substring which matches by the unanchored regex
mainBinder :: Int
mainBinder = 0
| awalterschulze/xhaskell-regex-deriv | Text/Regex/Deriv/Common.hs | bsd-3-clause | 3,221 | 0 | 13 | 937 | 1,159 | 649 | 510 | 88 | 2 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module State6502 where
import Data.Word
import Deque
import Data.Array
import Data.Time.Clock
import Control.Lens
import Control.Monad.State
import Data.Bits.Lens
import System.Console.Haskeline
import Data.Array.IO
import qualified Data.IntMap as M
import System.IO
import Data.ByteString as B
import FileSystems
data Registers = R {
_pc :: !Word16,
_p :: !Word8,
_a :: !Word8,
_x :: !Word8,
_y :: !Word8,
_s :: !Word8
}
makeLenses ''Registers
{-# INLINE flagC #-}
flagC :: Lens' Registers Bool
flagC = p . bitAt 0
{-# INLINE flagZ #-}
flagZ :: Lens' Registers Bool
flagZ = p . bitAt 1
{-# INLINE flagI #-}
flagI :: Lens' Registers Bool
flagI = p . bitAt 2
{-# INLINE flagD #-}
flagD :: Lens' Registers Bool
flagD = p . bitAt 3
{-# INLINE flagB #-}
flagB :: Lens' Registers Bool
flagB = p . bitAt 4
{-# INLINE flagV #-}
flagV :: Lens' Registers Bool
flagV = p . bitAt 6
{-# INLINE flagN #-}
flagN :: Lens' Registers Bool
flagN = p . bitAt 7
data KeyInput = KeyInput {
buffer :: Deque Word8,
keydefs :: Array Int [Word8]
}
data VDUOutput = VDUOutput {
vbuffer :: [Word8],
requiredChars :: Int
}
data State6502 = S {
_mem :: IOUArray Int Word8,
_clock :: !Int,
_regs :: !Registers,
_debug :: !Bool,
_currentDirectory :: Char,
_sysclock :: !UTCTime,
_handles :: M.IntMap VHandle,
_keyQueue :: KeyInput,
_vduQueue :: VDUOutput,
_logFile :: Maybe Handle
}
makeLenses ''State6502
| dpiponi/Bine | src/State6502.hs | bsd-3-clause | 1,646 | 0 | 10 | 436 | 447 | 254 | 193 | 83 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# OPTIONS_GHC -fno-warn-missing-fields #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-----------------------------------------------------------------
-- Autogenerated by Thrift Compiler (0.7.0-dev) --
-- --
-- DO NOT EDIT UNLESS YOU ARE SURE YOU KNOW WHAT YOU ARE DOING --
-----------------------------------------------------------------
module Thrift.ContentProvider_Client(downloadMesh) where
import Data.IORef
import Prelude ( Bool(..), Enum, Double, String, Maybe(..),
Eq, Show, Ord,
return, length, IO, fromIntegral, fromEnum, toEnum,
(&&), (||), (==), (++), ($), (-) )
import Control.Exception
import Data.ByteString.Lazy
import Data.Int
import Data.Typeable ( Typeable )
import qualified Data.Map as Map
import qualified Data.Set as Set
import Thrift
import Thrift.Content_Types
import Thrift.ContentProvider
seqid = newIORef 0
downloadMesh (ip,op) arg_name = do
send_downloadMesh op arg_name
recv_downloadMesh ip
send_downloadMesh op arg_name = do
seq <- seqid
seqn <- readIORef seq
writeMessageBegin op ("downloadMesh", M_CALL, seqn)
write_DownloadMesh_args op (DownloadMesh_args{f_DownloadMesh_args_name=Just arg_name})
writeMessageEnd op
tFlush (getTransport op)
recv_downloadMesh ip = do
(fname, mtype, rseqid) <- readMessageBegin ip
if mtype == M_EXCEPTION then do
x <- readAppExn ip
readMessageEnd ip
throw x
else return ()
res <- read_DownloadMesh_result ip
readMessageEnd ip
case f_DownloadMesh_result_success res of
Just v -> return v
Nothing -> do
throw (AppExn AE_MISSING_RESULT "downloadMesh failed: unknown result")
| csabahruska/GFXDemo | Thrift/ContentProvider_Client.hs | bsd-3-clause | 1,913 | 0 | 14 | 392 | 416 | 231 | 185 | 45 | 3 |
{-# Language ScopedTypeVariables #-}
{-# Language DeriveGeneric #-}
{-# Language DeriveDataTypeable #-}
module StateManager where
import Control.Distributed.Process
import Control.Monad (filterM)
import Control.Monad.Trans.State.Strict
import Control.Monad.Trans.Class (lift)
import Data.Binary (Binary)
import Data.Map as Map
import Data.Maybe
import Data.Typeable
import GHC.Generics
import Task
type TaskState = Map.Map TaskId TaskResult
type StateProcess = StateT TaskState Process
data StateReq
= Finish (TaskId, TaskResult)
| CheckDeps (ProcessId, [TaskId])
deriving (Show, Generic, Typeable)
instance Binary StateReq
isFinished :: TaskId -> StateProcess Bool
isFinished tid = do
taskState <- get
return (isJust $ Map.lookup tid taskState)
updateState :: TaskId -> TaskResult -> StateProcess ()
updateState tid res = modify $ \s -> insert tid res s
stateManager :: Process ()
stateManager = do
say "starting state manager"
evalStateT stateProc Map.empty
where
stateProc :: StateProcess ()
stateProc = do
(req :: StateReq) <- lift expect
case req of
Finish (tid, res) -> updateState tid res
CheckDeps (pid, deps) -> do
numFinished <- filterM isFinished deps
lift $ send pid (length numFinished == length deps)
stateProc
| sgeop/side-batch | src/StateManager.hs | bsd-3-clause | 1,333 | 0 | 18 | 274 | 391 | 207 | 184 | 40 | 2 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Cardano.Wallet.API.Indices (
module Cardano.Wallet.API.Indices
-- * Re-exports from IxSet for convenience
-- (these were previously /defined/ in this module)
, IndicesOf
, IxSet
, Indexable
, IsIndexOf
) where
import Universum
import Cardano.Wallet.API.V1.Types
import qualified Data.Text as T
import GHC.TypeLits
import qualified Pos.Chain.Txp as Txp
import qualified Pos.Core as Core
import Pos.Crypto (decodeHash)
import Cardano.Wallet.Kernel.DB.Util.IxSet (HasPrimKey (..),
Indexable, IndicesOf, IsIndexOf, IxSet, OrdByPrimKey,
ixFun, ixList)
import qualified Data.IxSet.Typed as IxSet
-- | 'ToIndex' represents the witness that we can build an index 'ix' for a resource 'a'
-- from an input 'Text'.
class ToIndex a ix where
-- | How to build this index from the input 'Text'.
toIndex :: Proxy a -> Text -> Maybe ix
-- | How to access this index from the input data.
accessIx :: (a -> ix)
instance ToIndex Wallet WalletId where
toIndex _ x = Just (WalletId x)
accessIx Wallet{..} = walId
instance ToIndex Wallet Core.Coin where
toIndex _ x = case readMaybe (T.unpack x) of
Nothing -> Nothing
Just c | c > Core.maxCoinVal -> Nothing
Just c -> Just (Core.mkCoin c)
accessIx Wallet{..} = let (V1 balance) = walBalance in balance
instance ToIndex Wallet (V1 Core.Timestamp) where
toIndex _ = fmap V1 . Core.parseTimestamp
accessIx = walCreatedAt
instance ToIndex Transaction (V1 Txp.TxId) where
toIndex _ = fmap V1 . rightToMaybe . decodeHash
accessIx Transaction{..} = txId
instance ToIndex Transaction (V1 Core.Timestamp) where
toIndex _ = fmap V1 . Core.parseTimestamp
accessIx Transaction{..} = txCreationTime
instance ToIndex WalletAddress (V1 Core.Address) where
toIndex _ = fmap V1 . either (const Nothing) Just . Core.decodeTextAddress
accessIx WalletAddress{..} = addrId
--
-- Primary and secondary indices for V1 types
--
instance HasPrimKey Wallet where
type PrimKey Wallet = WalletId
primKey = walId
instance HasPrimKey Account where
type PrimKey Account = AccountIndex
primKey = accIndex
instance HasPrimKey Transaction where
type PrimKey Transaction = V1 Txp.TxId
primKey = txId
instance HasPrimKey WalletAddress where
type PrimKey WalletAddress = V1 Core.Address
primKey = addrId
-- | The secondary indices for each major resource.
type SecondaryWalletIxs = '[Core.Coin, V1 Core.Timestamp]
type SecondaryTransactionIxs = '[V1 Core.Timestamp]
type SecondaryAccountIxs = '[]
type SecondaryWalletAddressIxs = '[]
type instance IndicesOf Wallet = SecondaryWalletIxs
type instance IndicesOf Account = SecondaryAccountIxs
type instance IndicesOf Transaction = SecondaryTransactionIxs
type instance IndicesOf WalletAddress = SecondaryWalletAddressIxs
--
-- Indexable instances for V1 types
--
-- TODO [CBR-356] These should not exist! We should not create 'IxSet's
-- (with their indices) on the fly. Fortunately, the only one for which this
-- is /really/ important is addresses, for which we already have special
-- cases. Nonetheless, the instances below should also go.
--
-- Instance for 'WalletAddress' is available only in
-- "Cardano.Wallet.API.V1.LegacyHandlers.Instances". The same should be done
-- for the other instances here.
--
instance IxSet.Indexable (WalletId ': SecondaryWalletIxs)
(OrdByPrimKey Wallet) where
indices = ixList (ixFun ((:[]) . unV1 . walBalance))
(ixFun ((:[]) . walCreatedAt))
instance IxSet.Indexable (V1 Txp.TxId ': SecondaryTransactionIxs)
(OrdByPrimKey Transaction) where
indices = ixList (ixFun (\Transaction{..} -> [txCreationTime]))
instance IxSet.Indexable (AccountIndex ': SecondaryAccountIxs)
(OrdByPrimKey Account) where
indices = ixList
-- | Extract the parameter names from a type leve list with the shape
type family ParamNames res xs where
ParamNames res '[] =
'[]
ParamNames res (ty ': xs) =
IndexToQueryParam res ty ': ParamNames res xs
-- | This type family allows you to recover the query parameter if you know
-- the resource and index into that resource.
type family IndexToQueryParam resource ix where
IndexToQueryParam Account AccountIndex = "id"
IndexToQueryParam Wallet Core.Coin = "balance"
IndexToQueryParam Wallet WalletId = "id"
IndexToQueryParam Wallet (V1 Core.Timestamp) = "created_at"
IndexToQueryParam WalletAddress (V1 Core.Address) = "address"
IndexToQueryParam Transaction (V1 Txp.TxId) = "id"
IndexToQueryParam Transaction (V1 Core.Timestamp) = "created_at"
-- This is the fallback case. It will trigger a type error if you use
-- 'IndexToQueryParam'' with a pairing that is invalid. We want this to
-- trigger early, so that we don't get Weird Errors later on with stuck
-- types.
IndexToQueryParam res ix = TypeError (
'Text "You used `IndexToQueryParam' with the following resource:"
':$$: 'Text " " ':<>: 'ShowType res
':$$: 'Text "and index type:"
':$$: 'Text " " ':<>: 'ShowType ix
':$$: 'Text "But no instance for that type was defined."
':$$: 'Text "Perhaps you mismatched a resource and an index?"
':$$: 'Text "Or, maybe you need to add a type instance to `IndexToQueryParam'."
)
-- | Type-level composition of 'KnownSymbol' and 'IndexToQueryParam'
--
-- TODO: Alternatively, it would be possible to get rid of 'IndexToQueryParam'
-- completely and just have the 'KnownQueryParam' class.
class KnownSymbol (IndexToQueryParam resource ix) => KnownQueryParam resource ix
instance KnownQueryParam Account AccountIndex
instance KnownQueryParam Wallet Core.Coin
instance KnownQueryParam Wallet WalletId
instance KnownQueryParam Wallet (V1 Core.Timestamp)
instance KnownQueryParam WalletAddress (V1 Core.Address)
instance KnownQueryParam Transaction (V1 Txp.TxId)
instance KnownQueryParam Transaction (V1 Core.Timestamp)
| input-output-hk/pos-haskell-prototype | wallet/src/Cardano/Wallet/API/Indices.hs | mit | 6,558 | 0 | 17 | 1,529 | 1,346 | 725 | 621 | -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.Support.CreateCase
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Creates a new case in the AWS Support Center. This operation is modeled on
-- the behavior of the AWS Support Center <https://console.aws.amazon.com/support/home#/case/create Create Case> page. Its parameters
-- require you to specify the following information:
--
-- IssueType. The type of issue for the case. You can specify either
-- "customer-service" or "technical." If you do not indicate a value, the
-- default is "technical." ServiceCode. The code for an AWS service. You
-- obtain the 'ServiceCode' by calling 'DescribeServices'. CategoryCode. The
-- category for the service defined for the 'ServiceCode' value. You also obtain
-- the category code for a service by calling 'DescribeServices'. Each AWS service
-- defines its own set of category codes. SeverityCode. A value that indicates
-- the urgency of the case, which in turn determines the response time according
-- to your service level agreement with AWS Support. You obtain the SeverityCode
-- by calling 'DescribeSeverityLevels'. Subject. The Subject field on the AWS
-- Support Center <https://console.aws.amazon.com/support/home#/case/create Create Case> page. CommunicationBody. The Description field on
-- the AWS Support Center <https://console.aws.amazon.com/support/home#/case/create Create Case> page. AttachmentSetId. The ID of a set of
-- attachments that has been created by using 'AddAttachmentsToSet'. Language.
-- The human language in which AWS Support handles the case. English and
-- Japanese are currently supported. CcEmailAddresses. The AWS Support Center CC
-- field on the <https://console.aws.amazon.com/support/home#/case/create Create Case> page. You can list email addresses to be copied on
-- any correspondence about the case. The account that opens the case is already
-- identified by passing the AWS Credentials in the HTTP POST method or in a
-- method or function call from one of the programming languages supported by an <http://aws.amazon.com/tools/ AWS SDK>. To add additional communication or attachments to an existing
-- case, use 'AddCommunicationToCase'.
--
-- A successful 'CreateCase' request returns an AWS Support case number. Case
-- numbers are used by the 'DescribeCases' operation to retrieve existing AWS
-- Support cases.
--
-- <http://docs.aws.amazon.com/awssupport/latest/APIReference/API_CreateCase.html>
module Network.AWS.Support.CreateCase
(
-- * Request
CreateCase
-- ** Request constructor
, createCase
-- ** Request lenses
, ccAttachmentSetId
, ccCategoryCode
, ccCcEmailAddresses
, ccCommunicationBody
, ccIssueType
, ccLanguage
, ccServiceCode
, ccSeverityCode
, ccSubject
-- * Response
, CreateCaseResponse
-- ** Response constructor
, createCaseResponse
-- ** Response lenses
, ccrCaseId
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.Support.Types
import qualified GHC.Exts
data CreateCase = CreateCase
{ _ccAttachmentSetId :: Maybe Text
, _ccCategoryCode :: Maybe Text
, _ccCcEmailAddresses :: List "ccEmailAddresses" Text
, _ccCommunicationBody :: Text
, _ccIssueType :: Maybe Text
, _ccLanguage :: Maybe Text
, _ccServiceCode :: Maybe Text
, _ccSeverityCode :: Maybe Text
, _ccSubject :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'CreateCase' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ccAttachmentSetId' @::@ 'Maybe' 'Text'
--
-- * 'ccCategoryCode' @::@ 'Maybe' 'Text'
--
-- * 'ccCcEmailAddresses' @::@ ['Text']
--
-- * 'ccCommunicationBody' @::@ 'Text'
--
-- * 'ccIssueType' @::@ 'Maybe' 'Text'
--
-- * 'ccLanguage' @::@ 'Maybe' 'Text'
--
-- * 'ccServiceCode' @::@ 'Maybe' 'Text'
--
-- * 'ccSeverityCode' @::@ 'Maybe' 'Text'
--
-- * 'ccSubject' @::@ 'Text'
--
createCase :: Text -- ^ 'ccSubject'
-> Text -- ^ 'ccCommunicationBody'
-> CreateCase
createCase p1 p2 = CreateCase
{ _ccSubject = p1
, _ccCommunicationBody = p2
, _ccServiceCode = Nothing
, _ccSeverityCode = Nothing
, _ccCategoryCode = Nothing
, _ccCcEmailAddresses = mempty
, _ccLanguage = Nothing
, _ccIssueType = Nothing
, _ccAttachmentSetId = Nothing
}
-- | The ID of a set of one or more attachments for the case. Create the set by
-- using 'AddAttachmentsToSet'.
ccAttachmentSetId :: Lens' CreateCase (Maybe Text)
ccAttachmentSetId =
lens _ccAttachmentSetId (\s a -> s { _ccAttachmentSetId = a })
-- | The category of problem for the AWS Support case.
ccCategoryCode :: Lens' CreateCase (Maybe Text)
ccCategoryCode = lens _ccCategoryCode (\s a -> s { _ccCategoryCode = a })
-- | A list of email addresses that AWS Support copies on case correspondence.
ccCcEmailAddresses :: Lens' CreateCase [Text]
ccCcEmailAddresses =
lens _ccCcEmailAddresses (\s a -> s { _ccCcEmailAddresses = a })
. _List
-- | The communication body text when you create an AWS Support case by calling 'CreateCase'.
ccCommunicationBody :: Lens' CreateCase Text
ccCommunicationBody =
lens _ccCommunicationBody (\s a -> s { _ccCommunicationBody = a })
-- | The type of issue for the case. You can specify either "customer-service" or
-- "technical." If you do not indicate a value, the default is "technical."
ccIssueType :: Lens' CreateCase (Maybe Text)
ccIssueType = lens _ccIssueType (\s a -> s { _ccIssueType = a })
-- | The ISO 639-1 code for the language in which AWS provides support. AWS
-- Support currently supports English ("en") and Japanese ("ja"). Language
-- parameters must be passed explicitly for operations that take them.
ccLanguage :: Lens' CreateCase (Maybe Text)
ccLanguage = lens _ccLanguage (\s a -> s { _ccLanguage = a })
-- | The code for the AWS service returned by the call to 'DescribeServices'.
ccServiceCode :: Lens' CreateCase (Maybe Text)
ccServiceCode = lens _ccServiceCode (\s a -> s { _ccServiceCode = a })
-- | The code for the severity level returned by the call to 'DescribeSeverityLevels'
-- .
--
-- The availability of severity levels depends on each customer's support
-- subscription. In other words, your subscription may not necessarily require
-- the urgent level of response time.
--
ccSeverityCode :: Lens' CreateCase (Maybe Text)
ccSeverityCode = lens _ccSeverityCode (\s a -> s { _ccSeverityCode = a })
-- | The title of the AWS Support case.
ccSubject :: Lens' CreateCase Text
ccSubject = lens _ccSubject (\s a -> s { _ccSubject = a })
newtype CreateCaseResponse = CreateCaseResponse
{ _ccrCaseId :: Maybe Text
} deriving (Eq, Ord, Read, Show, Monoid)
-- | 'CreateCaseResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ccrCaseId' @::@ 'Maybe' 'Text'
--
createCaseResponse :: CreateCaseResponse
createCaseResponse = CreateCaseResponse
{ _ccrCaseId = Nothing
}
-- | The AWS Support case ID requested or returned in the call. The case ID is an
-- alphanumeric string formatted as shown in this example: case-/12345678910-2013-c4c1d2bf33c5cf47/
ccrCaseId :: Lens' CreateCaseResponse (Maybe Text)
ccrCaseId = lens _ccrCaseId (\s a -> s { _ccrCaseId = a })
instance ToPath CreateCase where
toPath = const "/"
instance ToQuery CreateCase where
toQuery = const mempty
instance ToHeaders CreateCase
instance ToJSON CreateCase where
toJSON CreateCase{..} = object
[ "subject" .= _ccSubject
, "serviceCode" .= _ccServiceCode
, "severityCode" .= _ccSeverityCode
, "categoryCode" .= _ccCategoryCode
, "communicationBody" .= _ccCommunicationBody
, "ccEmailAddresses" .= _ccCcEmailAddresses
, "language" .= _ccLanguage
, "issueType" .= _ccIssueType
, "attachmentSetId" .= _ccAttachmentSetId
]
instance AWSRequest CreateCase where
type Sv CreateCase = Support
type Rs CreateCase = CreateCaseResponse
request = post "CreateCase"
response = jsonResponse
instance FromJSON CreateCaseResponse where
parseJSON = withObject "CreateCaseResponse" $ \o -> CreateCaseResponse
<$> o .:? "caseId"
| kim/amazonka | amazonka-support/gen/Network/AWS/Support/CreateCase.hs | mpl-2.0 | 9,316 | 0 | 10 | 1,952 | 1,066 | 649 | 417 | 109 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.KMS.GetKeyRotationStatus
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves a Boolean value that indicates whether key rotation is enabled
-- for the specified key.
--
-- /See:/ <http://docs.aws.amazon.com/kms/latest/APIReference/API_GetKeyRotationStatus.html AWS API Reference> for GetKeyRotationStatus.
module Network.AWS.KMS.GetKeyRotationStatus
(
-- * Creating a Request
getKeyRotationStatus
, GetKeyRotationStatus
-- * Request Lenses
, gkrsKeyId
-- * Destructuring the Response
, getKeyRotationStatusResponse
, GetKeyRotationStatusResponse
-- * Response Lenses
, gkrsrsKeyRotationEnabled
, gkrsrsResponseStatus
) where
import Network.AWS.KMS.Types
import Network.AWS.KMS.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'getKeyRotationStatus' smart constructor.
newtype GetKeyRotationStatus = GetKeyRotationStatus'
{ _gkrsKeyId :: Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'GetKeyRotationStatus' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gkrsKeyId'
getKeyRotationStatus
:: Text -- ^ 'gkrsKeyId'
-> GetKeyRotationStatus
getKeyRotationStatus pKeyId_ =
GetKeyRotationStatus'
{ _gkrsKeyId = pKeyId_
}
-- | A unique identifier for the customer master key. This value can be a
-- globally unique identifier or the fully specified ARN to a key.
--
-- - Key ARN Example -
-- arn:aws:kms:us-east-1:123456789012:key\/12345678-1234-1234-1234-123456789012
-- - Globally Unique Key ID Example -
-- 12345678-1234-1234-1234-123456789012
gkrsKeyId :: Lens' GetKeyRotationStatus Text
gkrsKeyId = lens _gkrsKeyId (\ s a -> s{_gkrsKeyId = a});
instance AWSRequest GetKeyRotationStatus where
type Rs GetKeyRotationStatus =
GetKeyRotationStatusResponse
request = postJSON kMS
response
= receiveJSON
(\ s h x ->
GetKeyRotationStatusResponse' <$>
(x .?> "KeyRotationEnabled") <*> (pure (fromEnum s)))
instance ToHeaders GetKeyRotationStatus where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("TrentService.GetKeyRotationStatus" :: ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON GetKeyRotationStatus where
toJSON GetKeyRotationStatus'{..}
= object (catMaybes [Just ("KeyId" .= _gkrsKeyId)])
instance ToPath GetKeyRotationStatus where
toPath = const "/"
instance ToQuery GetKeyRotationStatus where
toQuery = const mempty
-- | /See:/ 'getKeyRotationStatusResponse' smart constructor.
data GetKeyRotationStatusResponse = GetKeyRotationStatusResponse'
{ _gkrsrsKeyRotationEnabled :: !(Maybe Bool)
, _gkrsrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'GetKeyRotationStatusResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gkrsrsKeyRotationEnabled'
--
-- * 'gkrsrsResponseStatus'
getKeyRotationStatusResponse
:: Int -- ^ 'gkrsrsResponseStatus'
-> GetKeyRotationStatusResponse
getKeyRotationStatusResponse pResponseStatus_ =
GetKeyRotationStatusResponse'
{ _gkrsrsKeyRotationEnabled = Nothing
, _gkrsrsResponseStatus = pResponseStatus_
}
-- | A Boolean value that specifies whether key rotation is enabled.
gkrsrsKeyRotationEnabled :: Lens' GetKeyRotationStatusResponse (Maybe Bool)
gkrsrsKeyRotationEnabled = lens _gkrsrsKeyRotationEnabled (\ s a -> s{_gkrsrsKeyRotationEnabled = a});
-- | The response status code.
gkrsrsResponseStatus :: Lens' GetKeyRotationStatusResponse Int
gkrsrsResponseStatus = lens _gkrsrsResponseStatus (\ s a -> s{_gkrsrsResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-kms/gen/Network/AWS/KMS/GetKeyRotationStatus.hs | mpl-2.0 | 4,673 | 0 | 13 | 961 | 585 | 351 | 234 | 76 | 1 |
-- Copyright 2012-2013 Greg Horn
--
-- This file is part of rawesome.
--
-- rawesome is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- rawesome 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 Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public License
-- along with rawesome. If not, see <http://www.gnu.org/licenses/>.
{-# OPTIONS_GHC -Wall #-}
{-# Language DoAndIfThenElse #-}
{-# Language OverloadedStrings #-}
{-# Language CPP #-}
module Main ( main ) where
import Data.Foldable ( toList )
import Data.Maybe ( fromMaybe )
import System.Random ( randomRs, mkStdGen)
#if OSX
import qualified System.ZMQ3 as ZMQ
#else
import qualified System.ZMQ as ZMQ
#endif
import Control.Concurrent ( MVar, forkIO, modifyMVar_, newMVar, readMVar)
import Control.Monad ( forever )
import qualified Data.ByteString.Lazy as BL
import Data.Packed ( fromLists )
import Text.ProtocolBuffers ( messageGet )
import Text.ProtocolBuffers.Basic ( uToString )
--import System.Remote.Monitoring ( forkServer )
import qualified Kite.CarouselState as CS
import qualified Kite.Dcm as Dcm
import qualified Kite.Xyz as KiteXyz
import SpatialMath
import Vis
import DrawAC
data State = State { sTrails :: [[Xyz Double]]
, sCS :: Maybe CS.CarouselState
, sParticles :: [Xyz Double]
}
toNice :: CS.CarouselState -> (Xyz Double, Quat Double, Xyz Double, Xyz Double, Double)
toNice cs = (xyz, q'n'b, r'n0'a0, r'n0't0, fromMaybe 1 $ CS.visSpan cs)
where
x = KiteXyz.x $ CS.kiteXyz cs
y = KiteXyz.y $ CS.kiteXyz cs
z = KiteXyz.z $ CS.kiteXyz cs
r11 = Dcm.r11 $ CS.kiteDcm cs
r12 = Dcm.r12 $ CS.kiteDcm cs
r13 = Dcm.r13 $ CS.kiteDcm cs
r21 = Dcm.r21 $ CS.kiteDcm cs
r22 = Dcm.r22 $ CS.kiteDcm cs
r23 = Dcm.r23 $ CS.kiteDcm cs
r31 = Dcm.r31 $ CS.kiteDcm cs
r32 = Dcm.r32 $ CS.kiteDcm cs
r33 = Dcm.r33 $ CS.kiteDcm cs
delta = CS.delta cs
q'nwu'ned = Quat 0 1 0 0
q'n'a = Quat (cos(0.5*delta)) 0 0 (sin(-0.5*delta))
q'aNWU'bNWU = quatOfDcm $ fromLists [ [r11, r12, r13]
, [r21, r22, r23]
, [r31, r32, r33]
]
q'a'b = q'nwu'ned * q'aNWU'bNWU * q'nwu'ned
q'n'b = q'n'a * q'a'b
q'n'aNWU = q'n'a * q'nwu'ned
rArm = Xyz (CS.rArm cs) 0 0
xyzArm = rArm + Xyz x y z
xyz = rotVecByQuatB2A q'n'aNWU xyzArm
zt = CS.zt cs
r'n0'a0 = rotVecByQuatB2A q'n'a rArm
r'n0't0 = xyz + (rotVecByQuatB2A q'n'b $ Xyz 0 0 (-zt))
drawFun :: State -> VisObject Double
----drawFun state = VisObjects $ [axes] ++ (map text [-5..5]) ++ [boxText, ac, plane,trailLines]
drawFun (State {sCS=Nothing}) = VisObjects []
drawFun state@(State {sCS=Just cs}) =
VisObjects [axes, txt, ac, plane, trailLines, arm, line, zLine, xyLine, points]
where
(pos@(Xyz x y z), quat, r'n0'a0, r'n0't0, visSpan) = toNice cs
points = Points (sParticles state) (Just 2) $ makeColor 1 1 1 0.5
zLine = Line [Xyz x y (planeZ-0.01), pos] $ makeColor 0.1 0.2 1 0.5
xyLine = Line [Xyz x y (planeZ-0.01), Xyz 0 0 (planeZ-0.01)] $ makeColor 0.2 0.7 1 0.5
axes = Axes (0.5, 15)
arm = Line [Xyz 0 0 0, r'n0'a0] $ makeColor 1 1 0 lineAlpha
line = Line [r'n0'a0, r'n0't0] $ makeColor 0 1 1 lineAlpha
plane = Trans (Xyz 0 0 planeZ) $ Plane (Xyz 0 0 1) (makeColor 1 1 1 1) (makeColor 0.2 0.3 0.32 (realToFrac planeAlpha))
planeZ' = planeZ-0.5
planeAlpha
| z < planeZ' = 1
| z < planeZ'+2 = (planeZ'+2-z)/2
| otherwise = 0
txt = VisObjects $
zipWith (\s k -> Text2d (uToString s) (30,fromIntegral $ 30*k) TimesRoman24 (makeColor 1 1 1 1)) messages (reverse [1..length messages])
messages = toList $ CS.messages cs
ac = Trans pos $ Scale (visSpan,visSpan,visSpan) ac'
(ac',_) = drawAc kiteAlpha (Xyz 0 0 0) quat
lineAlpha = realToFrac $ fromMaybe 1 (CS.lineTransparency cs)
kiteAlpha = realToFrac $ fromMaybe 1 (CS.kiteTransparency cs)
trailLines = drawTrails (sTrails state)
planeZ :: Double
planeZ = 1
particleBox :: Double
particleBox = 8
state0 :: State
state0 = State { sCS = Nothing
, sTrails = [[],[],[]]
, sParticles = take 300 $ randomRs (Xyz (-particleBox) (-particleBox) (planeZ-2*particleBox),
Xyz particleBox particleBox planeZ)
(mkStdGen 0)
}
updateTrail :: [Xyz a] -> Xyz a -> [Xyz a]
updateTrail trail0 xyz
| length trail0 < 65 = xyz:trail0
| otherwise = take 65 (xyz:trail0)
boundParticle :: Xyz Double -> Xyz Double
boundParticle xyz@(Xyz x y z)
| x > particleBox = boundParticle (Xyz (x-2*particleBox) y z)
| x < -particleBox = boundParticle (Xyz (x+2*particleBox) y z)
| y > particleBox = boundParticle (Xyz x (y-2*particleBox) z)
| y < -particleBox = boundParticle (Xyz x (y+2*particleBox) z)
| z > planeZ = boundParticle (Xyz x y (z-2*particleBox))
| z < planeZ-2*particleBox = boundParticle (Xyz x y (z+2*particleBox))
| otherwise = xyz
windShear :: Double -> Double -> Double
windShear w0 z
| z' < zt = 0
| otherwise = w0*log(z'/zt)/log(z0/zt)
where
z' = z + planeZ + zt + 2
z0 = 100
zt = 0.1
updateState :: CS.CarouselState -> State -> IO State
updateState cs x0 =
return $ State { sCS = Just cs
, sTrails = zipWith updateTrail trails0 trails
, sParticles = map (\xyz@(Xyz _ _ z) -> boundParticle $ (Xyz (ts*(windShear w0 (-z))) 0 0) + xyz) (sParticles x0)
}
where
w0 = fromMaybe 0 (CS.w0 cs)
trails0 = sTrails x0
(pos,q,_,_,_) = toNice cs
(_,trails) = drawAc 1 pos q
withContext :: (ZMQ.Context -> IO a) -> IO a
#if OSX
withContext = ZMQ.withContext
#else
withContext = ZMQ.withContext 1
#endif
sub :: MVar State -> IO ()
sub m = withContext $ \context -> do
#if OSX
let receive = ZMQ.receive
#else
let receive = flip ZMQ.receive []
#endif
ZMQ.withSocket context ZMQ.Sub $ \subscriber -> do
ZMQ.connect subscriber "tcp://localhost:5563"
ZMQ.subscribe subscriber "carousel"
forever $ do
_ <- receive subscriber
mre <- ZMQ.moreToReceive subscriber
if mre
then do
msg <- receive subscriber
let cs = case messageGet (BL.fromChunks [msg]) of
Left err -> error err
Right (cs',_) -> cs'
modifyMVar_ m (updateState cs)
else return ()
ts :: Double
ts = 0.02
main :: IO ()
main = do
-- _ <- forkServer "localhost" 8000
m <- newMVar state0
_ <- forkIO (sub m)
-- threadDelay 5000000
let simFun _ _ = return ()
df _ = fmap drawFun (readMVar m)
simulateIO (Just ((1260,940),(1930,40))) "kite sim" ts () df simFun
| ghorn/rawesome | wtfviz/src/KiteSim.hs | lgpl-3.0 | 7,212 | 0 | 26 | 1,892 | 2,576 | 1,357 | 1,219 | 145 | 3 |
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.Indexed.Fix
-- Copyright : (C) 2008 Edward Kmett
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : portable
--
----------------------------------------------------------------------------
module Control.Monad.Indexed.Fix
( IxMonadFix(..)
) where
import Control.Monad.Indexed
class IxMonad m => IxMonadFix m where
imfix :: (a -> m i i a) -> m i i a
| urska19/MFP---Samodejno-racunanje-dvosmernih-preslikav | Control/Monad/Indexed/Fix.hs | apache-2.0 | 575 | 4 | 10 | 93 | 84 | 51 | 33 | 5 | 0 |
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "src/Data/Foldable/Compat.hs" #-}
{-# LANGUAGE CPP, NoImplicitPrelude #-}
module Data.Foldable.Compat (
module Base
, maximumBy
, minimumBy
) where
import Data.Foldable as Base hiding (maximumBy, minimumBy)
import Prelude (Ordering(..))
-- | The largest element of a non-empty structure with respect to the
-- given comparison function.
maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
maximumBy cmp = foldl1 max'
where max' x y = case cmp x y of
GT -> x
_ -> y
-- | The least element of a non-empty structure with respect to the
-- given comparison function.
minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
minimumBy cmp = foldl1 min'
where min' x y = case cmp x y of
GT -> y
_ -> x
| phischu/fragnix | tests/packages/scotty/Data.Foldable.Compat.hs | bsd-3-clause | 902 | 0 | 9 | 298 | 210 | 115 | 95 | 19 | 2 |
--
-- Copyright (c) 2013 Citrix Systems, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
module Vm.State where
import Control.Applicative
import Data.Maybe
import XenMgr.Rpc
import Vm.Types
import Tools.XenStore
import Rpc.Autogen.XenmgrConst
import System.Timeout
import Text.Printf
import Tools.Log
stateFromStr :: String -> VmState
stateFromStr "pre-create" = PreCreate
stateFromStr "creating-domain" = CreatingDomain
stateFromStr "creating-devices" = CreatingDevices
stateFromStr "created" = Created
stateFromStr "running" = Running
stateFromStr "shutdown" = Shutdown
stateFromStr "shutdowning" = ShuttingDown
stateFromStr "rebooting" = Rebooting
stateFromStr "rebooted" = Rebooted
stateFromStr "suspended" = Suspended
stateFromStr "suspending" = Suspending
stateFromStr "restoring" = Restoring
stateFromStr "paused" = Paused
stateFromStr s = error $ "unexpected VM state string: " ++ s
stateToStr :: VmState -> String
stateToStr PreCreate = "pre-create"
stateToStr CreatingDomain = "creating-domain"
stateToStr CreatingDevices = "creating-devices"
stateToStr Created = "created"
stateToStr Running = "running"
stateToStr Shutdown = "shutdown"
stateToStr ShuttingDown = "shutdowning"
stateToStr Rebooting = "rebooting"
stateToStr Rebooted = "rebooted"
stateToStr Suspended = "suspended"
stateToStr Suspending = "suspending"
stateToStr Restoring = "restoring"
stateToStr Paused = "paused"
stateToPublicStr :: VmState -> String
stateToPublicStr PreCreate = eVM_STATE_CREATING
stateToPublicStr CreatingDomain = eVM_STATE_CREATING
stateToPublicStr CreatingDevices = eVM_STATE_CREATING
stateToPublicStr Created = eVM_STATE_CREATING
stateToPublicStr Running = eVM_STATE_RUNNING
stateToPublicStr ShuttingDown = eVM_STATE_STOPPING
stateToPublicStr Rebooting = eVM_STATE_REBOOTING
stateToPublicStr Rebooted = eVM_STATE_REBOOTED
stateToPublicStr Suspending = eVM_STATE_SUSPENDING
stateToPublicStr Suspended = eVM_STATE_SUSPENDED
stateToPublicStr Restoring = eVM_STATE_RESTORING
stateToPublicStr Paused = eVM_STATE_PAUSED
stateToPublicStr Shutdown = eVM_STATE_STOPPED
internalStatePath :: Uuid -> String
internalStatePath uuid = "/vm/" ++ show uuid ++ "/state"
updateVmInternalState :: MonadRpc e m => Uuid -> VmState -> m ()
updateVmInternalState uuid s = liftIO (xsWrite (internalStatePath uuid) (stateToStr s))
getVmInternalState :: MonadRpc e m => Uuid -> m VmState
getVmInternalState uuid = fromMaybe Shutdown . fmap stateFromStr <$> (liftIO $ xsRead (internalStatePath uuid))
waitForVmInternalState :: MonadRpc e m => Uuid -> VmState -> Int -> m ()
waitForVmInternalState uuid state to_secs = do
info $ printf "Wait for vm %s state to become %s" (show uuid) stateStr
handle =<< ( liftIO $ timeout (10^6 * to_secs) (xsWaitFor (internalStatePath uuid) check) )
where
stateStr = stateToStr state
check = (== Just stateStr) <$> xsRead (internalStatePath uuid)
handle Nothing = error $ "Timeout while waiting for vm " ++ show uuid ++ " state to become " ++ stateStr ++ " after " ++ show to_secs ++ "s"
handle _ = return ()
| jean-edouard/manager | xenmgr/Vm/State.hs | gpl-2.0 | 3,845 | 0 | 14 | 653 | 768 | 395 | 373 | 67 | 2 |
{-
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[PrimOp]{Primitive operations (machine-level)}
-}
{-# LANGUAGE CPP #-}
module PrimOp (
PrimOp(..), PrimOpVecCat(..), allThePrimOps,
primOpType, primOpSig,
primOpTag, maxPrimOpTag, primOpOcc,
tagToEnumKey,
primOpOutOfLine, primOpCodeSize,
primOpOkForSpeculation, primOpOkForSideEffects,
primOpIsCheap, primOpFixity,
getPrimOpResultInfo, PrimOpResultInfo(..),
PrimCall(..)
) where
#include "HsVersions.h"
import TysPrim
import TysWiredIn
import CmmType
import Demand
import Var ( TyVar )
import OccName ( OccName, pprOccName, mkVarOccFS )
import TyCon ( TyCon, isPrimTyCon, tyConPrimRep, PrimRep(..) )
import Type ( Type, mkForAllTys, mkFunTy, mkFunTys, tyConAppTyCon,
typePrimRep )
import BasicTypes ( Arity, Fixity(..), FixityDirection(..), Boxity(..) )
import ForeignCall ( CLabelString )
import Unique ( Unique, mkPrimOpIdUnique )
import Outputable
import FastString
import Module ( UnitId )
{-
************************************************************************
* *
\subsection[PrimOp-datatype]{Datatype for @PrimOp@ (an enumeration)}
* *
************************************************************************
These are in \tr{state-interface.verb} order.
-}
-- supplies:
-- data PrimOp = ...
#include "primop-data-decl.hs-incl"
-- supplies
-- primOpTag :: PrimOp -> Int
#include "primop-tag.hs-incl"
primOpTag _ = error "primOpTag: unknown primop"
instance Eq PrimOp where
op1 == op2 = primOpTag op1 == primOpTag op2
instance Ord PrimOp where
op1 < op2 = primOpTag op1 < primOpTag op2
op1 <= op2 = primOpTag op1 <= primOpTag op2
op1 >= op2 = primOpTag op1 >= primOpTag op2
op1 > op2 = primOpTag op1 > primOpTag op2
op1 `compare` op2 | op1 < op2 = LT
| op1 == op2 = EQ
| otherwise = GT
instance Outputable PrimOp where
ppr op = pprPrimOp op
data PrimOpVecCat = IntVec
| WordVec
| FloatVec
-- An @Enum@-derived list would be better; meanwhile... (ToDo)
allThePrimOps :: [PrimOp]
allThePrimOps =
#include "primop-list.hs-incl"
tagToEnumKey :: Unique
tagToEnumKey = mkPrimOpIdUnique (primOpTag TagToEnumOp)
{-
************************************************************************
* *
\subsection[PrimOp-info]{The essential info about each @PrimOp@}
* *
************************************************************************
The @String@ in the @PrimOpInfos@ is the ``base name'' by which the user may
refer to the primitive operation. The conventional \tr{#}-for-
unboxed ops is added on later.
The reason for the funny characters in the names is so we do not
interfere with the programmer's Haskell name spaces.
We use @PrimKinds@ for the ``type'' information, because they're
(slightly) more convenient to use than @TyCons@.
-}
data PrimOpInfo
= Dyadic OccName -- string :: T -> T -> T
Type
| Monadic OccName -- string :: T -> T
Type
| Compare OccName -- string :: T -> T -> Int#
Type
| GenPrimOp OccName -- string :: \/a1..an . T1 -> .. -> Tk -> T
[TyVar]
[Type]
Type
mkDyadic, mkMonadic, mkCompare :: FastString -> Type -> PrimOpInfo
mkDyadic str ty = Dyadic (mkVarOccFS str) ty
mkMonadic str ty = Monadic (mkVarOccFS str) ty
mkCompare str ty = Compare (mkVarOccFS str) ty
mkGenPrimOp :: FastString -> [TyVar] -> [Type] -> Type -> PrimOpInfo
mkGenPrimOp str tvs tys ty = GenPrimOp (mkVarOccFS str) tvs tys ty
{-
************************************************************************
* *
\subsubsection{Strictness}
* *
************************************************************************
Not all primops are strict!
-}
primOpStrictness :: PrimOp -> Arity -> StrictSig
-- See Demand.StrictnessInfo for discussion of what the results
-- The arity should be the arity of the primop; that's why
-- this function isn't exported.
#include "primop-strictness.hs-incl"
{-
************************************************************************
* *
\subsubsection{Fixity}
* *
************************************************************************
-}
primOpFixity :: PrimOp -> Maybe Fixity
#include "primop-fixity.hs-incl"
{-
************************************************************************
* *
\subsubsection[PrimOp-comparison]{PrimOpInfo basic comparison ops}
* *
************************************************************************
@primOpInfo@ gives all essential information (from which everything
else, notably a type, can be constructed) for each @PrimOp@.
-}
primOpInfo :: PrimOp -> PrimOpInfo
#include "primop-primop-info.hs-incl"
primOpInfo _ = error "primOpInfo: unknown primop"
{-
Here are a load of comments from the old primOp info:
A @Word#@ is an unsigned @Int#@.
@decodeFloat#@ is given w/ Integer-stuff (it's similar).
@decodeDouble#@ is given w/ Integer-stuff (it's similar).
Decoding of floating-point numbers is sorta Integer-related. Encoding
is done with plain ccalls now (see PrelNumExtra.hs).
A @Weak@ Pointer is created by the @mkWeak#@ primitive:
mkWeak# :: k -> v -> f -> State# RealWorld
-> (# State# RealWorld, Weak# v #)
In practice, you'll use the higher-level
data Weak v = Weak# v
mkWeak :: k -> v -> IO () -> IO (Weak v)
The following operation dereferences a weak pointer. The weak pointer
may have been finalized, so the operation returns a result code which
must be inspected before looking at the dereferenced value.
deRefWeak# :: Weak# v -> State# RealWorld ->
(# State# RealWorld, v, Int# #)
Only look at v if the Int# returned is /= 0 !!
The higher-level op is
deRefWeak :: Weak v -> IO (Maybe v)
Weak pointers can be finalized early by using the finalize# operation:
finalizeWeak# :: Weak# v -> State# RealWorld ->
(# State# RealWorld, Int#, IO () #)
The Int# returned is either
0 if the weak pointer has already been finalized, or it has no
finalizer (the third component is then invalid).
1 if the weak pointer is still alive, with the finalizer returned
as the third component.
A {\em stable name/pointer} is an index into a table of stable name
entries. Since the garbage collector is told about stable pointers,
it is safe to pass a stable pointer to external systems such as C
routines.
\begin{verbatim}
makeStablePtr# :: a -> State# RealWorld -> (# State# RealWorld, StablePtr# a #)
freeStablePtr :: StablePtr# a -> State# RealWorld -> State# RealWorld
deRefStablePtr# :: StablePtr# a -> State# RealWorld -> (# State# RealWorld, a #)
eqStablePtr# :: StablePtr# a -> StablePtr# a -> Int#
\end{verbatim}
It may seem a bit surprising that @makeStablePtr#@ is a @IO@
operation since it doesn't (directly) involve IO operations. The
reason is that if some optimisation pass decided to duplicate calls to
@makeStablePtr#@ and we only pass one of the stable pointers over, a
massive space leak can result. Putting it into the IO monad
prevents this. (Another reason for putting them in a monad is to
ensure correct sequencing wrt the side-effecting @freeStablePtr@
operation.)
An important property of stable pointers is that if you call
makeStablePtr# twice on the same object you get the same stable
pointer back.
Note that we can implement @freeStablePtr#@ using @_ccall_@ (and,
besides, it's not likely to be used from Haskell) so it's not a
primop.
Question: Why @RealWorld@ - won't any instance of @_ST@ do the job? [ADR]
Stable Names
~~~~~~~~~~~~
A stable name is like a stable pointer, but with three important differences:
(a) You can't deRef one to get back to the original object.
(b) You can convert one to an Int.
(c) You don't need to 'freeStableName'
The existence of a stable name doesn't guarantee to keep the object it
points to alive (unlike a stable pointer), hence (a).
Invariants:
(a) makeStableName always returns the same value for a given
object (same as stable pointers).
(b) if two stable names are equal, it implies that the objects
from which they were created were the same.
(c) stableNameToInt always returns the same Int for a given
stable name.
These primops are pretty weird.
dataToTag# :: a -> Int (arg must be an evaluated data type)
tagToEnum# :: Int -> a (result type must be an enumerated type)
The constraints aren't currently checked by the front end, but the
code generator will fall over if they aren't satisfied.
************************************************************************
* *
Which PrimOps are out-of-line
* *
************************************************************************
Some PrimOps need to be called out-of-line because they either need to
perform a heap check or they block.
-}
primOpOutOfLine :: PrimOp -> Bool
#include "primop-out-of-line.hs-incl"
{-
************************************************************************
* *
Failure and side effects
* *
************************************************************************
Note [PrimOp can_fail and has_side_effects]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Both can_fail and has_side_effects mean that the primop has
some effect that is not captured entirely by its result value.
---------- has_side_effects ---------------------
A primop "has_side_effects" if it has some *write* effect, visible
elsewhere
- writing to the world (I/O)
- writing to a mutable data structure (writeIORef)
- throwing a synchronous Haskell exception
Often such primops have a type like
State -> input -> (State, output)
so the state token guarantees ordering. In general we rely *only* on
data dependencies of the state token to enforce write-effect ordering
* NB1: if you inline unsafePerformIO, you may end up with
side-effecting ops whose 'state' output is discarded.
And programmers may do that by hand; see Trac #9390.
That is why we (conservatively) do not discard write-effecting
primops even if both their state and result is discarded.
* NB2: We consider primops, such as raiseIO#, that can raise a
(Haskell) synchronous exception to "have_side_effects" but not
"can_fail". We must be careful about not discarding such things;
see the paper "A semantics for imprecise exceptions".
* NB3: *Read* effects (like reading an IORef) don't count here,
because it doesn't matter if we don't do them, or do them more than
once. *Sequencing* is maintained by the data dependency of the state
token.
---------- can_fail ----------------------------
A primop "can_fail" if it can fail with an *unchecked* exception on
some elements of its input domain. Main examples:
division (fails on zero demoninator)
array indexing (fails if the index is out of bounds)
An "unchecked exception" is one that is an outright error, (not
turned into a Haskell exception,) such as seg-fault or
divide-by-zero error. Such can_fail primops are ALWAYS surrounded
with a test that checks for the bad cases, but we need to be
very careful about code motion that might move it out of
the scope of the test.
Note [Transformations affected by can_fail and has_side_effects]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The can_fail and has_side_effects properties have the following effect
on program transformations. Summary table is followed by details.
can_fail has_side_effects
Discard NO NO
Float in YES YES
Float out NO NO
Duplicate YES NO
* Discarding. case (a `op` b) of _ -> rhs ===> rhs
You should not discard a has_side_effects primop; e.g.
case (writeIntArray# a i v s of (# _, _ #) -> True
Arguably you should be able to discard this, since the
returned stat token is not used, but that relies on NEVER
inlining unsafePerformIO, and programmers sometimes write
this kind of stuff by hand (Trac #9390). So we (conservatively)
never discard a has_side_effects primop.
However, it's fine to discard a can_fail primop. For example
case (indexIntArray# a i) of _ -> True
We can discard indexIntArray#; it has can_fail, but not
has_side_effects; see Trac #5658 which was all about this.
Notice that indexIntArray# is (in a more general handling of
effects) read effect, but we don't care about that here, and
treat read effects as *not* has_side_effects.
Similarly (a `/#` b) can be discarded. It can seg-fault or
cause a hardware exception, but not a synchronous Haskell
exception.
Synchronous Haskell exceptions, e.g. from raiseIO#, are treated
as has_side_effects and hence are not discarded.
* Float in. You can float a can_fail or has_side_effects primop
*inwards*, but not inside a lambda (see Duplication below).
* Float out. You must not float a can_fail primop *outwards* lest
you escape the dynamic scope of the test. Example:
case d ># 0# of
True -> case x /# d of r -> r +# 1
False -> 0
Here we must not float the case outwards to give
case x/# d of r ->
case d ># 0# of
True -> r +# 1
False -> 0
Nor can you float out a has_side_effects primop. For example:
if blah then case writeMutVar# v True s0 of (# s1 #) -> s1
else s0
Notice that s0 is mentioned in both branches of the 'if', but
only one of these two will actually be consumed. But if we
float out to
case writeMutVar# v True s0 of (# s1 #) ->
if blah then s1 else s0
the writeMutVar will be performed in both branches, which is
utterly wrong.
* Duplication. You cannot duplicate a has_side_effect primop. You
might wonder how this can occur given the state token threading, but
just look at Control.Monad.ST.Lazy.Imp.strictToLazy! We get
something like this
p = case readMutVar# s v of
(# s', r #) -> (S# s', r)
s' = case p of (s', r) -> s'
r = case p of (s', r) -> r
(All these bindings are boxed.) If we inline p at its two call
sites, we get a catastrophe: because the read is performed once when
s' is demanded, and once when 'r' is demanded, which may be much
later. Utterly wrong. Trac #3207 is real example of this happening.
However, it's fine to duplicate a can_fail primop. That is really
the only difference between can_fail and has_side_effects.
Note [Implementation: how can_fail/has_side_effects affect transformations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
How do we ensure that that floating/duplication/discarding are done right
in the simplifier?
Two main predicates on primpops test these flags:
primOpOkForSideEffects <=> not has_side_effects
primOpOkForSpeculation <=> not (has_side_effects || can_fail)
* The "no-float-out" thing is achieved by ensuring that we never
let-bind a can_fail or has_side_effects primop. The RHS of a
let-binding (which can float in and out freely) satisfies
exprOkForSpeculation; this is the let/app invariant. And
exprOkForSpeculation is false of can_fail and has_side_effects.
* So can_fail and has_side_effects primops will appear only as the
scrutinees of cases, and that's why the FloatIn pass is capable
of floating case bindings inwards.
* The no-duplicate thing is done via primOpIsCheap, by making
has_side_effects things (very very very) not-cheap!
-}
primOpHasSideEffects :: PrimOp -> Bool
#include "primop-has-side-effects.hs-incl"
primOpCanFail :: PrimOp -> Bool
#include "primop-can-fail.hs-incl"
primOpOkForSpeculation :: PrimOp -> Bool
-- See Note [PrimOp can_fail and has_side_effects]
-- See comments with CoreUtils.exprOkForSpeculation
-- primOpOkForSpeculation => primOpOkForSideEffects
primOpOkForSpeculation op
= primOpOkForSideEffects op
&& not (primOpOutOfLine op || primOpCanFail op)
-- I think the "out of line" test is because out of line things can
-- be expensive (eg sine, cosine), and so we may not want to speculate them
primOpOkForSideEffects :: PrimOp -> Bool
primOpOkForSideEffects op
= not (primOpHasSideEffects op)
{-
Note [primOpIsCheap]
~~~~~~~~~~~~~~~~~~~~
@primOpIsCheap@, as used in \tr{SimplUtils.hs}. For now (HACK
WARNING), we just borrow some other predicates for a
what-should-be-good-enough test. "Cheap" means willing to call it more
than once, and/or push it inside a lambda. The latter could change the
behaviour of 'seq' for primops that can fail, so we don't treat them as cheap.
-}
primOpIsCheap :: PrimOp -> Bool
-- See Note [PrimOp can_fail and has_side_effects]
primOpIsCheap op = primOpOkForSpeculation op
-- In March 2001, we changed this to
-- primOpIsCheap op = False
-- thereby making *no* primops seem cheap. But this killed eta
-- expansion on case (x ==# y) of True -> \s -> ...
-- which is bad. In particular a loop like
-- doLoop n = loop 0
-- where
-- loop i | i == n = return ()
-- | otherwise = bar i >> loop (i+1)
-- allocated a closure every time round because it doesn't eta expand.
--
-- The problem that originally gave rise to the change was
-- let x = a +# b *# c in x +# x
-- were we don't want to inline x. But primopIsCheap doesn't control
-- that (it's exprIsDupable that does) so the problem doesn't occur
-- even if primOpIsCheap sometimes says 'True'.
{-
************************************************************************
* *
PrimOp code size
* *
************************************************************************
primOpCodeSize
~~~~~~~~~~~~~~
Gives an indication of the code size of a primop, for the purposes of
calculating unfolding sizes; see CoreUnfold.sizeExpr.
-}
primOpCodeSize :: PrimOp -> Int
#include "primop-code-size.hs-incl"
primOpCodeSizeDefault :: Int
primOpCodeSizeDefault = 1
-- CoreUnfold.primOpSize already takes into account primOpOutOfLine
-- and adds some further costs for the args in that case.
primOpCodeSizeForeignCall :: Int
primOpCodeSizeForeignCall = 4
{-
************************************************************************
* *
PrimOp types
* *
************************************************************************
-}
primOpType :: PrimOp -> Type -- you may want to use primOpSig instead
primOpType op
= case primOpInfo op of
Dyadic _occ ty -> dyadic_fun_ty ty
Monadic _occ ty -> monadic_fun_ty ty
Compare _occ ty -> compare_fun_ty ty
GenPrimOp _occ tyvars arg_tys res_ty ->
mkForAllTys tyvars (mkFunTys arg_tys res_ty)
primOpOcc :: PrimOp -> OccName
primOpOcc op = case primOpInfo op of
Dyadic occ _ -> occ
Monadic occ _ -> occ
Compare occ _ -> occ
GenPrimOp occ _ _ _ -> occ
-- primOpSig is like primOpType but gives the result split apart:
-- (type variables, argument types, result type)
-- It also gives arity, strictness info
primOpSig :: PrimOp -> ([TyVar], [Type], Type, Arity, StrictSig)
primOpSig op
= (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity)
where
arity = length arg_tys
(tyvars, arg_tys, res_ty)
= case (primOpInfo op) of
Monadic _occ ty -> ([], [ty], ty )
Dyadic _occ ty -> ([], [ty,ty], ty )
Compare _occ ty -> ([], [ty,ty], intPrimTy)
GenPrimOp _occ tyvars arg_tys res_ty -> (tyvars, arg_tys, res_ty )
data PrimOpResultInfo
= ReturnsPrim PrimRep
| ReturnsAlg TyCon
-- Some PrimOps need not return a manifest primitive or algebraic value
-- (i.e. they might return a polymorphic value). These PrimOps *must*
-- be out of line, or the code generator won't work.
getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo
getPrimOpResultInfo op
= case (primOpInfo op) of
Dyadic _ ty -> ReturnsPrim (typePrimRep ty)
Monadic _ ty -> ReturnsPrim (typePrimRep ty)
Compare _ _ -> ReturnsPrim (tyConPrimRep intPrimTyCon)
GenPrimOp _ _ _ ty | isPrimTyCon tc -> ReturnsPrim (tyConPrimRep tc)
| otherwise -> ReturnsAlg tc
where
tc = tyConAppTyCon ty
-- All primops return a tycon-app result
-- The tycon can be an unboxed tuple, though, which
-- gives rise to a ReturnAlg
{-
We do not currently make use of whether primops are commutable.
We used to try to move constants to the right hand side for strength
reduction.
-}
{-
commutableOp :: PrimOp -> Bool
#include "primop-commutable.hs-incl"
-}
-- Utils:
dyadic_fun_ty, monadic_fun_ty, compare_fun_ty :: Type -> Type
dyadic_fun_ty ty = mkFunTys [ty, ty] ty
monadic_fun_ty ty = mkFunTy ty ty
compare_fun_ty ty = mkFunTys [ty, ty] intPrimTy
-- Output stuff:
pprPrimOp :: PrimOp -> SDoc
pprPrimOp other_op = pprOccName (primOpOcc other_op)
{-
************************************************************************
* *
\subsubsection[PrimCall]{User-imported primitive calls}
* *
************************************************************************
-}
data PrimCall = PrimCall CLabelString UnitId
instance Outputable PrimCall where
ppr (PrimCall lbl pkgId)
= text "__primcall" <+> ppr pkgId <+> ppr lbl
| siddhanathan/ghc | compiler/prelude/PrimOp.hs | bsd-3-clause | 23,245 | 0 | 11 | 6,302 | 1,556 | 858 | 698 | -1 | -1 |
module Test20 where
y c = c
f n y = n y
g = (f 1 1)
h = (+1) 1
| kmate/HaRe | old/testing/refacFunDef/Test20.hs | bsd-3-clause | 67 | 0 | 6 | 26 | 50 | 27 | 23 | 5 | 1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
@Uniques@ are used to distinguish entities in the compiler (@Ids@,
@Classes@, etc.) from each other. Thus, @Uniques@ are the basic
comparison key in the compiler.
If there is any single operation that needs to be fast, it is @Unique@
comparison. Unsurprisingly, there is quite a bit of huff-and-puff
directed to that end.
Some of the other hair in this code is to be able to use a
``splittable @UniqueSupply@'' if requested/possible (not standard
Haskell).
-}
{-# LANGUAGE CPP, BangPatterns, MagicHash #-}
module Unique (
-- * Main data types
Unique, Uniquable(..),
-- ** Constructors, desctructors and operations on 'Unique's
hasKey,
pprUnique,
mkUniqueGrimily, -- Used in UniqSupply only!
getKey, -- Used in Var, UniqFM, Name only!
mkUnique, unpkUnique, -- Used in BinIface only
incrUnique, -- Used for renumbering
deriveUnique, -- Ditto
newTagUnique, -- Used in CgCase
initTyVarUnique,
-- ** Making built-in uniques
-- now all the built-in Uniques (and functions to make them)
-- [the Oh-So-Wonderful Haskell module system wins again...]
mkAlphaTyVarUnique,
mkPrimOpIdUnique,
mkTupleTyConUnique, mkTupleDataConUnique,
mkCTupleTyConUnique,
mkPreludeMiscIdUnique, mkPreludeDataConUnique,
mkPreludeTyConUnique, mkPreludeClassUnique,
mkPArrDataConUnique,
mkVarOccUnique, mkDataOccUnique, mkTvOccUnique, mkTcOccUnique,
mkRegSingleUnique, mkRegPairUnique, mkRegClassUnique, mkRegSubUnique,
mkCostCentreUnique,
mkBuiltinUnique,
mkPseudoUniqueD,
mkPseudoUniqueE,
mkPseudoUniqueH
) where
#include "HsVersions.h"
import BasicTypes
import FastString
import Outputable
import Util
-- just for implementing a fast [0,61) -> Char function
import GHC.Exts (indexCharOffAddr#, Char(..), Int(..))
import Data.Char ( chr, ord )
import Data.Bits
{-
************************************************************************
* *
\subsection[Unique-type]{@Unique@ type and operations}
* *
************************************************************************
The @Chars@ are ``tag letters'' that identify the @UniqueSupply@.
Fast comparison is everything on @Uniques@:
-}
--why not newtype Int?
-- | The type of unique identifiers that are used in many places in GHC
-- for fast ordering and equality tests. You should generate these with
-- the functions from the 'UniqSupply' module
data Unique = MkUnique {-# UNPACK #-} !Int
{-
Now come the functions which construct uniques from their pieces, and vice versa.
The stuff about unique *supplies* is handled further down this module.
-}
unpkUnique :: Unique -> (Char, Int) -- The reverse
mkUniqueGrimily :: Int -> Unique -- A trap-door for UniqSupply
getKey :: Unique -> Int -- for Var
incrUnique :: Unique -> Unique
deriveUnique :: Unique -> Int -> Unique
newTagUnique :: Unique -> Char -> Unique
mkUniqueGrimily = MkUnique
{-# INLINE getKey #-}
getKey (MkUnique x) = x
incrUnique (MkUnique i) = MkUnique (i + 1)
-- deriveUnique uses an 'X' tag so that it won't clash with
-- any of the uniques produced any other way
deriveUnique (MkUnique i) delta = mkUnique 'X' (i + delta)
-- newTagUnique changes the "domain" of a unique to a different char
newTagUnique u c = mkUnique c i where (_,i) = unpkUnique u
-- pop the Char in the top 8 bits of the Unique(Supply)
-- No 64-bit bugs here, as long as we have at least 32 bits. --JSM
-- and as long as the Char fits in 8 bits, which we assume anyway!
mkUnique :: Char -> Int -> Unique -- Builds a unique from pieces
-- NOT EXPORTED, so that we can see all the Chars that
-- are used in this one module
mkUnique c i
= MkUnique (tag .|. bits)
where
tag = ord c `shiftL` 24
bits = i .&. 16777215 {-``0x00ffffff''-}
unpkUnique (MkUnique u)
= let
-- as long as the Char may have its eighth bit set, we
-- really do need the logical right-shift here!
tag = chr (u `shiftR` 24)
i = u .&. 16777215 {-``0x00ffffff''-}
in
(tag, i)
{-
************************************************************************
* *
\subsection[Uniquable-class]{The @Uniquable@ class}
* *
************************************************************************
-}
-- | Class of things that we can obtain a 'Unique' from
class Uniquable a where
getUnique :: a -> Unique
hasKey :: Uniquable a => a -> Unique -> Bool
x `hasKey` k = getUnique x == k
instance Uniquable FastString where
getUnique fs = mkUniqueGrimily (uniqueOfFS fs)
instance Uniquable Int where
getUnique i = mkUniqueGrimily i
{-
************************************************************************
* *
\subsection[Unique-instances]{Instance declarations for @Unique@}
* *
************************************************************************
And the whole point (besides uniqueness) is fast equality. We don't
use `deriving' because we want {\em precise} control of ordering
(equality on @Uniques@ is v common).
-}
eqUnique, ltUnique, leUnique :: Unique -> Unique -> Bool
eqUnique (MkUnique u1) (MkUnique u2) = u1 == u2
ltUnique (MkUnique u1) (MkUnique u2) = u1 < u2
leUnique (MkUnique u1) (MkUnique u2) = u1 <= u2
cmpUnique :: Unique -> Unique -> Ordering
cmpUnique (MkUnique u1) (MkUnique u2)
= if u1 == u2 then EQ else if u1 < u2 then LT else GT
instance Eq Unique where
a == b = eqUnique a b
a /= b = not (eqUnique a b)
instance Ord Unique where
a < b = ltUnique a b
a <= b = leUnique a b
a > b = not (leUnique a b)
a >= b = not (ltUnique a b)
compare a b = cmpUnique a b
-----------------
instance Uniquable Unique where
getUnique u = u
-- We do sometimes make strings with @Uniques@ in them:
showUnique :: Unique -> String
showUnique uniq
= case unpkUnique uniq of
(tag, u) -> finish_show tag u (iToBase62 u)
finish_show :: Char -> Int -> String -> String
finish_show 't' u _pp_u | u < 26
= -- Special case to make v common tyvars, t1, t2, ...
-- come out as a, b, ... (shorter, easier to read)
[chr (ord 'a' + u)]
finish_show tag _ pp_u = tag : pp_u
pprUnique :: Unique -> SDoc
pprUnique u = text (showUnique u)
instance Outputable Unique where
ppr = pprUnique
instance Show Unique where
show uniq = showUnique uniq
{-
************************************************************************
* *
\subsection[Utils-base62]{Base-62 numbers}
* *
************************************************************************
A character-stingy way to read/write numbers (notably Uniques).
The ``62-its'' are \tr{[0-9a-zA-Z]}. We don't handle negative Ints.
Code stolen from Lennart.
-}
iToBase62 :: Int -> String
iToBase62 n_
= ASSERT(n_ >= 0) go n_ ""
where
go n cs | n < 62
= let !c = chooseChar62 n in c : cs
| otherwise
= go q (c : cs) where (q, r) = quotRem n 62
!c = chooseChar62 r
chooseChar62 :: Int -> Char
{-# INLINE chooseChar62 #-}
chooseChar62 (I# n) = C# (indexCharOffAddr# chars62 n)
chars62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"#
{-
************************************************************************
* *
\subsection[Uniques-prelude]{@Uniques@ for wired-in Prelude things}
* *
************************************************************************
Allocation of unique supply characters:
v,t,u : for renumbering value-, type- and usage- vars.
B: builtin
C-E: pseudo uniques (used in native-code generator)
X: uniques derived by deriveUnique
_: unifiable tyvars (above)
0-9: prelude things below
(no numbers left any more..)
:: (prelude) parallel array data constructors
other a-z: lower case chars for unique supplies. Used so far:
d desugarer
f AbsC flattener
g SimplStg
n Native codegen
r Hsc name cache
s simplifier
-}
mkAlphaTyVarUnique :: Int -> Unique
mkPreludeClassUnique :: Int -> Unique
mkPreludeTyConUnique :: Int -> Unique
mkTupleTyConUnique :: Boxity -> Arity -> Unique
mkCTupleTyConUnique :: Arity -> Unique
mkPreludeDataConUnique :: Arity -> Unique
mkTupleDataConUnique :: Boxity -> Arity -> Unique
mkPrimOpIdUnique :: Int -> Unique
mkPreludeMiscIdUnique :: Int -> Unique
mkPArrDataConUnique :: Int -> Unique
mkAlphaTyVarUnique i = mkUnique '1' i
mkPreludeClassUnique i = mkUnique '2' i
-- Prelude type constructors occupy *three* slots.
-- The first is for the tycon itself; the latter two
-- are for the generic to/from Ids. See TysWiredIn.mk_tc_gen_info.
mkPreludeTyConUnique i = mkUnique '3' (3*i)
mkTupleTyConUnique Boxed a = mkUnique '4' (3*a)
mkTupleTyConUnique Unboxed a = mkUnique '5' (3*a)
mkCTupleTyConUnique a = mkUnique 'k' (3*a)
-- Data constructor keys occupy *two* slots. The first is used for the
-- data constructor itself and its wrapper function (the function that
-- evaluates arguments as necessary and calls the worker). The second is
-- used for the worker function (the function that builds the constructor
-- representation).
mkPreludeDataConUnique i = mkUnique '6' (2*i) -- Must be alphabetic
mkTupleDataConUnique Boxed a = mkUnique '7' (2*a) -- ditto (*may* be used in C labels)
mkTupleDataConUnique Unboxed a = mkUnique '8' (2*a)
mkPrimOpIdUnique op = mkUnique '9' op
mkPreludeMiscIdUnique i = mkUnique '0' i
-- No numbers left anymore, so I pick something different for the character tag
mkPArrDataConUnique a = mkUnique ':' (2*a)
-- The "tyvar uniques" print specially nicely: a, b, c, etc.
-- See pprUnique for details
initTyVarUnique :: Unique
initTyVarUnique = mkUnique 't' 0
mkPseudoUniqueD, mkPseudoUniqueE, mkPseudoUniqueH,
mkBuiltinUnique :: Int -> Unique
mkBuiltinUnique i = mkUnique 'B' i
mkPseudoUniqueD i = mkUnique 'D' i -- used in NCG for getUnique on RealRegs
mkPseudoUniqueE i = mkUnique 'E' i -- used in NCG spiller to create spill VirtualRegs
mkPseudoUniqueH i = mkUnique 'H' i -- used in NCG spiller to create spill VirtualRegs
mkRegSingleUnique, mkRegPairUnique, mkRegSubUnique, mkRegClassUnique :: Int -> Unique
mkRegSingleUnique = mkUnique 'R'
mkRegSubUnique = mkUnique 'S'
mkRegPairUnique = mkUnique 'P'
mkRegClassUnique = mkUnique 'L'
mkCostCentreUnique :: Int -> Unique
mkCostCentreUnique = mkUnique 'C'
mkVarOccUnique, mkDataOccUnique, mkTvOccUnique, mkTcOccUnique :: FastString -> Unique
-- See Note [The Unique of an OccName] in OccName
mkVarOccUnique fs = mkUnique 'i' (uniqueOfFS fs)
mkDataOccUnique fs = mkUnique 'd' (uniqueOfFS fs)
mkTvOccUnique fs = mkUnique 'v' (uniqueOfFS fs)
mkTcOccUnique fs = mkUnique 'c' (uniqueOfFS fs)
| acowley/ghc | compiler/basicTypes/Unique.hs | bsd-3-clause | 11,873 | 0 | 12 | 3,227 | 1,840 | 994 | 846 | 150 | 3 |
{-# LANGUAGE OverloadedLabels, DataKinds, FlexibleContexts #-}
import GHC.OverloadedLabels
-- No instance for (OverloadedLabel "x" t0)
a = #x
-- No instance for (OverloadedLabel "x" (t0 -> t1), OverloadedLabel "y" t0)
b = #x #y
-- Could not deduce (OverloadedLabel "y" t) from (OverloadedLabel "x" t)
c :: IsLabel "x" t => t
c = #y
main = return ()
| olsner/ghc | testsuite/tests/overloadedrecflds/should_fail/overloadedlabelsfail01.hs | bsd-3-clause | 354 | 0 | 6 | 64 | 52 | 29 | 23 | 7 | 1 |
{-# OPTIONS_HADDOCK hide #-}
module Ticket61_Hidden where
class C a where
-- | A comment about f
f :: a
| DavidAlphaFox/ghc | utils/haddock/html-test/src/Ticket61_Hidden.hs | bsd-3-clause | 110 | 0 | 6 | 26 | 20 | 12 | 8 | 4 | 0 |
{-# LANGUAGE DuplicateRecordFields #-}
module OverloadedRecFldsRun02_A (U(..), V(MkV, x), Unused(..), u) where
data U = MkU { x :: Bool, y :: Bool }
data V = MkV { x :: Int }
data Unused = MkUnused { unused :: Bool }
u = MkU False True
| shlevy/ghc | testsuite/tests/overloadedrecflds/should_run/OverloadedRecFldsRun02_A.hs | bsd-3-clause | 239 | 0 | 8 | 50 | 94 | 60 | 34 | 9 | 1 |
{-# htermination min :: Char -> Char -> Char #-}
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Prelude_min_3.hs | mit | 49 | 0 | 2 | 10 | 3 | 2 | 1 | 1 | 0 |
{-# LANGUAGE TupleSections #-}
-- | Parser for .prof files generated by GHC.
module ProfFile
( Time(..)
, Line(..)
, lIndividualTime
, lInheritedTime
, lIndividualAlloc
, lInheritedAlloc
, parse
, processLines
, findStart
) where
import Control.Arrow (second, left)
import Data.Char (isSpace)
import Data.List (isPrefixOf)
import Text.Read (readEither)
import Control.Monad (unless)
import Control.Applicative
import Prelude -- Quash AMP related warnings in GHC>=7.10
data Time = Time
{ tIndividual :: Double
, tInherited :: Double
} deriving (Show, Eq)
data Line = Line
{ lCostCentre :: String
, lModule :: String
, lNumber :: Int
, lEntries :: Int
, lTime :: Time
, lAlloc :: Time
, lTicks :: Int
, lBytes :: Int
, lChildren :: [Line]
} deriving (Show, Eq)
lIndividualTime :: Line -> Double
lIndividualTime = tIndividual . lTime
lInheritedTime :: Line -> Double
lInheritedTime = tInherited . lTime
lIndividualAlloc :: Line -> Double
lIndividualAlloc = tIndividual . lAlloc
lInheritedAlloc :: Line -> Double
lInheritedAlloc = tInherited . lAlloc
data ProfFormat = NoSources | IncludesSources
-- | Returns a function accepting the children and returning a fully
-- formed 'Line'.
parseLine :: ProfFormat -> String -> Either String ([Line] -> Line)
parseLine format s =
case format of
NoSources ->
case words s of
(costCentre:module_:no:entries:indTime:indAlloc:inhTime:inhAlloc:other) ->
parse' costCentre module_ no entries indTime indAlloc inhTime inhAlloc other
_ -> Left $ "Malformed .prof file line:\n" ++ s
IncludesSources ->
case words s of
(costCentre:module_:rest) | (no:entries:indTime:indAlloc:inhTime:inhAlloc:other) <- dropSRC rest ->
parse' costCentre module_ no entries indTime indAlloc inhTime inhAlloc other
_ -> Left $ "Malformed .prof file line:\n" ++ s
where
-- XXX: The SRC field can contain arbitrary characters (from the
-- subdirectory name)!
--
-- As a heuristic, assume SRC spans until the last word which:
--
-- * Ends with '>'
-- (for special values emitted by GHC like "<no location info>")
--
-- or
--
-- * Contains a colon eventually followed by another colon or a minus
-- (to identify the source span, e.g. ":69:55-64" or ":(36,1)-(38,30)",
-- or maybe for a single character ":30:3")
--
-- If there is no such word, assume SRC is just one word.
--
-- This heuristic will break if:
--
-- * In the future, columns to the right of SRC can match the above
-- condition (currently, they're all numeric)
--
-- or
--
-- * GHC doesn't add a source span formatted as assumed above, and the
-- SRC contains spaces
--
-- The implementation is not very efficient, but I suppose this is not
-- performance-critical.
dropSRC (_:rest) = reverse . takeWhile (not . isPossibleEndOfSRC) . reverse $ rest
dropSRC [] = []
isPossibleEndOfSRC w = last w == '>'
|| case break (==':') w of
(_, _:rest) -> any (`elem` ":-") rest
_ -> False
parse' costCentre module_ no entries indTime indAlloc inhTime inhAlloc other = do
pNo <- readEither' no
pEntries <- readEither' entries
pTime <- Time <$> readEither' indTime <*> readEither' inhTime
pAlloc <- Time <$> readEither' indAlloc <*> readEither' inhAlloc
(pTicks, pBytes) <-
case other of
(ticks:bytes:_) -> (,) <$> readEither' ticks <*> readEither' bytes
_ -> pure (0, 0)
return $ Line costCentre module_ pNo pEntries pTime pAlloc pTicks pBytes
readEither' str = left (("Could not parse value "++show str++": ")++)
(readEither str)
type LineNumber = Int
processLines :: ProfFormat -> [String] -> LineNumber -> Either String [Line]
processLines format lines0 lineNumber0 = do
((ss,_), lines') <- go 0 lines0 lineNumber0
unless (null ss) $
error "processLines: the impossible happened, not all strings were consumed."
return lines'
where
go :: Int -> [String] -> LineNumber -> Either String (([String], LineNumber), [Line])
go _depth [] lineNumber = do
return (([], lineNumber), [])
go depth0 (line : lines') lineNumber = do
let (spaces, rest) = break (not . isSpace) line
let depth = length spaces
if depth < depth0
then return ((line : lines', lineNumber), [])
else do
parsedLine <- left (("Parse error in line "++show lineNumber++": ")++) $
parseLine format rest
((lines'', lineNumber''), children) <- go (depth + 1) lines' (lineNumber + 1)
second (parsedLine children :) <$> go depth lines'' lineNumber''
firstLineNoSources :: [String]
firstLineNoSources = ["COST", "CENTRE", "MODULE", "no.", "entries", "%time", "%alloc", "%time", "%alloc"]
-- Since GHC 8.0.2 the cost centres include the src location
firstLineIncludesSources :: [String]
firstLineIncludesSources = ["COST", "CENTRE", "MODULE", "SRC", "no.", "entries", "%time", "%alloc", "%time", "%alloc"]
findStart :: [String] -> LineNumber -> Either String (ProfFormat, [String], [String], LineNumber)
findStart [] _ = Left "Malformed .prof file: couldn't find start line"
findStart (line : _empty : lines') lineNumber | (firstLineNoSources `isPrefixOf` words line) = return (NoSources, words line, lines', lineNumber + 2)
| (firstLineIncludesSources `isPrefixOf` words line) = return (IncludesSources, words line, lines', lineNumber + 2)
findStart (_line : lines') lineNumber = findStart lines' (lineNumber + 1)
parse :: String -> Either String ([String], [Line])
parse s = do
(format, names, ss, lineNumber) <- findStart (lines s) 1
return . (names,) =<< processLines format ss lineNumber
| fpco/ghc-prof-flamegraph | ProfFile.hs | mit | 6,019 | 0 | 21 | 1,535 | 1,618 | 885 | 733 | 106 | 7 |
module Monoid8 where
import Data.Monoid
import Test.QuickCheck
import SemiGroupAssociativeLaw
import Test.HUnit
import MonoidLaws
import Text.Show.Functions
import ArbitrarySum
newtype Mem s a = Mem { runMem :: s -> (a,s) } deriving Show
mappendMem :: Monoid a => Mem s a -> Mem s a -> Mem s a
mappendMem f1 f2 =
Mem $ combiningFunc
where
combiningFunc s =
let
(a1, s1) = (runMem f1) s
(a2, s2) = (runMem f2) s1
in
(a1 `mappend` a2, s2)
instance Monoid a => Monoid (Mem s a) where
mempty = Mem $ \n -> (mempty, n)
mappend = mappendMem
{-
Iceland_jack: arbitrary :: (CoArbitrary s, Arbitrary s, Arbitrary a) => Gen (s -> (a, s))
Iceland_jack: You can already generate functions like that
Iceland_jack: So you can just do
Iceland_jack: Mem <$> arbitrary
Iceland_jack: :: (Arbitrary a, Arbitrary s, CoArbitrary s) => Gen (Mem s a)
Iceland_jack: Where 's' appears as an "input" (CoArbitrary, contravariant position) as well as an "output" (Arbitrary, covariant position)
Iceland_jack: that's why we get (Arbitrary s, CoArbitrary s)
-}
instance (CoArbitrary s, Arbitrary s, Arbitrary a) => Arbitrary (Mem s a) where
arbitrary = Mem <$> arbitrary
f' = Mem $ \s -> ("hi", s + 1)
test1 = TestCase (assertEqual "" (runMem (f' <> mempty) $ 0) ("hi", 1))
test2 = TestCase (assertEqual "" (runMem (mempty <> f') 0) ("hi", 1))
test3 = TestCase (assertEqual "" (runMem mempty 0 :: (String, Int)) ("", 0))
test4 = TestCase (assertEqual "" (runMem (f' <> mempty) 0) (runMem f' 0))
test5 = TestCase (assertEqual "" (runMem (mempty <> f') 0) (runMem f' 0))
-- can't use semigroupAssoc as Eq isn't defined for functions...
-- instead use QuickCheck to generate a random value which is applied
-- to both combined functions producing a result which can be tested
-- for equality
memAssoc :: (Eq s, Eq a, Monoid a) => s -> Mem s a -> Mem s a -> Mem s a -> Bool
memAssoc v a b c = (runMem (a <> (b <> c)) $ v) == (runMem ((a <> b) <> c) $ v)
type MemAssoc = Int -> Mem Int (Sum Int) -> Mem Int (Sum Int) -> Mem Int (Sum Int) -> Bool
memLeftIdentity :: (Eq s, Eq a, Monoid a) => s -> Mem s a -> Bool
memLeftIdentity x a = (runMem (mempty <> a) $ x) == (runMem a $ x)
memRightIdentity :: (Eq s, Eq a, Monoid a) => s -> Mem s a -> Bool
memRightIdentity x a = (runMem (a <> mempty) $ x) == (runMem a $ x)
main :: IO ()
main = do
quickCheck (memAssoc :: MemAssoc)
quickCheck (memLeftIdentity :: Int -> Mem Int (Sum Int) -> Bool)
quickCheck (memRightIdentity :: Int -> Mem Int (Sum Int) -> Bool)
counts <- runTestTT (TestList [test1, test2, test3, test4, test5])
print counts | NickAger/LearningHaskell | HaskellProgrammingFromFirstPrinciples/Chapter15.hsproj/Monoid8.hs | mit | 2,666 | 0 | 13 | 593 | 971 | 513 | 458 | 42 | 1 |
-- Copyright (c) 2016-present, SoundCloud Ltd.
-- All rights reserved.
--
-- This source code is distributed under the terms of a MIT license,
-- found in the LICENSE file.
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
module Kubernetes.Model.V1.Binding
( Binding (..)
, kind
, apiVersion
, metadata
, target
, mkBinding
) where
import Control.Lens.TH (makeLenses)
import Data.Aeson.TH (defaultOptions,
deriveJSON,
fieldLabelModifier)
import Data.Text (Text)
import GHC.Generics (Generic)
import Kubernetes.Model.V1.ObjectMeta (ObjectMeta)
import Kubernetes.Model.V1.ObjectReference (ObjectReference)
import Prelude hiding (drop, error, max,
min)
import qualified Prelude as P
import Test.QuickCheck (Arbitrary, arbitrary)
import Test.QuickCheck.Instances ()
-- | Binding ties one object to another. For example, a pod is bound to a node by a scheduler.
data Binding = Binding
{ _kind :: !(Maybe Text)
, _apiVersion :: !(Maybe Text)
, _metadata :: !(Maybe ObjectMeta)
, _target :: !(ObjectReference)
} deriving (Show, Eq, Generic)
makeLenses ''Binding
$(deriveJSON defaultOptions{fieldLabelModifier = (\n -> if n == "_type_" then "type" else P.drop 1 n)} ''Binding)
instance Arbitrary Binding where
arbitrary = Binding <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
-- | Use this method to build a Binding
mkBinding :: ObjectReference -> Binding
mkBinding xtargetx = Binding Nothing Nothing Nothing xtargetx
| soundcloud/haskell-kubernetes | lib/Kubernetes/Model/V1/Binding.hs | mit | 2,009 | 0 | 14 | 731 | 345 | 206 | 139 | 43 | 1 |
--------------------------------------------------------------------
-- |
-- Copyright : © Oleg Grenrus 2014
-- License : MIT
-- Maintainer: Oleg Grenrus <[email protected]>
-- Stability : experimental
-- Portability: non-portable
--
-- This module re-exports tree-based implementation.
--------------------------------------------------------------------
module Data.Algebra.Boolean.NNF (
module Data.Algebra.Boolean.NNF.Tree
) where
import Data.Algebra.Boolean.NNF.Tree
| phadej/boolean-normal-forms | src/Data/Algebra/Boolean/NNF.hs | mit | 484 | 0 | 5 | 52 | 37 | 30 | 7 | 3 | 0 |
{-# language NoImplicitPrelude, DoAndIfThenElse, OverloadedStrings, ExtendedDefaultRules #-}
module IHaskell.Publish (publishResult) where
import IHaskellPrelude
import qualified Data.Text as T
import qualified Data.Text.Encoding as E
import IHaskell.Display
import IHaskell.Types
import IHaskell.CSS (ihaskellCSS)
-- | Publish evaluation results, ignore any CommMsgs. This function can be used to create a function
-- of type (EvaluationResult -> IO ()), which can be used to publish results to the frontend. The
-- resultant function shares some state between different calls by storing it inside the MVars
-- passed while creating it using this function. Pager output is accumulated in the MVar passed for
-- this purpose if a pager is being used (indicated by an argument), and sent to the frontend
-- otherwise.
publishResult :: (Message -> IO ()) -- ^ A function to send messages
-> MessageHeader -- ^ Message header to use for reply
-> MVar [Display] -- ^ A MVar to use for displays
-> MVar Bool -- ^ A mutable boolean to decide whether the output need to be cleared and
-- redrawn
-> MVar [DisplayData] -- ^ A MVar to use for storing pager output
-> Bool -- ^ Whether to use the pager
-> EvaluationResult -- ^ The evaluation result
-> IO ()
publishResult send replyHeader displayed updateNeeded pagerOutput usePager result = do
let final =
case result of
IntermediateResult{} -> False
FinalResult{} -> True
outs = outputs result
-- If necessary, clear all previous output and redraw.
clear <- readMVar updateNeeded
when clear $ do
clearOutput
disps <- readMVar displayed
mapM_ sendOutput $ reverse disps
-- Draw this message.
sendOutput outs
-- If this is the final message, add it to the list of completed messages. If it isn't, make sure we
-- clear it later by marking update needed as true.
modifyMVar_ updateNeeded (const $ return $ not final)
when final $ do
modifyMVar_ displayed (return . (outs :))
-- If this has some pager output, store it for later.
let pager = pagerOut result
unless (null pager) $
if usePager
then modifyMVar_ pagerOutput (return . (++ pager))
else sendOutput $ Display pager
where
clearOutput = do
header <- dupHeader replyHeader ClearOutputMessage
send $ ClearOutput header True
sendOutput (ManyDisplay manyOuts) = mapM_ sendOutput manyOuts
sendOutput (Display outs) = do
header <- dupHeader replyHeader DisplayDataMessage
send $ PublishDisplayData header "haskell" $ map (convertSvgToHtml . prependCss) outs
convertSvgToHtml (DisplayData MimeSvg svg) = html $ makeSvgImg $ base64 $ E.encodeUtf8 svg
convertSvgToHtml x = x
makeSvgImg :: Base64 -> String
makeSvgImg base64data = T.unpack $ "<img src=\"data:image/svg+xml;base64," <>
base64data <>
"\"/>"
prependCss (DisplayData MimeHtml html) =
DisplayData MimeHtml $ mconcat ["<style>", T.pack ihaskellCSS, "</style>", html]
prependCss x = x
| sumitsahrawat/IHaskell | src/IHaskell/Publish.hs | mit | 3,310 | 0 | 15 | 916 | 586 | 299 | 287 | 52 | 6 |
module Interpreter where
-- union = union (|||), delete = remove (---)
import Parsing
import Data.List
-- Free variables of a term (variables that are not bound by a lambda)
freeVariables :: Term -> [Var]
freeVariables (Constant _) = []
freeVariables (Variable v) = [v]
freeVariables (Application (a, b)) = (freeVariables a) `union` (freeVariables b)
freeVariables (Lambda (x, b)) = filter (\z -> z == x) (freeVariables b)
-- Checks if a variable is free in a term
isFreeVariableOf :: Var -> Term -> Bool
isFreeVariableOf v t = v `elem` (freeVariables t)
-- Create a new variable name, that is not free in a term
newVar :: Term -> Var
newVar t = newVar' t "new-var"
newVar' :: Term -> Var -> Var
newVar' t nVar = if isFreeVariableOf nVar t
then newVar' t (nVar++"1")
else nVar
-- substitute a variable in a term with another term
substitution :: Term -> Var -> Term -> Term
substitution (Variable term1) var term2
| term1 == var = term2
substitution (Application (t1,t2)) var term2 =
Application (substitution t1 var term2, substitution t2 var term2)
substitution (Lambda (x,t)) var term2
| x /= var && not (isFreeVariableOf x term2) = Lambda (x, substitution t var term2)
| x /= var = substitution (substitution t x (Variable (newVar (Application (t, term2))))) var term2
substitution term1 _ _ = term1
-- apply parameters to a function
betaConversion :: Term -> Term
betaConversion (Application (Lambda (x, a), b)) = substitution a x b
betaConversion t = t
-- pattern matching here probably buggy
etaConversion :: Term -> Term
etaConversion (Lambda (x, Application (t, Variable x2)))
| x == x2 = etaConversion' x t (Lambda (x, Application (t, Variable x2)))
etaConversion te = te
etaConversion' :: Var -> Term -> Term -> Term
etaConversion' _ (Constant (Num t)) _ = Constant (Num t)
etaConversion' x t te = if (isFreeVariableOf x t) then te else t
-- give the constants some meaning
deltaConversion :: Term -> Term
deltaConversion (Application (Constant Succ, Constant (Num n))) = Constant (Num (n + 1))
deltaConversion (Application (Application (Constant Add, Constant (Num n)), Constant (Num m))) = Constant (Num (n + m))
deltaConversion t = t
| JorisM/HLambdaCalculus | Interpreter.hs | mit | 2,187 | 6 | 15 | 402 | 832 | 433 | 399 | 39 | 2 |
-- ch4.hs
module Ch4 where
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome xs = (reverse xs) == xs
myAbs :: Integer -> Integer
myAbs x = if x >= 0 then x else (-x)
f :: (a, b) -> (c, d) -> ((b, d), (a, c))
f x y = ((snd x, snd y), (fst x, fst y)) | candu/haskellbook | ch4/ch4.hs | mit | 252 | 0 | 8 | 62 | 161 | 92 | 69 | 7 | 2 |
module Language.Asol.Expression where
data Instruction = Push Integer
| Top Int
| Pop
| Print
| Read
| Emit
| Mul
| Sub
| Add
| Div
| Mod
| Pow
| Fact
| Swap
| Dup
| ShowStack
deriving (Eq,Show)
| kmein/asol | Language/Asol/Expression.hs | mit | 468 | 0 | 6 | 314 | 74 | 47 | 27 | 18 | 0 |
-- Core stuff: Tic Tac Toe struct, win conditions
module Core where
data Place = X | O | E
deriving (Show, Eq)
-- X, O or Empty
data Player = PX | PO | N
deriving (Show, Eq)
-- N is to be used only for a full board where no one has won
getPlace :: Player -> Place
getPlace player = case player of
PX -> X
PO -> O
N -> E
switchPlayer :: Player -> Player
switchPlayer player = case player of
PX -> PO
PO -> PX
N -> N
data Row = Row {
left :: Place,
mid :: Place,
right :: Place
} deriving Eq
instance Show Row where
show (Row l m r) = (show l) ++ " " ++ (show m) ++ " " ++ (show r)
data Board = Board {
top :: Row,
middle :: Row,
bottom :: Row
} deriving Eq
instance Show Board where
show (Board t m b) = (show t) ++ "\n\n" ++ (show m) ++ "\n\n" ++ (show b) ++ "\n"
data Diagonal = LMR | RML deriving (Show, Eq) -- Left-middle-right or Right-middle-left, from the top down
emptyBoard :: Board
emptyBoard = Board (Row E E E) (Row E E E) (Row E E E)
getByPosition :: Board -> (Int, Int) -> Place
getByPosition (Board t m b) (x, y) = selector (case y of
1 -> t
2 -> m
_ -> b)
where
selector = case x of
1 -> left
2 -> mid
3 -> right
setByPosition :: Board -> (Int, Int) -> Place -> Board
setByPosition (Board t m b) (x, y) place = Board t' m' b'
where
substitute (Row l m r) x = Row
(if x == 1 then place else l)
(if x == 2 then place else m)
(if x == 3 then place else r)
t' = if y == 1 then substitute t x else t
m' = if y == 2 then substitute m x else m
b' = if y == 3 then substitute b x else b
placeIsFull :: Place -> Bool
placeIsFull E = False
placeIsFull _ = True
rowIsFull :: Row -> Bool
rowIsFull (Row l m r) = placeIsFull l && placeIsFull m && placeIsFull r
boardIsFull :: Board -> Bool
boardIsFull (Board t m b) = rowIsFull t && rowIsFull m && rowIsFull b
getDiag :: Board -> Diagonal -> Row
getDiag board LMR = Row (getByPosition board (1, 1)) (getByPosition board (2, 2)) (getByPosition board (3, 3))
getDiag board RML = Row (getByPosition board (3, 1)) (getByPosition board (2, 2)) (getByPosition board (1, 3))
checkPosInt :: Place -> Place -> Int
checkPosInt place1 place2 = if place1 == place2 then 1 else 0
countPos :: Row -> Player -> Int
countPos row player = sum [ checkPosInt p $ getPlace player | p <- [ left row, mid row, right row ] ]
findDiag :: Board -> Place -> Bool
findDiag (Board t m b) place =
(mid m == place) &&
(((left t == place) && (right b == place)) ||
((right t == place) && (left b == place)))
findRow :: Board -> Place -> Bool
findRow (Board t m b) place = checkRow t || checkRow m || checkRow b
where
checkRow (Row l m r) = (l == place) && (m == place) && (r == place)
findColumn :: Board -> Place -> Bool
findColumn (Board t m b) place =
((left t == place) && (left m == place) && (left b == place)) ||
((mid t == place) && (mid m == place) && (mid b == place)) ||
((right t == place) && (right m == place) && (right b == place))
findPath :: Board -> Player -> Bool
findPath board player = (findDiag board p) || (findRow board p) || (findColumn board p)
where
p = getPlace player
determineWin :: Board -> Maybe Player -- Just Player if won or full, Nothing if no one has won and there are free spots
determineWin board
| findPath board PX = Just PX
| findPath board PO = Just PO
| boardIsFull board = Just N
| otherwise = Nothing
| quantum-dan/tictactoe-ai | Core.hs | mit | 3,579 | 0 | 12 | 1,013 | 1,542 | 806 | 736 | 86 | 7 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ViewPatterns #-}
module Commands.TH.Data where
import Commands.Grammar
import Data.List.NonEmpty (toList)
import Data.Functor
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
-- |
-- given the input 'Production':
--
-- > Production ''Command [
-- > Variant ''ReplaceWith [Part "replace", Hole ''Phrase, Part "with", Hole ''Phrase],
-- > Variant ''Click [Hole ''Times, Hole ''Button, Part "click"],
-- > Variant ''Undo [Part "undo"]]
--
-- 'buildDataD' builds a @data@ declaration:
--
-- > data Command
-- > = ReplaceWith Phrase Phrase
-- > | Click Times Button
-- > | Undo
-- > deriving (Show,Eq)
--
-- i.e. ignore 'Terminal's, keep 'NonTerminal's
--
buildDataD :: Production -> Dec
buildDataD (Production lhs (toList -> rhs)) = DataD context typename parameters constructors derived
where
context = []
NonTerminal typename = lhs
parameters = []
constructors = buildConstructorC <$> rhs
derived = [''Show, ''Eq]
-- |
-- given the input 'Variant':
--
-- > Variant ''ReplaceWith [Part "replace", Hole ''Phrase, Part "with", Hole ''Phrase],
--
-- 'buildConstructorC' builds the constructor "declaration":
--
-- > ReplaceWith Phrase Phrase
--
buildConstructorC :: Variant -> Con
buildConstructorC (Variant constructor (toList -> symbols)) = NormalC constructor arguments
where
arguments = concatMap buildArgument symbols
buildArgument :: Symbol -> [StrictType]
buildArgument (Part {}) = []
buildArgument (Hole (NonTerminal name)) = [(NotStrict, ConT name)]
| sboosali/Haskell-DragonNaturallySpeaking | sources/Commands/TH/Data.hs | mit | 1,628 | 0 | 11 | 331 | 272 | 163 | 109 | 21 | 2 |
{-------------------------------------------------------------------------------
Consider the consecutive primes p₁ = 19 and p₂ = 23. It can be verified that 1219 is the smallest number such that the last digits are formed by p₁ whilst also being divisible by p₂.
In fact, with the exception of p₁ = 3 and p₂ = 5, for every pair of consecutive primes, p₂ > p₁, there exist values of n for which the last digits are formed by p₁ and n is divisible by p₂. Let S be the smallest of these values of n.
Find ∑ S for every pair of consecutive primes with 5 ≤ p₁ ≤ 1000000.
-------------------------------------------------------------------------------}
import qualified Data.Numbers.Primes as Primes
import qualified Data.Digits as Digits
unDigits = Digits.unDigits 10
from0to9 = [0..9]
-- Given m and e, build the smallest number S such that m|S and S ends by e.
genS :: Int -> Int -> Int
genS m e = (m *) $ minimum $ recGenS e 0 [] []
where
recGenS :: Int -> Int -> [Int] -> [Int] -> [Int]
recGenS 0 _ digits acc = unDigits digits : acc
recGenS end rest digits acc =
concat $ map (\(d, r) -> recGenS end' r (d:digits) acc) ds
where
(end', end'') = quotRem end 10
ds = [(d, r') | d <- from0to9
, let (r', r0') = quotRem (m * d + rest) 10
, r0' == end'']
-- return ∑ S for every pair of consecutive primes with 5 ≤ p₁ ≤ bound
euler bound =
sum $ map (\(p1, p2) -> genS p2 p1)
$ takeWhile (\(p1, p2) -> p1 <= bound)
$ dropWhile (\(p1, p2) -> p1 < 5)
$ zip Primes.primes $ tail Primes.primes
main = do
putStr "Smallest number ending by 19 multiple of 23: "
putStrLn $ show $ genS 23 19
putStrLn $ "Euler 134: " ++ (show $ euler 1000000) | dpieroux/euler | 0134.hs | mit | 1,797 | 0 | 17 | 443 | 427 | 228 | 199 | 23 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
module WS.App where
import Control.Applicative ((<$>), (<*>))
import Control.Exception (Exception)
import Control.Monad.Catch (MonadThrow, MonadCatch, throwM, catch)
import Control.Monad.Trans.Class (lift)
import qualified Control.Monad.Trans.Either as E
import qualified Data.ByteString.Char8 as BS
import Data.Text (Text, pack)
import Data.Time (getCurrentTimeZone, getCurrentTime, utcToLocalTime, LocalTime)
import Data.Typeable (Typeable)
import Database.Relational.Query
import Servant
import WS.Cache as Cache
import WS.DB as DB
import WS.Mail as Mail
import qualified WS.Types as User
import WS.Types (User, user, tableOfUser, InsertUser(..), piUser, RegForm(..), LoginForm(..))
type API = "register" :> ReqBody '[JSON] RegForm :> Post '[JSON] User
:<|> "login" :> ReqBody '[JSON] LoginForm :> Post '[] ()
:<|> "users" :> Capture "userId" Int :> Get '[JSON] User
api :: Proxy API
api = Proxy
server :: Server API
server = registerH
:<|> loginH
:<|> getUserH
where
registerH f = lift (register f) `catch` errorH
loginH f = lift (login f) `catch` errorH
getUserH i = lift (getUser i) `catch` errorH
-- errorH :: Monad m => AppException -> E.EitherT ServantErr m a
errorH NotFound = E.left err404
-- handlers
adminAddress :: Text
adminAddress = "[email protected]"
data AppException = NotFound deriving (Show, Typeable)
instance Exception AppException
class (MonadCatch m, MonadMail m, MonadCache m, MonadDB m) => App m where
getCurrentLocalTime :: m LocalTime
instance App IO where
getCurrentLocalTime = utcToLocalTime <$> getCurrentTimeZone <*> getCurrentTime
register :: App m => RegForm -> m User
register form = do
lt <- getCurrentLocalTime
_ <- insertUser' (regName form) (regEmailAddress form) lt
user' <- getUserByName (regName form)
sendMail
adminAddress
(User.emailAddress user')
"register"
(pack $ "registered at " ++ show lt)
return user'
login :: App m => LoginForm -> m ()
login form = do
lt <- getCurrentLocalTime
let name' = loginName form
_ <- updateUser' name' lt
user' <- getUserByName name'
sendMail
adminAddress
(User.emailAddress user')
"login"
(pack $ "logged-in at " ++ show lt)
getUser :: App m => Int -> m User
getUser userId = do
u <- getUserCache userId
case u of
Just u' -> return u'
Nothing -> do
u' <- getUserById userId
setUserCache u'
return u'
-- operations
getUserCache :: MonadCache m => Int -> m (Maybe User)
getUserCache pk = Cache.get (BS.pack . show $ pk)
setUserCache :: MonadCache m => User -> m ()
setUserCache u = Cache.set (BS.pack . show $ User.id u) u
insertUser' :: MonadDB m => Text -> Text -> LocalTime -> m Integer
insertUser' name addr time = insert (typedInsert tableOfUser piUser) ins
where
ins = InsertUser { insName = name
, insEmailAddress = addr
, insCreatedAt = time
, insLastLoggedinAt = time
}
updateUser' :: MonadDB m => Text -> LocalTime -> m Integer
updateUser' name time = update (typedUpdate tableOfUser target) ()
where
target = updateTarget $ \proj -> do
User.lastLoggedinAt' <-# value time
wheres $ proj ! User.name' .=. value name
getUserById :: (MonadThrow m, MonadDB m) => Int -> m User
getUserById pk = do
res <- select (relationalQuery rel) (fromIntegral pk)
if null res
then throwM NotFound
else return $ head res
where
rel = relation' . placeholder $ \ph -> do
u <- query user
wheres $ u ! User.id' .=. ph
return u
getUserByName :: (MonadThrow m, MonadDB m) => Text -> m User
getUserByName name = do
res <- select (relationalQuery rel) name
if null res
then throwM NotFound
else return $ head res
where
rel = relation' . placeholder $ \ph -> do
u <- query user
wheres $ u ! User.name' .=. ph
return u
| krdlab/haskell-webapp-testing-experimentation | src/WS/App.hs | mit | 4,212 | 0 | 15 | 1,058 | 1,380 | 712 | 668 | 109 | 2 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
class TooMany a where
tooMany :: a -> Bool
instance TooMany Int where
tooMany n = n > 42
{-
newtype Goats = Goats Int deriving Show
-}
-- with GeneralizedNewtypeDeriving, we can get this automatically:
newtype Goats = Goats Int deriving (Show, Num)
instance TooMany Goats where
tooMany (Goats n) = n > 43
{-
-- reuse the original TooMany Int instance we made above:
instance TooMany Goats where
tooMany (Goats n) = tooMany n
-}
-- exercises:
-- make a TooMany instance for (Int, String)
-- with newtype:
newtype Goats' = Goats' (Int, String) deriving Show
instance TooMany Goats' where
tooMany (Goats' (n, _)) = n > 43
-- with FlexibleInstances:
instance TooMany (Int, String) where
tooMany (n,_) = n > 43
-- Make a TooMany instance for (Int, Int), check sum
--instance TooMany (Int, Int) where
-- tooMany (x,y) = (x+y) > 43
-- make a TooMany instance for (Num a, TooMany a) => (a, a)
instance (Num a, TooMany a) => TooMany (a, a) where
tooMany (x, y) = tooMany (x+y)
| JustinUnger/haskell-book | ch11/learn.hs | mit | 1,105 | 0 | 9 | 241 | 231 | 131 | 100 | 16 | 0 |
{-# LANGUAGE BangPatterns, CPP, FlexibleContexts #-}
-- |
-- Module : Statistics.Correlation.Kendall
--
-- Fast O(NlogN) implementation of
-- <http://en.wikipedia.org/wiki/Kendall_tau_rank_correlation_coefficient Kendall's tau>.
--
-- This module implementes Kendall's tau form b which allows ties in the data.
-- This is the same formula used by other statistical packages, e.g., R, matlab.
--
-- $$\tau = \frac{n_c - n_d}{\sqrt{(n_0 - n_1)(n_0 - n_2)}}$$
--
-- where $n_0 = n(n-1)/2$, $n_1 = number of pairs tied for the first quantify$,
-- $n_2 = number of pairs tied for the second quantify$,
-- $n_c = number of concordant pairs$, $n_d = number of discordant pairs$.
module Statistics.Correlation.Kendall
( kendall
, kendallMatrix
-- * References
-- $references
) where
import Control.Monad.ST (ST, runST)
import Data.Bits (shiftR)
import Data.Function (on)
import Data.STRef
import qualified Data.Vector.Algorithms.Intro as I
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Generic.Mutable as GM
import qualified Data.Vector.Unboxed as U
import qualified Data.Matrix.Generic as MG
import qualified Data.Matrix.Symmetric as MS
import Statistics.Correlation.Internal
-- | /O(nlogn)/ Compute the Kendall's tau from a vector of paired data.
-- Return NaN when number of pairs <= 1.
kendall :: (Ord a, Ord b, G.Vector v (a, b)) => v (a, b) -> Double
kendall xy'
| G.length xy' <= 1 = 0/0
| otherwise = runST $ do
xy <- G.thaw xy'
let n = GM.length xy
n_dRef <- newSTRef 0
I.sort xy
tieX <- numOfTiesBy ((==) `on` fst) xy
tieXY <- numOfTiesBy (==) xy
tmp <- GM.new n
mergeSort (compare `on` snd) xy tmp n_dRef
tieY <- numOfTiesBy ((==) `on` snd) xy
n_d <- readSTRef n_dRef
let n_0 = (fromIntegral n * (fromIntegral n-1)) `shiftR` 1 :: Integer
n_c = n_0 - n_d - tieX - tieY + tieXY
return $ fromIntegral (n_c - n_d) /
(sqrt.fromIntegral) ((n_0 - tieX) * (n_0 - tieY))
{-# INLINE kendall #-}
kendallMatrix :: (Ord a, MG.Matrix m v a, G.Vector v (a,a))
=> m v a -> MS.SymMatrix U.Vector Double
kendallMatrix = correlationMatrix kendall
{-# INLINE kendallMatrix #-}
-- calculate number of tied pairs in a sorted vector
numOfTiesBy :: GM.MVector v a
=> (a -> a -> Bool) -> v s a -> ST s Integer
numOfTiesBy f xs = do count <- newSTRef (0::Integer)
loop count (1::Int) (0::Int)
readSTRef count
where
n = GM.length xs
loop c !acc !i | i >= n - 1 = modifySTRef' c (+ g acc)
| otherwise = do
x1 <- GM.unsafeRead xs i
x2 <- GM.unsafeRead xs (i+1)
if f x1 x2
then loop c (acc+1) (i+1)
else modifySTRef' c (+ g acc) >> loop c 1 (i+1)
g x = fromIntegral ((x * (x - 1)) `shiftR` 1)
{-# INLINE numOfTiesBy #-}
-- Implementation of Knight's merge sort (adapted from vector-algorithm). This
-- function is used to count the number of discordant pairs.
mergeSort :: GM.MVector v e
=> (e -> e -> Ordering)
-> v s e
-> v s e
-> STRef s Integer
-> ST s ()
mergeSort cmp src buf count = loop 0 (GM.length src - 1)
where
loop l u
| u == l = return ()
| u - l == 1 = do
eL <- GM.unsafeRead src l
eU <- GM.unsafeRead src u
case cmp eL eU of
GT -> do GM.unsafeWrite src l eU
GM.unsafeWrite src u eL
modifySTRef' count (+1)
_ -> return ()
| otherwise = do
let mid = (u + l) `shiftR` 1
loop l mid
loop mid u
merge cmp (GM.unsafeSlice l (u-l+1) src) buf (mid - l) count
{-# INLINE mergeSort #-}
merge :: GM.MVector v e
=> (e -> e -> Ordering)
-> v s e
-> v s e
-> Int
-> STRef s Integer
-> ST s ()
merge cmp src buf mid count = do GM.unsafeCopy tmp lower
eTmp <- GM.unsafeRead tmp 0
eUpp <- GM.unsafeRead upper 0
loop tmp 0 eTmp upper 0 eUpp 0
where
lower = GM.unsafeSlice 0 mid src
upper = GM.unsafeSlice mid (GM.length src - mid) src
tmp = GM.unsafeSlice 0 mid buf
wroteHigh low iLow eLow high iHigh iIns
| iHigh >= GM.length high =
GM.unsafeCopy (GM.unsafeSlice iIns (GM.length low - iLow) src)
(GM.unsafeSlice iLow (GM.length low - iLow) low)
| otherwise = do eHigh <- GM.unsafeRead high iHigh
loop low iLow eLow high iHigh eHigh iIns
wroteLow low iLow high iHigh eHigh iIns
| iLow >= GM.length low = return ()
| otherwise = do eLow <- GM.unsafeRead low iLow
loop low iLow eLow high iHigh eHigh iIns
loop !low !iLow !eLow !high !iHigh !eHigh !iIns = case cmp eHigh eLow of
LT -> do GM.unsafeWrite src iIns eHigh
modifySTRef' count (+ fromIntegral (GM.length low - iLow))
wroteHigh low iLow eLow high (iHigh+1) (iIns+1)
_ -> do GM.unsafeWrite src iIns eLow
wroteLow low (iLow+1) high iHigh eHigh (iIns+1)
{-# INLINE merge #-}
-- $references
--
-- * William R. Knight. (1966) A computer method for calculating Kendall's Tau
-- with ungrouped data. /Journal of the American Statistical Association/,
-- Vol. 61, No. 314, Part 1, pp. 436-439. <http://www.jstor.org/pss/2282833>
--
| kaizhang/statistics-correlation | Statistics/Correlation/Kendall.hs | mit | 5,569 | 0 | 18 | 1,731 | 1,746 | 881 | 865 | 107 | 2 |
module Hoton.Types
(
Number
) where
type Number = Double
| woufrous/hoton | src/Hoton/Types.hs | mit | 63 | 0 | 4 | 16 | 17 | 11 | 6 | 4 | 0 |
-- |
-- Module: Math.NumberTheory.Zeta.Hurwitz
-- Copyright: (c) 2018 Alexandre Rodrigues Baldé
-- Licence: MIT
-- Maintainer: Alexandre Rodrigues Baldé <[email protected]>
--
-- Hurwitz zeta function.
{-# LANGUAGE ScopedTypeVariables #-}
module Math.NumberTheory.Zeta.Hurwitz
( zetaHurwitz
) where
import Math.NumberTheory.Recurrences (bernoulli, factorial)
import Math.NumberTheory.Zeta.Utils (skipEvens, skipOdds)
-- | Values of Hurwitz zeta function evaluated at @ζ(s, a)@ for @s ∈ [0, 1 ..]@.
--
-- The algorithm used was based on the Euler-Maclaurin formula and was derived
-- from <http://fredrikj.net/thesis/thesis.pdf Fast and Rigorous Computation of Special Functions to High Precision>
-- by F. Johansson, chapter 4.8, formula 4.8.5.
-- The error for each value in this recurrence is given in formula 4.8.9 as an
-- indefinite integral, and in formula 4.8.12 as a closed form formula.
--
-- It is the __user's responsibility__ to provide an appropriate precision for
-- the type chosen.
--
-- For instance, when using @Double@s, it does not make sense
-- to provide a number @ε < 1e-53@ as the desired precision. For @Float@s,
-- providing an @ε < 1e-24@ also does not make sense.
-- Example of how to call the function:
--
-- >>> zetaHurwitz 1e-15 0.25 !! 5
-- 1024.3489745265808
zetaHurwitz :: forall a . (Floating a, Ord a) => a -> a -> [a]
zetaHurwitz eps a = zipWith3 (\s i t -> s + i + t) ss is ts
where
-- When given @1e-14@ as the @eps@ argument, this'll be
-- @div (33 * (length . takeWhile (>= 1) . iterate (/ 10) . recip) 1e-14) 10 == div (33 * 14) 10@
-- @div (33 * 14) 10 == 46.
-- meaning @N,M@ in formula 4.8.5 will be @46@.
-- Multiplying by 33 and dividing by 10 is because asking for @14@ digits
-- of decimal precision equals asking for @(log 10 / log 2) * 14 ~ 3.3 * 14 ~ 46@
-- bits of precision.
digitsOfPrecision :: Integer
digitsOfPrecision =
let magnitude = toInteger . length . takeWhile (>= 1) . iterate (/ 10) . recip $ eps
in div (magnitude * 33) 10
-- @a + n@
aPlusN :: a
aPlusN = a + fromInteger digitsOfPrecision
-- @[(a + n)^s | s <- [0, 1, 2 ..]]@
powsOfAPlusN :: [a]
powsOfAPlusN = iterate (aPlusN *) 1
-- [ [ 1 ] | ]
-- | \sum_{k=0}^\(n-1) | ----------- | | s <- [0, 1, 2 ..] |
-- [ [ (a + k) ^ s ] | ]
-- @S@ value in 4.8.5 formula.
ss :: [a]
ss = let numbers = map ((a +) . fromInteger) [0..digitsOfPrecision-1]
denoms = replicate (fromInteger digitsOfPrecision) 1 :
iterate (zipWith (*) numbers) numbers
in map (sum . map recip) denoms
-- [ (a + n) ^ (1 - s) a + n | ]
-- | ----------------- = ---------------------- | s <- [0, 1, 2 ..] |
-- [ s - 1 (a + n) ^ s * (s - 1) | ]
-- @I@ value in 4.8.5 formula.
is :: [a]
is = let denoms = zipWith
(\powOfA int -> powOfA * fromInteger int)
powsOfAPlusN
[-1, 0..]
in map (aPlusN /) denoms
-- [ 1 | ]
-- [ ----------- | s <- [0 ..] ]
-- [ (a + n) ^ s | ]
constants2 :: [a]
constants2 = map recip powsOfAPlusN
-- [ [(s)_(2*k - 1) | k <- [1 ..]], s <- [0 ..]], i.e. odd indices of
-- infinite rising factorial sequences, each sequence starting at a
-- positive integer.
pochhammers :: [[Integer]]
pochhammers = let -- [ [(s)_k | k <- [1 ..]], s <- [1 ..]]
pochhs :: [[Integer]]
pochhs = iterate (\(x : xs) -> map (`div` x) xs) (tail factorial)
in -- When @s@ is @0@, the infinite sequence of rising
-- factorials starting at @s@ is @[0,0,0,0..]@.
repeat 0 : map skipOdds pochhs
-- [ B_2k | ]
-- | ------------------------- | k <- [1 ..] |
-- [ (2k)! (a + n) ^ (2*k - 1) | ]
second :: [a]
second =
take (fromInteger digitsOfPrecision) $
zipWith3
(\bern evenFac denom -> fromRational bern / (denom * fromInteger evenFac))
(tail $ skipOdds bernoulli)
(tail $ skipOdds factorial)
-- Recall that @powsOfAPlusN = [(a + n) ^ s | s <- [0 ..]]@, so this
-- is @[(a + n) ^ (2 * s - 1) | s <- [1 ..]]@
(skipEvens powsOfAPlusN)
fracs :: [a]
fracs = map
(sum . zipWith (\s p -> s * fromInteger p) second)
pochhammers
-- Infinite list of @T@ values in 4.8.5 formula, for every @s@ in
-- @[0, 1, 2 ..]@.
ts :: [a]
ts = zipWith
(\constant2 frac -> constant2 * (0.5 + frac))
constants2
fracs
| Bodigrim/arithmoi | Math/NumberTheory/Zeta/Hurwitz.hs | mit | 4,891 | 0 | 16 | 1,596 | 731 | 424 | 307 | 50 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PartialTypeSignatures #-}
module Web.Views.Index where
import Model.CoreTypes
import Web.Utils
import Web.Routes as R
import Web.Views.DiamondButton
import Text.Blaze.Html5 ((!))
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
indexAction :: PortfolioAction ctx a
indexAction = blaze $ baseHeader "Index" indexBase
indexBase :: H.Html
indexBase =
H.div ! A.class_ "white black-text" $
H.main $
H.div ! A.class_ "full f f-col f-sa center" $ do
H.div ! A.class_ "f-g1 f f-center fi-center" $
H.h5 $ H.blockquote "I wanna make the world a better place /s"
H.div ! A.class_ "f-g5 f f-center f-col fi-center" $ do
H.h5 $ H.em "Linux enthusiast"
H.h1 "Tom Lebreux"
H.div ! A.class_ "f f-row f-center f-g1 fi-center" $
diamondBtn (A.href $ toHref R.aboutR) "Press here"
| tomleb/portfolio | src/Web/Views/Index.hs | mit | 1,036 | 0 | 13 | 284 | 243 | 130 | 113 | 25 | 1 |
module Main where
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.Maybe (fromJust)
import Data.Aeson (decode)
import LevelParser
import ParitySolver
main :: IO ()
main = do
fc <- BS.readFile "story.json"
let levels = map fromLevel . fromJust $ decode fc
let findPath gs = findChoosenPath $ findCompletionPath gs
-- print . findPath $ levels !! 50
print . mapM_ findPath $ take 50 levels
| jcla1/parity-solver | Main.hs | mit | 498 | 0 | 12 | 160 | 129 | 67 | 62 | 12 | 1 |
isPrime::Integer->Bool
isPrime n = null [x | x <- [2..(floor(sqrt(fromInteger n)))], mod n x == 0]
factors::Integer->[Integer]
factors n = [x | x <- [1..n], mod n x == 0]
main::IO()
main = print $ last $ takeWhile isPrime $ factors 600851475143
| neutronest/eulerproject-douby | e3/e3.hs | mit | 247 | 0 | 15 | 44 | 150 | 76 | 74 | 6 | 1 |
{-# language TemplateHaskell #-}
{-# language DeriveDataTypeable #-}
module DPLLT.Trace where
import DPLLT.Data
import qualified Fourier_Motzkin as FM
import Autolib.Reader
import Autolib.ToDoc
import Autolib.Reporter
import Autolib.Size
import qualified Autolib.Relation as R
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import Data.List ( partition )
import Control.Applicative ((<$>))
import Data.List ( nub )
import Data.Typeable
import Data.Maybe ( isNothing, isJust )
import Debug.Trace
data Conflict = Boolean Clause
| Theory
deriving (Eq, Typeable, Show)
data Step = Decide Literal
| Propagate { use :: Conflict , obtain :: Literal }
| SAT
| Conflict Conflict
| Backtrack
| Backjump { to_level :: Int, learn :: Clause }
| UNSAT
deriving (Eq, Typeable, Show)
instance Size Step where size = const 1
derives [makeReader] [''Step ]
instance ToDoc Step where toDoc = text . show
data Reason = Decision | Alternate_Decision
| Propagation { antecedent :: Conflict }
deriving (Eq, Typeable, Show)
derives [makeReader] [''Reason ]
instance ToDoc Reason where toDoc = text . show
data Info =
Info { value :: Bool
, level :: Int
, reason :: Reason
}
deriving (Eq, Typeable, Show)
instance ToDoc Info where toDoc = text . show
derives [makeReader] [''Info]
instance ToDoc Conflict where toDoc = text . show
derives [makeReader] [''Conflict]
data State =
State { decision_level :: Int
, assignment :: M.Map Atom Info
, conflict :: Maybe Conflict
, variables :: S.Set Atom
, formula :: CNF
}
conflicting :: State -> Bool
conflicting s = isJust $ conflict s
state0 cnf = State
{ formula = nub $ map nub cnf
, variables = S.fromList $ map atom $ concat cnf
, decision_level = 0
, assignment = M.empty
, conflict = Nothing
}
data Modus = Modus
{ require_complete_propagation :: Bool
, decisions_must_be_negative :: Bool
, clause_learning :: Bool
, variable_elimination :: Bool
}
deriving (Eq, Typeable)
modus0 :: Modus
modus0 = Modus
{ require_complete_propagation = False
, decisions_must_be_negative = True
, clause_learning = False
, variable_elimination = False
}
derives [makeReader, makeToDoc] [''State, ''Modus]
instance Show State where show = render . toDoc
execute :: Modus -> CNF -> [Step] -> Reporter State
execute mo cnf steps = foldM ( work mo ) (state0 cnf) steps
work :: Modus -> State -> Step -> Reporter State
work mo a s = do
inform $ vcat [ text "current" </> toDoc a, text "step" </> toDoc s ]
case s of
Decide l -> do
when (require_complete_propagation mo) $ assert_completely_propagated a
assert_no_conflict a
let p = positive l ; v = atom l
must_be_unassigned a l
when (decisions_must_be_negative mo) $
when p $ reject $ text "decision literal must be negative"
return $ decide a l
Propagate { use = Theory, obtain = l } -> do
assert_no_conflict a
must_be_unassigned a l
case atom l of
Boolean_Atom ba -> do
reject $ text "theory propagation cannot yield a Boolean atom"
Theory_Atom ta -> do
let la = if positive l then ta else FM.negated ta
tcs = FM.negated la : theory_atoms a
sat = FM.satisfiable tcs
when sat $ reject
$ text "atom cannot be inferred because its negation, together with current theory atoms, is satisfiable"
</> toDoc tcs
return $ propagate a Theory l
Propagate { use = Boolean cl, obtain = l } -> do
assert_no_conflict a
must_be_unassigned a l
when (not $ elem cl $ formula a) $ reject $ text "the cnf does not contain this clause"
when (not $ elem l cl) $ reject $ text "the clause does not contain this literal"
let ( me, others ) = partition (== l) cl
forM_ others $ \ o -> case (evaluate_literal (assignment a) o) of
Nothing -> reject $ text "the clause is not unit, because"
<+> toDoc o <+> text "is unassigned"
Just True -> reject $ text "the clause is not unit, because"
<+> toDoc o <+> text "is true"
Just False -> return ()
return $ propagate a (Boolean cl) l
SAT -> do
assert_no_conflict a
forM_ (formula a) $ \ cl -> do
let vs = map (\ l -> (l, evaluate_literal (assignment a) l)) cl
sat = any ( \ (l,v) -> v == Just True ) vs
when (not sat) $ reject $ vcat
[ text "clause" <+> toDoc cl <+> text "is not satisfied"
, text "values of literals are" <+> toDoc vs
]
let tcs = theory_atoms a
sat = FM.satisfiable tcs
when (not sat) $ reject
$ text "the conjunction of theory atoms is not satisfiable"
</> toDoc tcs
return a
Conflict (Boolean cl) -> do
assert_no_conflict a
let vs = map (\ l -> (l, evaluate_literal (assignment a) l)) cl
unsat = all ( \ (l,v) -> v == Just False ) vs
when (not unsat) $ reject $ vcat
[ text "clause" <+> toDoc cl <+> text "is not a conflict clause"
, text "values of literals are" <+> toDoc vs
]
return $ boolean_conflict a cl
Conflict Theory -> do
assert_no_conflict a
let tcs = theory_atoms a
sat = FM.satisfiable tcs
when sat $ reject $
text "not a theory conflict, since the conjunction of theory atoms is satisfiable"
</> toDoc tcs
return $ a { conflict = Just Theory }
Backtrack -> assert_conflict a $ \ cl -> do
when ( clause_learning mo ) $ reject
$ text "Backtrack is not allowed (use Backjump)"
let dl = decision_level a
when (dl <= 0) $ reject
$ text "no previous decision (use UNSAT instead of Backtrack)"
return $ backtrack a
Backjump { to_level = dl, learn = learnt_cl } -> assert_conflict a $ \ con -> do
when (not $ clause_learning mo ) $ reject $ text "clause learning is not allowed (use Backtrack)"
case con of
Boolean cl -> do
reverse_unit_propagation_check a learnt_cl cl
when (dl >= decision_level a)
$ reject $ text "must jump to a lower level"
return $ ( reset_dl dl a )
{ formula = learnt_cl : formula a, conflict = Nothing }
_ -> reject $ text "Backjump only after Boolean conflict (for now)"
UNSAT -> assert_conflict a $ \ cl -> do
let dl = decision_level a
when (dl > 0) $ reject $ text "not at root decision level"
return a
theory_atoms a = do
(Theory_Atom a , info) <- M.toList $ assignment a
return $ if value info then a else FM.negated a
reverse_unit_propagation_check a lcl cl = do
let antes = do
(v, Info { reason = Propagation { antecedent = Boolean a}}) <- M.toList $ assignment a
return a
ok <- is_implied_by lcl $ cl : antes
when (not ok) $ reject
$ text "the learnt clause is not implied by conflict and antecedent clauses."
is_implied_by cl antes =
derive_conflict $ map ( \ l -> [ opposite l ] ) cl ++ antes
derive_conflict cnf = do
let ( conf, noconf ) = partition null cnf
( unit, nounit ) = partition (\ cl -> length cl == 1 ) noconf
if null conf
then if null unit
then return False -- no conflict, no propagation
else do
let cnf' = foldr assign cnf $ concat unit
derive_conflict cnf'
else return True -- conflict
assign l cnf =
let ( sat, open) = partition ( \ cl -> elem l cl ) cnf
in map ( filter ( \ l' -> l' /= opposite l) ) open
decide a l =
let p = positive l ; v = atom l
dl = succ $ decision_level a
in a
{ decision_level = dl
, assignment = M.insert v
(Info { value = p
, level = dl
, reason = Decision } ) $ assignment a
}
propagate a prop l =
let dl = decision_level a
in a
{ assignment = M.insert (atom l) (Info {
value = positive l, level = dl, reason = Propagation prop}) $ assignment a
}
backtrack a =
let dl = decision_level a
[(v,i)] = filter (\(v,i) -> reason i == Decision && level i == dl)
$ M.toList $ assignment a
a' = reset_dl (pred dl) a
in alternate ( a' { conflict = Nothing } ) v ( not $ value i )
boolean_conflict a cl = a { conflict = Just (Boolean cl) }
alternate a v p =
let i = Info { value = p, level = decision_level a, reason = Alternate_Decision }
in a { assignment = M.insert v i $ assignment a }
must_be_unassigned a l =
maybe ( return () )
( const $ reject $ text "literal" <+> toDoc l <+> text "is already assigned")
$ M.lookup (atom l) $ assignment a
assert_no_conflict a = when (conflicting a) $ reject
$ text "must handle conflict first (by Backtrack, Backjump or UNSAT)"
assert_conflict :: State -> ( Conflict -> Reporter r ) -> Reporter r
assert_conflict a cont = case conflict a of
Just con -> cont con
_ -> reject $ text "must find conflict first"
assert_completely_propagated a = do
when (not $ null $ unit_clauses a) $ reject
$ text "must do all unit propagations first"
is_unit_clause a cl =
let vs = map (evaluate_literal (assignment a)) cl
in ( not $ Just True `elem` vs )
&& ( 1 == length (filter isNothing vs) )
unit_clauses a = filter (is_unit_clause a) $ formula a
reset_dl dl a = a
{ assignment = M.filter ( \ i -> level i <= dl ) $ assignment a
, decision_level = dl
}
evaluate_literal a l = do
let f = if positive l then id else not
f <$> value <$> M.lookup (atom l) a
| marcellussiegburg/autotool | collection/src/DPLLT/Trace.hs | gpl-2.0 | 10,756 | 0 | 25 | 3,886 | 3,334 | 1,668 | 1,666 | 239 | 14 |
{-# LANGUAGE DeriveDataTypeable #-}
module ArrayBonn.Program where
import Autolib.Reader
import Autolib.ToDoc
import Autolib.TES.Identifier
import Autolib.Size
import Data.Typeable
data Program st = Program [ st ]
deriving ( Typeable )
plength ( Program sts ) = length sts
instance ToDoc st => ToDoc ( Program st ) where
toDoc ( Program ss ) = vcat $ map toDoc ss
instance Reader st => Reader ( Program st ) where
reader = do
ss <- many reader
return $ Program ss
instance Size st => Size ( Program st ) where
size ( Program ss ) = sum $ map size ss
| Erdwolf/autotool-bonn | src/ArrayBonn/Program.hs | gpl-2.0 | 583 | 1 | 11 | 133 | 206 | 104 | 102 | 18 | 1 |
module Inference.Builtin (builtinTypes) where
import Types
import Inference.Types
builtinTypes :: [(String, Inference Type)]
builtinTypes = [ ("dup", dup_)
, ("i", i_)
, ("drop", drop_)
, ("swap", swap_)
, ("quote", quote_)
]
dup_ :: Inference Type
dup_ = do v <- freshVar
[v] --> [v, v]
drop_ :: Inference Type
drop_ = do v <- freshVar
[v] --> []
swap_ :: Inference Type
swap_ = do v <- freshVar
v' <- freshVar
[v, v'] --> [v', v]
i_ :: Inference Type
i_ = do s <- freshStackVar
s' <- freshStackVar
let top = Fun ([] :# s) ([] :# s')
return $ Fun ([top] :# s) ([] :# s')
quote_ :: Inference Type
quote_ = do v <- freshVar
f <- [] --> [v]
[v] --> [f]
| breestanwyck/stack-unification | src/Inference/Builtin.hs | gpl-2.0 | 824 | 0 | 13 | 299 | 339 | 184 | 155 | 28 | 1 |
-- Copyright (C) 2006-2008 Angelos Charalambidis <[email protected]>
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2, or (at your option)
-- any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; see the file COPYING. If not, write to
-- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-- Boston, MA 02110-1301, USA.
{-# LANGUAGE FlexibleInstances #-}
module Pretty (
module Pretty,
module Text.PrettyPrint
) where
import Text.PrettyPrint
import Loc (Loc(..), LocSpan(..))
import Lang (Sym(..))
import Types (Typed(..), TyVar(..), MonoTypeV(..), GrdType(..), TyEnv(..), TySig(..), tyvars)
import Data.List (nub)
class Pretty a where
ppr :: a -> Doc
pprint a = print (ppr a)
instance Pretty Doc where
ppr = id
instance Pretty [Char] where
ppr = text
instance Pretty Int where
ppr = int
dcolon = text "::"
arrow = text "->"
dot = char '.'
entails = text ":-"
-- semi = text ";"
curly a = text "{" <+> a <+> text "}"
--brackets a = text "[" <+> a <+> text "]"
instance Pretty Loc where
ppr (Loc _ (-1) (-1)) = text "<no-location>"
ppr (Loc f l c) = hcat $ punctuate colon [ text f, int l, int c ]
instance Pretty LocSpan where
ppr (OneLineSpan f l c1 c2) =
hcat $ punctuate colon [ text f, int l, parens $ int c1 <> char '-' <> int c2 ]
ppr (MultiLineSpan f l1 c1 l2 c2) =
hcat $ punctuate colon [ text f, ppr_par l1 c1 <> char '-' <> ppr_par l2 c2 ]
where ppr_par l c = parens (int l <> comma <> int c)
ppr (LocSpan l1 l2) = ppr l1 <> char '-' <> ppr l2
instance Pretty Sym where
ppr (Sym s) = ppr s
ppr AnonSym = text "_"
instance Pretty a => Pretty (Typed a) where
ppr (T a ty) = ppr a -- <> dcolon <> ppr ty
instance Pretty GrdType where
ppr TyBool = text "o"
ppr TyAll = text "i"
instance Pretty TyVar where
ppr (Tv i _) = int i
instance (Eq a, Pretty a) => Pretty (MonoTypeV a) where
ppr t = pprPrec 1 f t
where f = tvmap [t]
-- pprPrec p f (TyTup tl) = parens $ sep (punctuate comma (map (pprPrec 1 f) tl))
pprPrec p f (TyGrd c) = ppr c
pprPrec p f (TyVar v) = f v
pprPrec p f ty@(TyFun t t') = if (p == 0) then
parens (sep [ pprPrec 0 f t , arrow <+> pprPrec p f t' ])
else
sep [ pprPrec 0 f t , arrow <+> pprPrec p f t' ]
tynames = letters ++ [ x++(show i) | x <- letters, i <- [1..] ]
where letters = [ "a", "b", "c", "d", "e", "f" ]
tvmap tys v =
let tvs = nub $ concatMap tyvars tys
fl = zip tvs tynames
in case lookup v fl of
Nothing -> ppr v
Just n -> text n
instance Pretty a => Pretty (TySig a) where
ppr (a,t) = sep [ ppr a, dcolon <+> ppr t]
instance Pretty a => Pretty (TyEnv a) where
ppr ts = vcat $ map ppr ts
| acharal/hopes | src/basic/Pretty.hs | gpl-2.0 | 3,353 | 0 | 12 | 946 | 1,105 | 576 | 529 | 63 | 2 |
{-# LANGUAGE DeriveGeneric #-}
module Language.Mulang.Transform.Normalizer (
normalize,
unnormalized,
NormalizationOptions (..),
SequenceSortMode (..)) where
import GHC.Generics
import Data.List (sort, nub)
import Data.List.Extra (unwind)
import Language.Mulang.Ast
import Language.Mulang.Ast.Visitor
import Language.Mulang.Ast.Operator (isCommutative)
import Language.Mulang.Builder (compact, trim)
import Language.Mulang.Generator (declarators, declaredIdentifiers)
import Language.Mulang.Inspector.Literal (isLiteral)
data NormalizationOptions = NormalizationOptions {
convertObjectVariableIntoObject :: Bool,
convertLambdaVariableIntoFunction :: Bool,
convertObjectLevelFunctionIntoMethod :: Bool,
convertObjectLevelLambdaVariableIntoMethod :: Bool,
convertObjectLevelVariableIntoAttribute :: Bool,
convertObjectIntoDict :: Bool,
sortSequenceDeclarations :: SequenceSortMode,
insertImplicitReturn :: Bool,
compactSequences :: Bool,
trimSequences :: Bool,
sortCommutativeApplications :: Bool
} deriving (Eq, Show, Read, Generic)
data SequenceSortMode
= SortNothing
| SortUniqueNonVariables
| SortAllNonVariables
| SortAll deriving (Eq, Show, Read, Generic)
unnormalized :: NormalizationOptions
unnormalized = NormalizationOptions {
convertObjectVariableIntoObject = False,
convertLambdaVariableIntoFunction = False,
convertObjectLevelFunctionIntoMethod = False,
convertObjectLevelLambdaVariableIntoMethod = False,
convertObjectLevelVariableIntoAttribute = False,
convertObjectIntoDict = False,
sortSequenceDeclarations = SortNothing,
insertImplicitReturn = False,
compactSequences = False,
trimSequences = False,
sortCommutativeApplications = False
}
normalize :: NormalizationOptions -> Expression -> Expression
normalize ops (Application (Send r m []) args) = Send (normalize ops r) (normalize ops m) (mapNormalize ops args)
normalize ops (Application (Primitive op) [e1, e2]) | isCommutative op = Application (Primitive op) (normalizeCommutativeArguments ops [e1, e2])
normalize ops (LValue n (Lambda vars e)) | convertLambdaVariableIntoFunction ops = SimpleFunction n vars (normalize ops e)
normalize ops (LValue n (MuObject e)) | convertObjectVariableIntoObject ops = Object n (normalizeObjectLevel ops e)
normalize ops (MuObject e) | convertObjectIntoDict ops = MuDict . normalize ops . normalizeArrows $ e
normalize ops (Object n e) = Object n (normalizeObjectLevel ops e)
normalize ops (Sequence es) = normalizeSequence ops . sortDeclarations ops . mapNormalize ops $ es
--
normalize _ a@(Assert _ _) = a
normalize ops (For stms e1) = For stms (normalize ops e1)
normalize ops (ForLoop e c i b) = ForLoop (normalize ops e) (normalize ops c) (normalize ops i) (normalize ops b)
normalize ops (Lambda ps e2) = Lambda ps (normalize ops e2)
normalize ops (Match e1 equations) = Match (normalize ops e1) (mapNormalizeEquation ops equations)
normalize ops (Rule n args es) = Rule n args (mapNormalize ops es)
normalize ops (Send r e es) = Send (normalize ops r) (normalize ops e) (mapNormalize ops es)
normalize ops (Switch v cs d) = Switch (normalize ops v) (normalizeSwitchCases ops cs) (normalize ops d)
normalize ops (Try t cs f) = Try (normalize ops t) (normalizeTryCases ops cs) (normalize ops f)
--
normalize _ (SinglePatternsList ps c) = c ps
normalize _ c@(Terminal) = c
normalize ops (ExpressionAndExpressionsList e es c) = c (normalize ops e) (mapNormalize ops es)
normalize ops (SingleEquationsList eqs c) = c (mapNormalizeEquation ops eqs)
normalize ops (SingleExpression e c) = c (normalize ops e)
normalize ops (SingleExpressionsList es c) = c (mapNormalize ops es)
normalize ops (ThreeExpressions e1 e2 e3 c) = c (normalize ops e1) (normalize ops e2) (normalize ops e3)
normalize ops (TwoExpressions e1 e2 c) = c (normalize ops e1) (normalize ops e2)
mapNormalize ops = map (normalize ops)
mapNormalizeEquation ops = map (normalizeEquation ops)
normalizeArrows :: Expression -> Expression
normalizeArrows (Sequence es) = Sequence . map normalizeArrows $ es
normalizeArrows (LValue n v) = Arrow (MuString n) v
normalizeArrows e = e
normalizeSequence :: NormalizationOptions -> [Expression] -> Expression
normalizeSequence ops = compact' . trim'
where
compact' = if compactSequences ops then compact else Sequence
trim' = if trimSequences ops then trim else id
normalizeCommutativeArguments :: NormalizationOptions -> [Expression] -> [Expression]
normalizeCommutativeArguments ops args | sortCommutativeApplications ops = sort args
normalizeCommutativeArguments _ args = args
normalizeObjectLevel :: NormalizationOptions -> Expression -> Expression
normalizeObjectLevel ops (Function n eqs) | convertObjectLevelFunctionIntoMethod ops = Method n (mapNormalizeEquation ops eqs)
normalizeObjectLevel ops (LValue n (Lambda vars e)) | convertObjectLevelLambdaVariableIntoMethod ops = SimpleMethod n vars (normalize ops e)
normalizeObjectLevel ops (LValue n e) | convertObjectLevelVariableIntoAttribute ops = Attribute n (normalize ops e)
normalizeObjectLevel ops (Sequence es) = normalizeSequence ops (map (normalizeObjectLevel ops) es)
normalizeObjectLevel ops e = normalize ops e
normalizeEquation :: NormalizationOptions -> Equation -> Equation
normalizeEquation ops = mapEquation (normalize ops) (normalizeBody ops)
normalizeBody :: NormalizationOptions -> Expression -> Expression
normalizeBody ops = normalizeReturn ops . normalize ops
normalizeReturn :: NormalizationOptions -> Expression -> Expression
normalizeReturn ops e | not $ insertImplicitReturn ops = e
normalizeReturn _ e | isImplicitReturn e = Return e
normalizeReturn _ (Sequence es) | Just (i, l) <- unwind es, isImplicitReturn l = Sequence $ i ++ [Return l]
normalizeReturn _ e = e
normalizeTryCases ops = map (\(p, e) -> (p, normalize ops e))
normalizeSwitchCases ops = map (\(e1, e2) -> (normalize ops e1, normalize ops e2))
isImplicitReturn :: Expression -> Bool
isImplicitReturn (Reference _) = True
isImplicitReturn (TypeCast _ _) = True
isImplicitReturn (FieldReference _ _ ) = True
isImplicitReturn (Application _ _ ) = True
isImplicitReturn (Send _ _ _ ) = True
isImplicitReturn (New _ _ ) = True
isImplicitReturn (If _ _ _) = True
isImplicitReturn MuNil = False
isImplicitReturn e = isLiteral e
isSafeDeclaration :: Expression -> Bool
isSafeDeclaration (Attribute _ _) = False
isSafeDeclaration (LValue _ _) = False
isSafeDeclaration (Other _ _) = False
isSafeDeclaration e = isDeclaration e
isDeclaration :: Expression -> Bool
isDeclaration = not.null.declarators
sortDeclarations :: NormalizationOptions -> [Expression] -> [Expression]
sortDeclarations ops expressions | shouldSort (sortSequenceDeclarations ops) = sort expressions
| otherwise = expressions
where
shouldSort :: SequenceSortMode -> Bool
shouldSort SortNothing = False
shouldSort SortUniqueNonVariables = all isSafeDeclaration expressions && identifiersAreUnique expressions
shouldSort SortAllNonVariables = all isSafeDeclaration expressions
shouldSort SortAll = all isDeclaration expressions
identifiersAreUnique = unique . map declaredIdentifiers
unique xs = nub xs == xs
| mumuki/mulang | src/Language/Mulang/Transform/Normalizer.hs | gpl-3.0 | 7,931 | 0 | 10 | 1,803 | 2,366 | 1,208 | 1,158 | 128 | 4 |
module HEP.Automation.MadGraph.Dataset.Processes where
data Process = TTBar | TTBar0or1J | SingleTZpSemiLep | TTBarSemiZp | TZpLep | TTBarSemiZpNotFull | TTBarSemiLep | SingleTZpJDecay | UUDijet | EEDijet | WBZprimeDecay | WGDijet
deriving (Show, Eq)
preDefProcess :: Process -> [Char]
preDefProcess TTBar = "\ngenerate P P > t t~ QED=99\n"
preDefProcess TTBar0or1J = "\ngenerate P P > t t~ QED=99 @1 \nadd process P P > t t~ J QED=99 @2 \n"
preDefProcess SingleTZpSemiLep = "\ngenerate P P > t zput QED=99, (t > b w+ , w+ > J J ), (zput > t~ u, (t~ > b~ w-, w- > L- vl~ )) @1\nadd process P P > t zput QED=99, (t > b w+ , w+ > L+ vl ), (zput > t~ u, (t~ > b~ w-, w- > J J )) @2\nadd process P P > zptu t~ QED=99, (zptu > t u~, (t > b w+, w+ > L+ vl )), (t~ > b~ w-, w- > J J ) @3\nadd process P P > zptu t~ QED=99, (zptu > t u~, (t > b w+, w+ > J J )), (t~ > b~ w-, w- > L- vl~ ) @4\n"
preDefProcess TTBarSemiZp = "\ngenerate P P > t t~ QED=99, ( t > b w+, w+ > l+ vl ), (t~ > u~ zput, zput > b~ d ) @1 \nadd process P P > t t~ QED=99, (t > u zptu, zptu > b d~ ), (t~ > b~ w-, w- > l- vl~ ) @2 \n"
preDefProcess TZpLep = "\ngenerate P P > t zput QED=99, zput > b~ d, ( t > b w+, w+ > l+ vl ) @1 \nadd process P P > t~ zptu QED=99, (t~ > b~ w-, w- > l- vl~ ), zptu > b d~ @2 \n"
preDefProcess TTBarSemiZpNotFull = "\ngenerate P P > t t~ QED=99, t > b w+, t~ > u~ zput @1 \nadd process P P > t t~ QED=99, t > u zptu, t~ > b~ w- @2 \n"
preDefProcess TTBarSemiLep = "\ngenerate P P > t t~ QED=99, (t > b w+ , w+ > J J ), (t~ > b~ w-, w- > L- vl~ ) @1\nadd process P P > t t~ QED=99, (t > b w+ , w+ > L+ vl ), (t~ > b~ w-, w- > J J ) @2\n"
preDefProcess SingleTZpJDecay = "\ngenerate P P > t zput J $ t~ , ( t > w+ b, w+ > l+ vl), zput > b~ d @1 \nadd process P P > t~ zptu J $ t , (t~ > w- b~, w- > l- vl~), zptu > b d~ @2\n"
preDefProcess UUDijet = "\ngenerate u u~ > u u~ QED=0\n"
preDefProcess EEDijet = "\ngenerate e+ e- > u u~ \n"
preDefProcess WBZprimeDecay = "\ngenerate p p > w+ b zput $ t / d d~ , w+ > l+ vl , zput > d b~ QED=99 @1 \nadd process p p > w- b~ zptu $ t~ / d d~ , w- > l- vl~ , zptu > d~ b QED=99 @2 \n"
preDefProcess WGDijet = "\ngenerate P P > w+ gg QED=99, w+ > l+ vl, gg > J J @1 \nadd process P P > w- gg QED=99, w- > l- vl~, gg > J J @2 \n"
| wavewave/madgraph-auto-dataset | src/HEP/Automation/MadGraph/Dataset/Processes.hs | gpl-3.0 | 2,336 | 0 | 6 | 624 | 168 | 94 | 74 | 16 | 1 |
fromY id :: b -> a | hmemcpy/milewski-ctfp-pdf | src/content/2.6/code/haskell/snippet02.hs | gpl-3.0 | 18 | 3 | 4 | 5 | 13 | 6 | 7 | -1 | -1 |
module Numbering
( dividable
, is_prime
) where
dividable :: Int -> Int -> Bool
dividable x y = (x `mod` y) == 0
is_prime :: Int -> Bool
is_prime 1 = False
is_prime x = length dividers == 0
where dividers = (filter (dividable x) [2..floor (sqrt (fromIntegral x))])
| susu/haskell-problems | ProjectEuler/Numbering.hs | gpl-3.0 | 272 | 0 | 14 | 57 | 121 | 65 | 56 | 9 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
-- spurious warnings for view patterns
-- |
-- Copyright : (c) 2010-2012 Benedikt Schmidt & Simon Meier
-- License : GPL v3 (see LICENSE)
--
-- Maintainer : Benedikt Schmidt <[email protected]>
--
-- Terms with logical variables and names.
module Term.LTerm (
-- * Names
Name(..)
, NameTag(..)
, NameId(..)
, NTerm
-- ** Queries
, sortOfName
-- ** Construction
, freshTerm
, pubTerm
-- * LVar
, LSort(..)
, LVar(..)
, NodeId
, LTerm
, LNTerm
, freshLVar
, sortPrefix
, sortSuffix
, sortCompare
, sortOfLTerm
, sortOfLNTerm
, sortOfLit
, isMsgVar
, isFreshVar
, isPubVar
, isPubConst
, isSimpleTerm
, getVar
, getMsgVar
, freshToConst
, variableToConst
, niFactors
, containsPrivate
, containsNoPrivateExcept
, neverContainsFreshPriv
-- ** Destructors
, ltermVar
, ltermVar'
, ltermNodeId
, ltermNodeId'
, bltermNodeId
, bltermNodeId'
-- ** Manging Free LVars
, HasFrees(..)
, MonotoneFunction(..)
, occurs
, freesList
, frees
, someInst
, rename
, renameIgnoring
, eqModuloFreshnessNoAC
, avoid
, evalFreshAvoiding
, evalFreshTAvoiding
, renameAvoiding
, renameAvoidingIgnoring
, avoidPrecise
, renamePrecise
, renameDropNamehint
, varOccurences
-- * BVar
, BVar(..)
, BLVar
, BLTerm
, foldBVar
, fromFree
-- * Pretty-Printing
, prettyLVar
, prettyNodeId
, prettyNTerm
, prettyLNTerm
, showLitName
-- * Convenience exports
, module Term.VTerm
) where
import Text.PrettyPrint.Class
-- import Control.Applicative
import Control.DeepSeq
import Control.Monad.Bind
import Control.Monad.Identity
import qualified Control.Monad.Trans.PreciseFresh as Precise
import GHC.Generics (Generic)
import Data.Binary
import qualified Data.DList as D
import Data.Foldable hiding (concatMap, elem, notElem, any)
import Data.Data
import qualified Data.Map as M
import qualified Data.Map.Strict as M'
import Data.Monoid
import qualified Data.Set as S
-- import Data.Traversable
import qualified Data.ByteString.Char8 as BC
import Safe (fromJustNote)
import Extension.Data.Monoid
import Extension.Prelude
import Logic.Connectives
import Term.Rewriting.Definitions
import Term.VTerm
------------------------------------------------------------------------------
-- Sorts.
------------------------------------------------------------------------------
-- | Sorts for logical variables. They satisfy the following sub-sort relation:
--
-- > LSortFresh < LSortMsg
-- > LSortPub < LSortMsg
--
data LSort = LSortPub -- ^ Arbitrary public names.
| LSortFresh -- ^ Arbitrary fresh names.
| LSortMsg -- ^ Arbitrary messages.
| LSortNode -- ^ Sort for variables denoting nodes of derivation graphs.
deriving( Eq, Ord, Show, Enum, Bounded, Typeable, Data, Generic, NFData, Binary )
-- | @sortCompare s1 s2@ compares @s1@ and @s2@ with respect to the partial order on sorts.
-- Partial order: Node Msg
-- / \
-- Pub Fresh
sortCompare :: LSort -> LSort -> Maybe Ordering
sortCompare s1 s2 = case (s1, s2) of
(a, b) | a == b -> Just EQ
-- Node is incomparable to all other sorts, invalid input
(LSortNode, _ ) -> Nothing
(_, LSortNode) -> Nothing
-- Msg is greater than all sorts except Node
(LSortMsg, _ ) -> Just GT
(_, LSortMsg ) -> Just LT
-- The remaining combinations (Pub/Fresh) are incomparable
_ -> Nothing
-- | @sortPrefix s@ is the prefix we use for annotating variables of sort @s@.
sortPrefix :: LSort -> String
sortPrefix LSortMsg = ""
sortPrefix LSortFresh = "~"
sortPrefix LSortPub = "$"
sortPrefix LSortNode = "#"
-- | @sortSuffix s@ is the suffix we use for annotating variables of sort @s@.
sortSuffix :: LSort -> String
sortSuffix LSortMsg = "msg"
sortSuffix LSortFresh = "fresh"
sortSuffix LSortPub = "pub"
sortSuffix LSortNode = "node"
------------------------------------------------------------------------------
-- Names
------------------------------------------------------------------------------
-- | Type safety for names.
newtype NameId = NameId { getNameId :: String }
deriving( Eq, Ord, Typeable, Data, Generic, NFData, Binary )
-- | Tags for names.
data NameTag = FreshName | PubName | NodeName
deriving( Eq, Ord, Show, Typeable, Data, Generic, NFData, Binary )
-- | Names.
data Name = Name {nTag :: NameTag, nId :: NameId}
deriving( Eq, Ord, Typeable, Data, Generic, NFData, Binary)
-- | Terms with literals containing names and arbitrary variables.
type NTerm v = VTerm Name v
-- Instances
------------
instance IsConst Name where
instance Show Name where
show (Name FreshName n) = "~'" ++ show n ++ "'"
show (Name PubName n) = "'" ++ show n ++ "'"
show (Name NodeName n) = "#'" ++ show n ++ "'"
instance Show NameId where
show = getNameId
-- Construction of terms with names
-----------------------------------
-- | @freshTerm f@ represents the fresh name @f@.
freshTerm :: String -> NTerm v
freshTerm = lit . Con . Name FreshName . NameId
-- | @pubTerm f@ represents the pub name @f@.
pubTerm :: String -> NTerm v
pubTerm = lit . Con . Name PubName . NameId
-- | Return 'LSort' for given 'Name'.
sortOfName :: Name -> LSort
sortOfName (Name FreshName _) = LSortFresh
sortOfName (Name PubName _) = LSortPub
sortOfName (Name NodeName _) = LSortNode
-- | Is a term a public constant?
isPubConst :: LNTerm -> Bool
isPubConst (viewTerm -> Lit (Con v)) = (sortOfName v == LSortPub)
isPubConst _ = False
------------------------------------------------------------------------------
-- LVar: logical variables
------------------------------------------------------------------------------
-- | Logical variables. Variables with the same name and index but different
-- sorts are regarded as different variables.
data LVar = LVar
{ lvarName :: String
, lvarSort :: !LSort -- FIXME: Rename to 'sortOfLVar' for consistency
-- with the other 'sortOf' functions.
, lvarIdx :: !Integer
}
deriving( Typeable, Data, Generic, NFData, Binary )
-- | An alternative name for logical variables, which are intented to be
-- variables of sort 'LSortNode'.
type NodeId = LVar
-- | Terms used for proving; i.e., variables fixed to logical variables.
type LTerm c = VTerm c LVar
-- | Terms used for proving; i.e., variables fixed to logical variables
-- and constants to Names.
type LNTerm = VTerm Name LVar
-- | @freshLVar v@ represents a fresh logical variable with name @v@.
freshLVar :: MonadFresh m => String -> LSort -> m LVar
freshLVar n s = LVar n s <$> freshIdent n
-- | Returns the most precise sort of an 'LTerm'.
sortOfLTerm :: Show c => (c -> LSort) -> LTerm c -> LSort
sortOfLTerm sortOfConst t = case viewTerm2 t of
Lit2 (Con c) -> sortOfConst c
Lit2 (Var lv) -> lvarSort lv
_ -> LSortMsg
-- | Returns the most precise sort of an 'LNTerm'.
sortOfLNTerm :: LNTerm -> LSort
sortOfLNTerm = sortOfLTerm sortOfName
-- | Returns the most precise sort of a 'Lit'.
sortOfLit :: Lit Name LVar -> LSort
sortOfLit (Con n) = sortOfName n
sortOfLit (Var v) = lvarSort v
-- | Is a term a message variable?
isMsgVar :: LNTerm -> Bool
isMsgVar (viewTerm -> Lit (Var v)) = (lvarSort v == LSortMsg)
isMsgVar _ = False
-- | Is a term a public variable?
isPubVar :: LNTerm -> Bool
isPubVar (viewTerm -> Lit (Var v)) = (lvarSort v == LSortPub)
isPubVar _ = False
-- | Is a term a fresh variable?
isFreshVar :: LNTerm -> Bool
isFreshVar (viewTerm -> Lit (Var v)) = (lvarSort v == LSortFresh)
isFreshVar _ = False
-- | If the term is a variable, return it, nothing otherwise.
getVar :: LNTerm -> Maybe LVar
getVar (viewTerm -> Lit (Var v)) = Just v
getVar _ = Nothing
-- | If the term is a message variable, return it, nothing otherwise.
getMsgVar :: LNTerm -> Maybe [LVar]
getMsgVar (viewTerm -> Lit (Var v)) | (lvarSort v == LSortMsg) = Just [v]
getMsgVar _ = Nothing
-- Utility functions for constraint solving
-------------------------------------------
-- | The non-inverse factors of a term.
niFactors :: LNTerm -> [LNTerm]
niFactors t = case viewTerm2 t of
FMult ts -> concatMap niFactors ts
FInv t1 -> niFactors t1
_ -> [t]
-- | @containsPrivate t@ returns @True@ if @t@ contains private function symbols.
containsPrivate :: Term t -> Bool
containsPrivate t = case viewTerm t of
Lit _ -> False
FApp (NoEq (_,(_,Private))) _ -> True
FApp _ as -> any containsPrivate as
-- | containsNoPrivateExcept t t2@ returns @True@ if @t2@ contains private function symbols other than @t@.
containsNoPrivateExcept :: [BC.ByteString] -> Term t -> Bool
containsNoPrivateExcept funs t = case viewTerm t of
Lit _ -> True
FApp (NoEq (f,(_,Private))) as -> (elem f funs) && (all (containsNoPrivateExcept funs) as)
FApp _ as -> all (containsNoPrivateExcept funs) as
-- | A term is *simple* iff there is an instance of this term that can be
-- constructed from public names only. i.e., the term does not contain any
-- fresh names, fresh variables, or private function symbols.
isSimpleTerm :: LNTerm -> Bool
isSimpleTerm t =
not (containsPrivate t) &&
(getAll . foldMap (All . (LSortFresh /=) . sortOfLit) $ t)
-- | 'True' iff no instance of this term contains fresh names or private function symbols.
neverContainsFreshPriv :: LNTerm -> Bool
neverContainsFreshPriv t =
not (containsPrivate t) &&
(getAll . foldMap (All . (`notElem` [LSortMsg, LSortFresh]) . sortOfLit) $ t)
-- | Replaces all Fresh variables with constants using toConst.
freshToConst :: LNTerm -> LNTerm
freshToConst t = case viewTerm t of
Lit (Con _) -> t
Lit (Var v) | (lvarSort v == LSortFresh) -> variableToConst v
Lit _ -> t
FApp f as -> termViewToTerm $ FApp f (map freshToConst as)
-- | Given a variable returns a constant containing its name and type
variableToConst :: LVar -> LNTerm
variableToConst cvar = constTerm (Name (nameOfSort cvar) (NameId ("constVar_" ++ toConstName cvar)))
where
toConstName (LVar name vsort idx) = (show vsort) ++ "_" ++ (show idx) ++ "_" ++ name
nameOfSort (LVar _ LSortFresh _) = FreshName
nameOfSort (LVar _ LSortPub _) = PubName
nameOfSort (LVar _ LSortNode _) = NodeName
nameOfSort (LVar _ LSortMsg _) = error "Invalid sort Msg"
-- Destructors
--------------
-- | Extract a variable of the given sort from a term that may be such a
-- variable. Use 'termVar', if you do not want to restrict the sort.
ltermVar :: LSort -> LTerm c -> Maybe LVar
ltermVar s t = do v <- termVar t; guard (s == lvarSort v); return v
-- | Extract a variable of the given sort from a term that must be such a
-- variable. Fails with an error, if that is not possible.
ltermVar' :: Show c => LSort -> LTerm c -> LVar
ltermVar' s t =
fromJustNote err (ltermVar s t)
where
err = "ltermVar': expected variable term of sort " ++ show s ++ ", but got " ++ show t
-- | Extract a node-id variable from a term that may be a node-id variable.
ltermNodeId :: LTerm c -> Maybe LVar
ltermNodeId = ltermVar LSortNode
-- | Extract a node-id variable from a term that must be a node-id variable.
ltermNodeId' :: Show c => LTerm c -> LVar
ltermNodeId' = ltermVar' LSortNode
-- BVar: Bound variables
------------------------
-- | Bound and free variables.
data BVar v = Bound Integer -- ^ A bound variable in De-Brujin notation.
| Free v -- ^ A free variable.
deriving( Eq, Ord, Show, Data, Typeable, Generic, NFData, Binary, IsVar)
-- | 'LVar's combined with quantified variables. They occur only in 'LFormula's.
type BLVar = BVar LVar
-- | Terms built over names and 'LVar's combined with quantified variables.
type BLTerm = NTerm BLVar
-- | Fold a possibly bound variable.
{-# INLINE foldBVar #-}
foldBVar :: (Integer -> a) -> (v -> a) -> BVar v -> a
foldBVar fBound fFree = go
where
go (Bound i) = fBound i
go (Free v) = fFree v
instance Functor BVar where
fmap f = foldBVar Bound (Free . f)
instance Foldable BVar where
foldMap f = foldBVar mempty f
instance Traversable BVar where
traverse f = foldBVar (pure . Bound) (fmap Free . f)
instance Applicative BVar where
pure = return
(<*>) = ap
instance Monad BVar where
return = Free
m >>= f = foldBVar Bound f m
-- | Extract the name of free variable under the assumption the variable is
-- guaranteed to be of the form @Free a@.
fromFree :: BVar v -> v
fromFree (Free v) = v
fromFree (Bound i) = error $ "fromFree: bound variable '" ++ show i ++ "'"
-- | Extract a node-id variable from a term that may be a node-id variable.
bltermNodeId :: BLTerm -> Maybe LVar
bltermNodeId t = do
Free v <- termVar t; guard (LSortNode == lvarSort v); return v
-- | Extract a node-id variable from a term that must be a node-id variable.
bltermNodeId' :: BLTerm -> LVar
bltermNodeId' t =
fromJustNote err (bltermNodeId t)
where
err = "bltermNodeId': expected free node-id variable term, but got " ++
show t
-- Instances
------------
instance Eq LVar where
(LVar n1 s1 i1) == (LVar n2 s2 i2) = i1 == i2 && s1 == s2 && n1 == n2
-- An ord instance that prefers the 'lvarIdx' over the 'lvarName'.
instance Ord LVar where
compare (LVar x1 x2 x3) (LVar y1 y2 y3) =
compare x3 y3 <> compare x2 y2 <> compare x1 y1
instance Show LVar where
show (LVar v s i) =
sortPrefix s ++ body
where
body | null v = show i
-- | isDigit (last v) = v ++ "." ++ show i
| i == 0 = v
| otherwise = v ++ "." ++ show i
instance IsVar LVar where
------------------------------------------------------------------------------
-- Managing bound and free LVars
------------------------------------------------------------------------------
-- | This type captures the occurence of a variable in a certain context.
type Occurence = [String]
-- | For performance reasons, we distinguish between monotone functions on
-- 'LVar's and arbitrary functions. For a monotone f, if @x <= y@, then
-- @f x <= f y@. This ensures that the AC-normal form does not have
-- to be recomputed. If you are unsure about what to use, then use the
-- 'Arbitrary' function.
data MonotoneFunction f = Monotone (LVar -> f LVar )
| Arbitrary (LVar -> f LVar )
-- | @HasFree t@ denotes that the type @t@ has free @LVar@ variables. They can
-- be collected using 'foldFrees' and 'foldFreesOcc' and mapped in the context
-- of an applicative functor using 'mapFrees'.
--
-- When defining instances of this class, you have to ensure that only the free
-- LVars are collected and mapped and no others. The instances for standard
-- Haskell types assume that all variables free in all type arguments are free.
-- The 'foldFreesOcc' is only used to define the function 'varOccurences'. See
-- below for required properties of the instance methods.
--
-- Once we need it, we can use type synonym instances to parameterize over the
-- variable type.
--
class HasFrees t where
foldFrees :: Monoid m => (LVar -> m ) -> t -> m
foldFreesOcc :: Monoid m => (Occurence -> LVar -> m) -> Occurence -> t -> m
mapFrees :: Applicative f => MonotoneFunction f -> t -> f t
-- | @v `occurs` t@ iff variable @v@ occurs as a free variable in @t@.
occurs :: HasFrees t => LVar -> t -> Bool
occurs x = getAny . foldFrees (Any . (x ==))
-- | @freesDList t@ is the difference list of all free variables of @t@.
freesDList :: HasFrees t => t -> D.DList LVar
freesDList = foldFrees pure
-- | @freesList t@ is the list of all free variables of @t@.
freesList :: HasFrees t => t -> [LVar]
freesList = D.toList . freesDList
-- | @frees t@ is the sorted and duplicate-free list of all free variables in
-- @t@.
frees :: HasFrees t => t -> [LVar]
frees = sortednub . freesList
-- | Returns the variables occuring in @t@ together with the contexts they appear in.
-- Note that certain contexts (and variables only occuring in such contexts) are
-- ignored by this function.
-- The function is used to "guess" renamings of variables, i.e., if t is a renaming of s,
-- then variables that occur in equal contexts in t and s are probably renamings of
-- each other.
varOccurences :: HasFrees a => a -> [(LVar, S.Set Occurence)]
varOccurences t =
map (\((v,ctx1):rest) -> (v, S.fromList (ctx1:(map snd rest)))) . groupOn fst . sortOn fst
. foldFreesOcc (\ c v -> [(v,c)]) [] $ t
-- | @someInst t@ returns an instance of @t@ where all free variables whose
-- binding is not yet determined by the caller are replaced with fresh
-- variables.
someInst :: (MonadFresh m, MonadBind LVar LVar m, HasFrees t) => t -> m t
someInst = mapFrees (Arbitrary $ \x -> importBinding (`LVar` lvarSort x) x (lvarName x))
-- | @rename t@ replaces all variables in @t@ with fresh variables.
-- Note that the result is not guaranteed to be equal for terms that are
-- equal modulo changing the indices of variables.
rename :: (MonadFresh m, HasFrees a) => a -> m a
rename x = case boundsVarIdx x of
Nothing -> return x
Just (minVarIdx, maxVarIdx) -> do
freshStart <- freshIdents (succ (maxVarIdx - minVarIdx))
return . runIdentity . mapFrees (Monotone $ incVar (freshStart - minVarIdx)) $ x
where
incVar shift (LVar n so i) = pure $ LVar n so (i+shift)
-- | @renameIgnoring t vars@ replaces all variables in @t@ with fresh variables, excpet for the variables in @vars@.
-- Note that the result is not guaranteed to be equal for terms that are
-- equal modulo changing the indices of variables.
renameIgnoring :: (MonadFresh m, HasFrees a) => [LVar] -> a -> m a
renameIgnoring vars x = case boundsVarIdx x of
Nothing -> return x
Just (minVarIdx, maxVarIdx) -> do
freshStart <- freshIdents (succ (maxVarIdx - minVarIdx))
return . runIdentity . mapFrees (Monotone $ incVar (freshStart - minVarIdx)) $ x
where
incVar shift (LVar n so i) = pure $ if elem (LVar n so i) vars then (LVar n so i) else (LVar n so (i+shift))
-- | @eqModuloFreshness t1 t2@ checks whether @t1@ is equal to @t2@ modulo
-- renaming of indices of free variables. Note that the normal form is not
-- unique with respect to AC symbols.
eqModuloFreshnessNoAC :: (HasFrees a, Eq a) => a -> a -> Bool
eqModuloFreshnessNoAC t1 =
-- this formulation shares normalisation of t1 among further calls to
-- different t2.
(normIndices t1 ==) . normIndices
where
normIndices = (`evalFresh` nothingUsed) . (`evalBindT` noBindings) .
mapFrees (Arbitrary $ \x -> importBinding (`LVar` lvarSort x) x "")
-- | The mininum and maximum index of all free variables.
boundsVarIdx :: HasFrees t => t -> Maybe (Integer, Integer)
boundsVarIdx = getMinMax . foldFrees (minMaxSingleton . lvarIdx)
-- | @avoid t@ computes a 'FreshState' that avoids generating
-- variables occurring in @t@.
avoid :: HasFrees t => t -> FreshState
avoid = maybe 0 (succ . snd) . boundsVarIdx
-- | @m `evalFreshAvoiding` t@ evaluates the monadic action @m@ with a
-- fresh-variable supply that avoids generating variables occurring in @t@.
evalFreshAvoiding :: HasFrees t => Fresh a -> t -> a
evalFreshAvoiding m a = evalFresh m (avoid a)
-- | @m `evalFreshTAvoiding` t@ evaluates the monadic action @m@ in the
-- underlying monad with a fresh-variable supply that avoids generating
-- variables occurring in @t@.
evalFreshTAvoiding :: (Monad m, HasFrees t) => FreshT m a -> t -> m a
evalFreshTAvoiding m = evalFreshT m . avoid
-- | @s `renameAvoiding` t@ replaces all free variables in @s@ by
-- fresh variables avoiding variables in @t@.
renameAvoiding :: (HasFrees s, HasFrees t) => s -> t -> s
renameAvoiding s t = evalFreshAvoiding (rename s) t
-- | @s `renameAvoiding` t@ replaces all free variables in @s@ by
-- fresh variables avoiding variables in @t@.
renameAvoidingIgnoring :: (HasFrees s, HasFrees t) => s -> t -> [LVar] -> s
renameAvoidingIgnoring s t vars = renameIgnoring vars s `evalFreshAvoiding` t
-- | @avoidPrecise t@ computes a 'Precise.FreshState' that avoids generating
-- variables occurring in @t@.
avoidPrecise :: HasFrees t => t -> Precise.FreshState
avoidPrecise =
foldl' ins M.empty . frees
where
ins m v = M'.insertWith max (lvarName v) (lvarIdx v + 1) m
-- | @renamePrecise t@ replaces all variables in @t@ with fresh variables.
-- If 'Control.Monad.PreciseFresh' is used with non-AC terms and identical
-- fresh state, the same result is returned for two terms that only differ
-- in the indices of variables.
renamePrecise :: (MonadFresh m, HasFrees a) => a -> m a
renamePrecise x = evalBindT (someInst x) noBindings
renameDropNamehint :: (MonadFresh m, MonadBind LVar LVar m, HasFrees a) => a -> m a
renameDropNamehint =
mapFrees (Arbitrary $ \x -> importBinding (`LVar` lvarSort x) x "")
-- Instances
------------
instance HasFrees LVar where
foldFrees = id
foldFreesOcc f c v = f c v
mapFrees (Arbitrary f) = f
mapFrees (Monotone f) = f
instance HasFrees v => HasFrees (Lit c v) where
foldFrees f (Var x) = foldFrees f x
foldFrees _ _ = mempty
foldFreesOcc f c (Var x) = foldFreesOcc f c x
foldFreesOcc _ _ _ = mempty
mapFrees f (Var x) = Var <$> mapFrees f x
mapFrees _ l = pure l
instance HasFrees v => HasFrees (BVar v) where
foldFrees _ (Bound _) = mempty
foldFrees f (Free v) = foldFrees f v
foldFreesOcc _ _ (Bound _) = mempty
foldFreesOcc f c (Free v) = foldFreesOcc f c v
mapFrees _ b@(Bound _) = pure b
mapFrees f (Free v) = Free <$> mapFrees f v
instance (HasFrees l, Ord l) => HasFrees (Term l) where
foldFrees f = foldMap (foldFrees f)
foldFreesOcc f c t = case viewTerm t of
Lit l -> foldFreesOcc f c l
FApp (NoEq o) as -> foldFreesOcc f ((BC.unpack . fst $ o):c) as
FApp o as -> mconcat $ map (foldFreesOcc f (show o:c)) as
-- AC or C symbols
mapFrees f (viewTerm -> Lit l) = lit <$> mapFrees f l
mapFrees f@(Arbitrary _) (viewTerm -> FApp o l) = fApp o <$> mapFrees f l
mapFrees f@(Monotone _) (viewTerm -> FApp o l) = unsafefApp o <$> mapFrees f l
instance HasFrees a => HasFrees (Equal a) where
foldFrees f = foldMap (foldFrees f)
foldFreesOcc f p (Equal a b) = foldFreesOcc f p (a,b)
mapFrees f = traverse (mapFrees f)
instance HasFrees a => HasFrees (Match a) where
foldFrees f = foldMap (foldFrees f)
foldFreesOcc _ _ NoMatch = mempty
foldFreesOcc f p (DelayedMatches ms) = foldFreesOcc f p ms
mapFrees f = traverse (mapFrees f)
instance HasFrees a => HasFrees (RRule a) where
foldFrees f = foldMap (foldFrees f)
foldFreesOcc f p (RRule a b) = foldFreesOcc f p (a,b)
mapFrees f = traverse (mapFrees f)
instance HasFrees () where
foldFrees _ = const mempty
foldFreesOcc _ _ = const mempty
mapFrees _ = pure
instance HasFrees Int where
foldFrees _ = const mempty
foldFreesOcc _ _ = const mempty
mapFrees _ = pure
instance HasFrees Integer where
foldFrees _ = const mempty
foldFreesOcc _ _ = const mempty
mapFrees _ = pure
instance HasFrees Bool where
foldFrees _ = const mempty
foldFreesOcc _ _ = const mempty
mapFrees _ = pure
instance HasFrees Char where
foldFrees _ = const mempty
foldFreesOcc _ _ = const mempty
mapFrees _ = pure
instance HasFrees a => HasFrees (Maybe a) where
foldFrees f = foldMap (foldFrees f)
foldFreesOcc _ _ Nothing = mempty
foldFreesOcc f p (Just x) = foldFreesOcc f p x
mapFrees f = traverse (mapFrees f)
instance (HasFrees a, HasFrees b) => HasFrees (Either a b) where
foldFrees f = either (foldFrees f) (foldFrees f)
foldFreesOcc f p = either (foldFreesOcc f ("0":p)) (foldFreesOcc f ("1":p))
mapFrees f = either (fmap Left . mapFrees f) (fmap Right . mapFrees f)
instance (HasFrees a, HasFrees b) => HasFrees (a, b) where
foldFrees f (x, y) = foldFrees f x `mappend` foldFrees f y
foldFreesOcc f p (x, y) = foldFreesOcc f ("0":p) x `mappend` foldFreesOcc f ("1":p) y
mapFrees f (x, y) = (,) <$> mapFrees f x <*> mapFrees f y
instance (HasFrees a, HasFrees b, HasFrees c) => HasFrees (a, b, c) where
foldFrees f (x, y, z) = foldFrees f (x, (y, z))
foldFreesOcc f p (x, y, z) =
foldFreesOcc f ("0":p) x `mappend` foldFreesOcc f ("1":p) y `mappend` foldFreesOcc f ("2":p) z
mapFrees f (x0, y0, z0) =
(\(x, (y, z)) -> (x, y, z)) <$> mapFrees f (x0, (y0, z0))
instance (HasFrees a, HasFrees b, HasFrees c, HasFrees d) => HasFrees (a, b, c, d) where
foldFrees f (x, y, z, a) = foldFrees f (x, (y, (z, a)))
foldFreesOcc f p (x, y, z, a) =
foldFreesOcc f ("0":p) x `mappend` foldFreesOcc f ("1":p) y
`mappend` foldFreesOcc f ("2":p) z `mappend` foldFreesOcc f ("3":p) a
mapFrees f (x0, y0, z0, a0) =
(\(x, (y, (z, a))) -> (x, y, z, a)) <$> mapFrees f (x0, (y0, (z0, a0)))
instance HasFrees a => HasFrees [a] where
foldFrees f = foldMap (foldFrees f)
foldFreesOcc f c xs = mconcat $ (map (\(i,x) -> foldFreesOcc f (show i:c) x)) $ zip [(0::Int)..] xs
mapFrees f = traverse (mapFrees f)
instance HasFrees a => HasFrees (Disj a) where
foldFrees f = foldMap (foldFrees f)
foldFreesOcc f p d = foldFreesOcc f p (getDisj d)
mapFrees f = traverse (mapFrees f)
instance HasFrees a => HasFrees (Conj a) where
foldFrees f = foldMap (foldFrees f)
foldFreesOcc f p c = foldFreesOcc f p (getConj c)
mapFrees f = traverse (mapFrees f)
instance (Ord a, HasFrees a) => HasFrees (S.Set a) where
foldFrees f = foldMap (foldFrees f)
foldFreesOcc f p = foldMap (foldFreesOcc f ("0":p))
mapFrees f = fmap S.fromList . mapFrees f . S.toList
instance (Ord k, HasFrees k, HasFrees v) => HasFrees (M.Map k v) where
foldFrees f = M.foldrWithKey combine mempty
where
combine k v m = foldFrees f k `mappend` (foldFrees f v `mappend` m)
foldFreesOcc f p = M.foldrWithKey combine mempty
where
combine k v m = foldFreesOcc f p (k,v) `mappend` m
mapFrees f = fmap M.fromList . mapFrees f . M.toList
------------------------------------------------------------------------------
-- Pretty Printing
------------------------------------------------------------------------------
-- | Pretty print a 'LVar'.
prettyLVar :: Document d => LVar -> d
prettyLVar = text . show
-- | Pretty print a 'NodeId'.
prettyNodeId :: Document d => NodeId -> d
prettyNodeId = text . show
-- | Pretty print an @NTerm@.
prettyNTerm :: (Show v, Document d) => NTerm v -> d
prettyNTerm = prettyTerm (text . show)
-- | Pretty print an @LTerm@.
prettyLNTerm :: Document d => LNTerm -> d
prettyLNTerm = prettyNTerm
-- | Pretty print a literal for case generation.
showLitName :: Lit Name LVar -> String
showLitName (Con (Name FreshName n)) = "Const_fresh_" ++ show n
showLitName (Con (Name PubName n)) = "Const_pub_" ++ show n
showLitName (Var (LVar v s i)) = "Var_" ++ sortSuffix s ++ "_" ++ body
where
body | null v = show i
| i == 0 = v
| otherwise = show i ++ "_" ++ v
| tamarin-prover/tamarin-prover | lib/term/src/Term/LTerm.hs | gpl-3.0 | 29,024 | 0 | 17 | 7,449 | 7,597 | 4,019 | 3,578 | 464 | 6 |
{-
Copyright (C) 2008 John Goerzen <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
import System.Log.Logger
import System.Log.Handler.Simple
import System.IO(stderr)
import System.Console.GetOpt.Utils
import System.Console.GetOpt
import System.Environment
import Data.List
import System.Exit
import Commands
import Control.Monad
import Utils
main =
do updateGlobalLogger "" (setLevel INFO)
argv <- getArgs
let (optargs, commandargs) = span (isPrefixOf "-") argv
case getOpt RequireOrder options optargs of
(o, n, []) -> worker o n commandargs
(_, _, errors) -> usageerror (concat errors) -- ++ usageInfo header options)
options = [Option "d" ["debug"] (NoArg ("d", "")) "Enable debugging",
Option "" ["help"] (NoArg ("help", "")) "Display this help"]
worker args n commandargs =
do when (lookup "help" args == Just "") $ usageerror ""
when (lookup "d" args == Just "")
(updateGlobalLogger "" (setLevel DEBUG))
handler <- streamHandler stderr DEBUG
updateGlobalLogger "" (setHandlers [handler])
let commandname = head cmdargs
case lookup commandname allCommands of
Just command ->
execcmd command (tail cmdargs)
Nothing -> usageerror ("Invalid command name " ++ commandname)
where cmdargs = case commandargs of
[] -> ["INVALID"]
x -> x
usageerror errormsg =
do putStrLn errormsg
putStrLn (usageInfo header options)
putStrLn "Run \"tarf lscommands\" for a list of available commands.\n\
\Run \"tarf command --help\" for help on a particular command.\n"
exitFailure
header = "Usage: tarf [global-options] command [command-options]\n\n\
\Available global-options are:\n"
| jgoerzen/tarfilter | tarf.hs | gpl-3.0 | 2,459 | 0 | 12 | 612 | 475 | 240 | 235 | 40 | 3 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Games.Leaderboards.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists all the leaderboard metadata for your application.
--
-- /See:/ <https://developers.google.com/games/ Google Play Game Services Reference> for @games.leaderboards.list@.
module Network.Google.Resource.Games.Leaderboards.List
(
-- * REST Resource
LeaderboardsListResource
-- * Creating a Request
, leaderboardsList
, LeaderboardsList
-- * Request Lenses
, llXgafv
, llUploadProtocol
, llAccessToken
, llUploadType
, llLanguage
, llPageToken
, llMaxResults
, llCallback
) where
import Network.Google.Games.Types
import Network.Google.Prelude
-- | A resource alias for @games.leaderboards.list@ method which the
-- 'LeaderboardsList' request conforms to.
type LeaderboardsListResource =
"games" :>
"v1" :>
"leaderboards" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "language" Text :>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] LeaderboardListResponse
-- | Lists all the leaderboard metadata for your application.
--
-- /See:/ 'leaderboardsList' smart constructor.
data LeaderboardsList =
LeaderboardsList'
{ _llXgafv :: !(Maybe Xgafv)
, _llUploadProtocol :: !(Maybe Text)
, _llAccessToken :: !(Maybe Text)
, _llUploadType :: !(Maybe Text)
, _llLanguage :: !(Maybe Text)
, _llPageToken :: !(Maybe Text)
, _llMaxResults :: !(Maybe (Textual Int32))
, _llCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LeaderboardsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'llXgafv'
--
-- * 'llUploadProtocol'
--
-- * 'llAccessToken'
--
-- * 'llUploadType'
--
-- * 'llLanguage'
--
-- * 'llPageToken'
--
-- * 'llMaxResults'
--
-- * 'llCallback'
leaderboardsList
:: LeaderboardsList
leaderboardsList =
LeaderboardsList'
{ _llXgafv = Nothing
, _llUploadProtocol = Nothing
, _llAccessToken = Nothing
, _llUploadType = Nothing
, _llLanguage = Nothing
, _llPageToken = Nothing
, _llMaxResults = Nothing
, _llCallback = Nothing
}
-- | V1 error format.
llXgafv :: Lens' LeaderboardsList (Maybe Xgafv)
llXgafv = lens _llXgafv (\ s a -> s{_llXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
llUploadProtocol :: Lens' LeaderboardsList (Maybe Text)
llUploadProtocol
= lens _llUploadProtocol
(\ s a -> s{_llUploadProtocol = a})
-- | OAuth access token.
llAccessToken :: Lens' LeaderboardsList (Maybe Text)
llAccessToken
= lens _llAccessToken
(\ s a -> s{_llAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
llUploadType :: Lens' LeaderboardsList (Maybe Text)
llUploadType
= lens _llUploadType (\ s a -> s{_llUploadType = a})
-- | The preferred language to use for strings returned by this method.
llLanguage :: Lens' LeaderboardsList (Maybe Text)
llLanguage
= lens _llLanguage (\ s a -> s{_llLanguage = a})
-- | The token returned by the previous request.
llPageToken :: Lens' LeaderboardsList (Maybe Text)
llPageToken
= lens _llPageToken (\ s a -> s{_llPageToken = a})
-- | The maximum number of leaderboards to return in the response. For any
-- response, the actual number of leaderboards returned may be less than
-- the specified \`maxResults\`.
llMaxResults :: Lens' LeaderboardsList (Maybe Int32)
llMaxResults
= lens _llMaxResults (\ s a -> s{_llMaxResults = a})
. mapping _Coerce
-- | JSONP
llCallback :: Lens' LeaderboardsList (Maybe Text)
llCallback
= lens _llCallback (\ s a -> s{_llCallback = a})
instance GoogleRequest LeaderboardsList where
type Rs LeaderboardsList = LeaderboardListResponse
type Scopes LeaderboardsList =
'["https://www.googleapis.com/auth/games"]
requestClient LeaderboardsList'{..}
= go _llXgafv _llUploadProtocol _llAccessToken
_llUploadType
_llLanguage
_llPageToken
_llMaxResults
_llCallback
(Just AltJSON)
gamesService
where go
= buildClient
(Proxy :: Proxy LeaderboardsListResource)
mempty
| brendanhay/gogol | gogol-games/gen/Network/Google/Resource/Games/Leaderboards/List.hs | mpl-2.0 | 5,420 | 0 | 19 | 1,333 | 887 | 512 | 375 | 123 | 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.Plus.People.ListByActivity
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Shut down. See https:\/\/developers.google.com\/+\/api-shutdown for more
-- details.
--
-- /See:/ <https://developers.google.com/+/api/ Google+ API Reference> for @plus.people.listByActivity@.
module Network.Google.Resource.Plus.People.ListByActivity
(
-- * REST Resource
PeopleListByActivityResource
-- * Creating a Request
, peopleListByActivity
, PeopleListByActivity
-- * Request Lenses
, plbaActivityId
, plbaCollection
, plbaPageToken
, plbaMaxResults
) where
import Network.Google.Plus.Types
import Network.Google.Prelude
-- | A resource alias for @plus.people.listByActivity@ method which the
-- 'PeopleListByActivity' request conforms to.
type PeopleListByActivityResource =
"plus" :>
"v1" :>
"activities" :>
Capture "activityId" Text :>
"people" :>
Capture "collection" PeopleListByActivityCollection
:>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "alt" AltJSON :> Get '[JSON] PeopleFeed
-- | Shut down. See https:\/\/developers.google.com\/+\/api-shutdown for more
-- details.
--
-- /See:/ 'peopleListByActivity' smart constructor.
data PeopleListByActivity =
PeopleListByActivity'
{ _plbaActivityId :: !Text
, _plbaCollection :: !PeopleListByActivityCollection
, _plbaPageToken :: !(Maybe Text)
, _plbaMaxResults :: !(Textual Word32)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PeopleListByActivity' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plbaActivityId'
--
-- * 'plbaCollection'
--
-- * 'plbaPageToken'
--
-- * 'plbaMaxResults'
peopleListByActivity
:: Text -- ^ 'plbaActivityId'
-> PeopleListByActivityCollection -- ^ 'plbaCollection'
-> PeopleListByActivity
peopleListByActivity pPlbaActivityId_ pPlbaCollection_ =
PeopleListByActivity'
{ _plbaActivityId = pPlbaActivityId_
, _plbaCollection = pPlbaCollection_
, _plbaPageToken = Nothing
, _plbaMaxResults = 20
}
-- | The ID of the activity to get the list of people for.
plbaActivityId :: Lens' PeopleListByActivity Text
plbaActivityId
= lens _plbaActivityId
(\ s a -> s{_plbaActivityId = a})
-- | The collection of people to list.
plbaCollection :: Lens' PeopleListByActivity PeopleListByActivityCollection
plbaCollection
= lens _plbaCollection
(\ s a -> s{_plbaCollection = a})
-- | The continuation token, which is used to page through large result sets.
-- To get the next page of results, set this parameter to the value of
-- \"nextPageToken\" from the previous response.
plbaPageToken :: Lens' PeopleListByActivity (Maybe Text)
plbaPageToken
= lens _plbaPageToken
(\ s a -> s{_plbaPageToken = a})
-- | The maximum number of people to include in the response, which is used
-- for paging. For any response, the actual number returned might be less
-- than the specified maxResults.
plbaMaxResults :: Lens' PeopleListByActivity Word32
plbaMaxResults
= lens _plbaMaxResults
(\ s a -> s{_plbaMaxResults = a})
. _Coerce
instance GoogleRequest PeopleListByActivity where
type Rs PeopleListByActivity = PeopleFeed
type Scopes PeopleListByActivity =
'["https://www.googleapis.com/auth/plus.login",
"https://www.googleapis.com/auth/plus.me"]
requestClient PeopleListByActivity'{..}
= go _plbaActivityId _plbaCollection _plbaPageToken
(Just _plbaMaxResults)
(Just AltJSON)
plusService
where go
= buildClient
(Proxy :: Proxy PeopleListByActivityResource)
mempty
| brendanhay/gogol | gogol-plus/gen/Network/Google/Resource/Plus/People/ListByActivity.hs | mpl-2.0 | 4,632 | 0 | 16 | 1,032 | 560 | 332 | 228 | 90 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.Disks.SetLabels
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Sets the labels on a disk. To learn more about labels, read the Labeling
-- Resources documentation.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.disks.setLabels@.
module Network.Google.Resource.Compute.Disks.SetLabels
(
-- * REST Resource
DisksSetLabelsResource
-- * Creating a Request
, disksSetLabels
, DisksSetLabels
-- * Request Lenses
, dslRequestId
, dslProject
, dslZone
, dslPayload
, dslResource
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.disks.setLabels@ method which the
-- 'DisksSetLabels' request conforms to.
type DisksSetLabelsResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"zones" :>
Capture "zone" Text :>
"disks" :>
Capture "resource" Text :>
"setLabels" :>
QueryParam "requestId" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] ZoneSetLabelsRequest :>
Post '[JSON] Operation
-- | Sets the labels on a disk. To learn more about labels, read the Labeling
-- Resources documentation.
--
-- /See:/ 'disksSetLabels' smart constructor.
data DisksSetLabels =
DisksSetLabels'
{ _dslRequestId :: !(Maybe Text)
, _dslProject :: !Text
, _dslZone :: !Text
, _dslPayload :: !ZoneSetLabelsRequest
, _dslResource :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'DisksSetLabels' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dslRequestId'
--
-- * 'dslProject'
--
-- * 'dslZone'
--
-- * 'dslPayload'
--
-- * 'dslResource'
disksSetLabels
:: Text -- ^ 'dslProject'
-> Text -- ^ 'dslZone'
-> ZoneSetLabelsRequest -- ^ 'dslPayload'
-> Text -- ^ 'dslResource'
-> DisksSetLabels
disksSetLabels pDslProject_ pDslZone_ pDslPayload_ pDslResource_ =
DisksSetLabels'
{ _dslRequestId = Nothing
, _dslProject = pDslProject_
, _dslZone = pDslZone_
, _dslPayload = pDslPayload_
, _dslResource = pDslResource_
}
-- | An optional request ID to identify requests. Specify a unique request ID
-- so that if you must retry your request, the server will know to ignore
-- the request if it has already been completed. For example, consider a
-- situation where you make an initial request and the request times out.
-- If you make the request again with the same request ID, the server can
-- check if original operation with the same request ID was received, and
-- if so, will ignore the second request. This prevents clients from
-- accidentally creating duplicate commitments. The request ID must be a
-- valid UUID with the exception that zero UUID is not supported
-- (00000000-0000-0000-0000-000000000000).
dslRequestId :: Lens' DisksSetLabels (Maybe Text)
dslRequestId
= lens _dslRequestId (\ s a -> s{_dslRequestId = a})
-- | Project ID for this request.
dslProject :: Lens' DisksSetLabels Text
dslProject
= lens _dslProject (\ s a -> s{_dslProject = a})
-- | The name of the zone for this request.
dslZone :: Lens' DisksSetLabels Text
dslZone = lens _dslZone (\ s a -> s{_dslZone = a})
-- | Multipart request metadata.
dslPayload :: Lens' DisksSetLabels ZoneSetLabelsRequest
dslPayload
= lens _dslPayload (\ s a -> s{_dslPayload = a})
-- | Name or id of the resource for this request.
dslResource :: Lens' DisksSetLabels Text
dslResource
= lens _dslResource (\ s a -> s{_dslResource = a})
instance GoogleRequest DisksSetLabels where
type Rs DisksSetLabels = Operation
type Scopes DisksSetLabels =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient DisksSetLabels'{..}
= go _dslProject _dslZone _dslResource _dslRequestId
(Just AltJSON)
_dslPayload
computeService
where go
= buildClient (Proxy :: Proxy DisksSetLabelsResource)
mempty
| brendanhay/gogol | gogol-compute/gen/Network/Google/Resource/Compute/Disks/SetLabels.hs | mpl-2.0 | 5,068 | 0 | 19 | 1,216 | 638 | 380 | 258 | 96 | 1 |
module MapJoin where
import Data.Maybe
import Data.Map (Map)
import qualified Data.Map as Map
naturalJoin, (⋈) :: Ord k => Map k a -> Map k b -> Map k (a,b)
leftSemiJoin, (⋉) :: Ord k => Map k a -> Map k b -> Map k a
rightSemiJoin, (⋊) :: Ord k => Map k a -> Map k b -> Map k b
leftOuterJoin, (⟕) :: Ord k => Map k a -> Map k b -> Map k (Maybe a,b)
rightOuterJoin, (⟖) :: Ord k => Map k a -> Map k b -> Map k (a,Maybe b)
fullOuterJoin, (⟗) :: Ord k => Map k a -> Map k b -> Map k (Maybe a,Maybe b)
naturalJoin l r = Map.intersectionWith (,) l r
leftSemiJoin = Map.intersection
rightSemiJoin = Map.intersectionWith (flip const)
leftOuterJoin l r = Map.mapWithKey (\k x -> (Map.lookup k l, x)) r
rightOuterJoin l r = Map.mapWithKey (\k x -> (x, Map.lookup k r)) l
fullOuterJoin l r = let
l' = Map.map (\a -> (Just a, Nothing)) l
r' = Map.map (\a -> (Nothing, Just a)) r
in
Map.unionWith (\(a, _) (_, b) -> (a, b)) l' r'
-- \Join
(⋈) = naturalJoin
-- \ltimes
(⋉) = leftSemiJoin
-- \rtimes
(⋊) = rightSemiJoin
-- \leftouterjoin
(⟕) = leftOuterJoin
-- \rightouterjoin
(⟖) = rightOuterJoin
-- \fullouterjoin
(⟗) = fullOuterJoin
| DanielG/kvm-in-a-box | src/MapJoin.hs | agpl-3.0 | 1,184 | 0 | 13 | 263 | 581 | 320 | 261 | 25 | 1 |
module MAC (MAC, enumerateMACs, showMAC, readMAC, nullMAC, toModifiedEUI64) where
import GHC.Generics
import Control.DeepSeq
import Control.Arrow
import Numeric
import Data.Bits
import Data.Word
import Data.List
import Data.List.Split
import Data.Function
import Safe
import BitUtils
import Read
newtype MAC = MAC [Word8]
deriving (Eq, Ord, Generic)
instance Show MAC where
show = showMAC
instance Read MAC where
readsPrec i = \s -> map (first readMAC) $ (readsPrec i :: ReadS String) s
instance NFData MAC
enumerateMACs :: MAC -> [MAC]
enumerateMACs (MAC bs) = let
x = mergeWords bs :: Word64
in
genericTake (2^(8*6) - x) $ map (MAC . drop 2 . splitWord) $ enumIntegral x
showMAC :: MAC -> String
showMAC (MAC ws) = intercalate ":" $ map (fill . flip showHex "") ws
where
fill s | length s == 1 = '0':s
fill s = s
readMAC :: String -> MAC
readMAC str = MAC $ map (unHex . readNote "readMAC") $ splitOn ":" str
nullMAC = readMAC "02:00:00:00:00:00"
toModifiedEUI64 :: MAC -> (Word32, Word32)
toModifiedEUI64 (MAC (map fromIntegral -> [a,b,c, d,e,f])) =
let a' = a `xor` 0x80 in
( (a' `shift` 24) .|.
(b `shift` 16) .|.
(c `shift` 8) .|.
0xff
, (d `shift` 24) .|.
(e `shift` 16) .|.
(f `shift` 8) .|.
0xff
)
| DanielG/kvm-in-a-box | src/MAC.hs | agpl-3.0 | 1,306 | 0 | 14 | 308 | 555 | 302 | 253 | -1 | -1 |
module Haskell.Codewars.LuckyNumbers where
filterLucky :: [Int] -> [Int]
filterLucky = filter (\x -> elem '7' $ show x)
| ice1000/OI-codes | codewars/1-100/find-the-lucky-numbers.hs | agpl-3.0 | 121 | 0 | 9 | 19 | 48 | 27 | 21 | 3 | 1 |
import System.Plugins.Eval
main = do r <- eval "map toUpper \"haskell\"" ["Data.Char"]
either putStrLn putStrLn r
| Changaco/haskell-plugins | testsuite/eval/eval2/Main.hs | lgpl-2.1 | 125 | 0 | 9 | 27 | 37 | 18 | 19 | 3 | 1 |
diffHam :: (Integral a) => a -> a -> a
diffHam a b
| a == 0 && b == 0 = 0
| otherwise = let rr = if (mod a 2) /= (mod b 2)
then 1
else 0
in rr + diffHam (div a 2) (div b 2)
totalHammingDistance :: (Integral a) => [a] -> a
totalHammingDistance [] = 0
totalHammingDistance (x:xs) = (sum $ map (diffHam x) xs) + totalHammingDistance xs
| ccqpein/Arithmetic-Exercises | Total-Hamming-Distance/THD.hs | apache-2.0 | 402 | 0 | 13 | 144 | 195 | 98 | 97 | 10 | 2 |
import Text.CSV
import Data.List as L
import Text.Nagato.NagatoIO as NagatoIO
import Text.Nagato.Models as Models
import Text.Nagato.MeCabTools as MeCabTools
import qualified Text.Nagato.Classify as NC
import qualified Text.Nagato.Train as Train
import qualified Text.Nagato.Train_complement as Train_compl
main = do
rawCsvData <- NagatoIO.loadCSVFileUtf8 "testData.csv"
let csvData = init rawCsvData
classes <- NagatoIO.readFromFile "classes.bin"
classesComplement <- NagatoIO.readFromFile "complementClasses.bin"
print $ fst $ unzip classes
print $ fst $ unzip classesComplement
classed <- mapM (\x->test (head x) classes classesComplement) csvData
let compared = unzip $ map (\a -> judge a) $ zip [a !! 1 | a <- csvData] classed
let accuracyNormal = (realToFrac (length (filter (==True) (fst compared)))) / (realToFrac (length csvData))
let accuracyComplement = (realToFrac (length (filter (==True) (snd compared)))) / (realToFrac (length csvData))
putStrLn "normal:"
print accuracyNormal
putStrLn "complement:"
print accuracyComplement
judge :: (String, (String, String)) -> (Bool, Bool)
judge item =
let trueAnswer = fst item
answers = snd item
in ((trueAnswer == (fst answers)),(trueAnswer == (snd answers )))
test :: String -> [(String, Props)] -> [(String, Props)] -> IO(String, String)
test text classNormal classComplement = do
wakati <- MeCabTools.parseWakati text
let wordList = words wakati
return ((NC.classify wordList classNormal), (NC.classifyComplement wordList classComplement))
trainAndSaveFromSetting :: String -> String -> IO()
trainAndSaveFromSetting settingFile saveFileName = do
trainResult <- trainFromSetting settingFile
NagatoIO.writeToFile saveFileName trainResult
trainFromSetting :: String -> IO [(String, Props)]
trainFromSetting settingFileName = do
classesList <- loadSettings settingFileName
let unzippedClasses = unzip classesList
classStrings <- loadClassStrings $ snd unzippedClasses
classesTrained <- mapM (\a -> Train.parseAndTrainClass a) classStrings
return $ zip (fst unzippedClasses) classesTrained
doTrainNormal :: String -> IO()
doTrainNormal settingName = trainAndSaveFromSetting settingName "classes.bin"
doTrainComplemnt :: String -> IO()
doTrainComplemnt settingName = doTrainCompl settingName "classes_complement.bin"
loadClassStrings :: [String] -> IO [String]
loadClassStrings settingFiles = do
if length settingFiles == 1
then do
str <- NagatoIO.loadPlainText $ head settingFiles
return [str]
else do
str <- NagatoIO.loadPlainText $ head settingFiles
deepStrs <- loadClassStrings $ drop 1 settingFiles
return $ str : deepStrs
doTrainCompl :: String -> String -> IO()
doTrainCompl settingFile saveFileName = do
counted <- countFromSetting settingFile
let complementCounts = L.map (\classItems -> ((fst classItems), (Train_compl.makeComplementClass (snd counted)))) counted
NagatoIO.writeToFile saveFileName complementCounts
countFromSetting :: String -> IO [(String, Freqs)]
countFromSetting settingFileName = do
classesList <- loadSettings settingFileName
let unzippedClasses = unzip classesList
classStrings <- loadClassStrings $ snd unzippedClasses
classesCounted <- mapM (\a -> Train.parseAndCountClass a) classStrings
return $ zip (fst unzippedClasses) classesCounted
loadSettings :: String -> IO [(String, String)]
loadSettings settingName = do
eitherCsv <- parseCSVFromFile settingName
case eitherCsv of
Right csv' -> return $ L.map (\x -> (x !! 0, x !! 1)) $ init csv'
Left e -> error $ show e
| haru2036/nagato | samples/tester.hs | apache-2.0 | 3,593 | 0 | 18 | 568 | 1,201 | 599 | 602 | 76 | 2 |
import Data.Set (Set)
import qualified Data.Set as Set
-- See TorusLatticeWalk.hs, this is mostly copied and pasted from there with
-- some changes to nextStatesRight and nextStatesUp
-- Notes: I can prove that the number of all cylinder walks is w^h where w is
-- the width, and h is the right. (At each height, take 0, 1, ..., w-1) steps,
-- at the final height, there's only one choice to make.
-- I believe that the maximum number of steps from (0,0) to (0, h) is w*h + (h % w).
-- The main diagonal and off-diagonals seem to have nice structure when counting
-- maximal walks.
-- n x n torus (A324603)
-- n x m torus (A324604)
-- n x m torus steps in maximal walk (A306779)
-- n x m torus number of maximal walks (A324605)
-- n x n torus maximal (A056188?)
-- n x n torus up >= right (A324606)
-- n x m torus up >= right (A324607)
-- n x n torus up > right (A324608)
-- n x n cylinder
-- n x m cylinder
-- n x n cylinder maximal
-- n x m cylinder maximal
-- n x n cylinder up > right
-- n x m cylinder up > right
data CurrentState = Intersected | Completed (Set Position) | Ongoing State deriving (Show, Eq)
type Position = (Int, Int)
type State = (Position, Set Position)
maximalCylinderWalks n m = recurse [] [Ongoing ((0, 0), Set.singleton (0,0))] where
recurse completedWalks [] = completedWalks
recurse completedWalks ongoingStates = recurse completedWalks' ongoingStates' where
nextStates = concatMap (\s -> [nextStatesRight n m s, nextStatesUp m s]) ongoingStates
ongoingStates' = filter isOngoing nextStates
completedWalks' = if null cW then completedWalks else cW where
cW = filter isCompleted nextStates
allCylinderWalks n m = recurse [] [Ongoing ((0, 0), Set.singleton (0,0))] where
recurse completedWalks [] = completedWalks
recurse completedWalks ongoingStates = recurse completedWalks' ongoingStates' where
nextStates = concatMap (\s -> [nextStatesRight n m s, nextStatesUp m s]) ongoingStates
ongoingStates' = filter isOngoing nextStates
completedWalks' = completedWalks ++ filter isCompleted nextStates
nextStatesRight :: Int -> Int -> CurrentState -> CurrentState
nextStatesRight width height (Ongoing ((x, y), pastPositions))
| newPosition == (0, height) = Completed pastPositions
| newPosition `elem` pastPositions = Intersected
| otherwise = Ongoing (newPosition, Set.insert newPosition pastPositions) where
newPosition = ((x + 1) `mod` width, y)
nextStatesUp :: Int -> CurrentState -> CurrentState
nextStatesUp height (Ongoing ((x, y), pastPositions))
| newPosition == (0, height) = Completed pastPositions
| y == height = Intersected
| newPosition `elem` pastPositions = Intersected
| otherwise = Ongoing (newPosition, Set.insert newPosition pastPositions) where
newPosition = (x, y + 1)
isCompleted :: CurrentState -> Bool
isCompleted (Completed _) = True
isCompleted _ = False
isOngoing :: CurrentState -> Bool
isOngoing (Ongoing _) = True
isOngoing _ = False
-- n x n torus
-- n x m torus
-- n x m torus size of maximal walk
-- n x m torus number of maximal walks
-- * n x n torus maximal
-- n x m torus maximal
-- n x n torus up > right
-- n x m torus up > right
-- n x n cylinder
-- n x m cylinder
-- n x n cylinder maximal
-- n x m cylinder maximal
-- n x n cylinder up > right
-- n x m cylinder up > right
stepCount :: CurrentState -> Int
stepCount Intersected = error "Intersected"
stepCount (Ongoing _) = error "Ongoing!"
stepCount (Completed steps) = length steps
| peterokagey/haskellOEIS | src/Sandbox/CylinderLatticeWalk.hs | apache-2.0 | 3,524 | 0 | 13 | 708 | 782 | 431 | 351 | 41 | 3 |
module Arbitrary.File where
import Test.QuickCheck
--import qualified Data.Test as T
import Filesystem.Path.CurrentOS
import Prelude hiding (FilePath, writeFile)
import qualified Data.Set as S
import Control.Applicative
import Data.ModulePath
import Control.Lens
import Arbitrary.TestModule (toGenerated, testModulePath)
import Arbitrary.FilePath
import Arbitrary.Properties
import Language.Haskell.Exts
import Language.Haskell.Exts.SrcLoc (noLoc)
import Data.Integrated.TestModule
import qualified Data.List as L
import qualified Data.Property as P
import Control.Monad.State
isTest :: Content -> Bool
isTest (Left _) = True
isTest _ = False
type Nonsense = String
type Content = Either TestModule Nonsense
data File = File { path :: FilePath, content :: Content }
instance Show File where
show (File p (Left t)) = show p ++ ": \n" ++ show t
show (File p (Right n)) = show p ++ ": \n" ++ show n
toStr :: TestModule -> String
toStr tm =
prettyPrint (toModule [] $ view modpath tm) ++ '\n' : append_properties_buf
where
append_properties_buf :: String
append_properties_buf =
L.intercalate "\n" . map (\f -> P.func f ++ " = undefined") $
view properties tm
-- Note, Nonsense can contain erroneously test data
-- or have a test like path with erroneous data
nonSenseGen :: Gen Char -> S.Set FilePath -> Gen File
nonSenseGen subpath avoided =
(\(p,b) -> File p (Right b)) <$>
frequency [ (1, testModule), (2, fakeModule), (2, nonModule) ]
where
testModule,fakeModule,nonModule :: Gen (FilePath, String)
testModule = do -- This case should fail gracefully.
mp <- testModulePath subpath S.empty
buf <- oneof [ garbageBuf, testBuf mp ]
return (relPath mp, buf)
fakeModule = do
mp <- suchThat arbitrary (not . flip S.member avoided . relPath)
buf <- oneof [ testBuf mp, moduleBuf mp ]
return (relPath mp, buf)
nonModule = liftM2 (,) (filepathGen subpath) garbageBuf
moduleBuf,testBuf :: ModulePath -> Gen String
testBuf mp = toStr . TestModule mp . list <$> (arbitrary :: Gen Properties)
moduleBuf mp =
return . prettyPrint $
Module noLoc (ModuleName $ show mp) [] Nothing Nothing [] []
garbageBuf :: Gen String
garbageBuf = return "Nonsense"
fileGen :: Gen Char -> StateT (S.Set FilePath, S.Set ModulePath) Gen File
fileGen subpath = do
test <- lift $ choose (True, False)
if test
then do
avoided <- snd <$> get
(fp, tm) <- lift $ toGenerated subpath avoided
modify
(\t -> (S.insert fp . fst $ t, S.insert (view modpath tm) . snd $ t))
return $ File fp (Left tm)
else do
avoided <- fst <$> get
f <- lift $ nonSenseGen subpath avoided
modify (over _1 (S.insert (path f)))
return f
| jfeltz/tasty-integrate | tests/Arbitrary/File.hs | bsd-2-clause | 2,787 | 0 | 18 | 622 | 977 | 512 | 465 | 69 | 2 |
module Ovid.Prelude
( JsCFAState (..)
, CFAOpts (..)
, emptyCFAOpts
, message
, warnAt
, enableUnlimitedRecursion, enablePreciseArithmetic, enablePreciseConditionals
-- source positions
, SourcePos, sourceName
-- Monads
, module Control.Monad
, module Control.Monad.Trans
, module Control.Monad.Identity
, lift2, lift3
-- module Control.Monad.State.Strict
, MonadState (..), StateT, runStateT, evalStateT
-- lists, numbers, etc
,tryInt, L.intersperse, L.isInfixOf, L.isPrefixOf, L.partition
-- others
, isJust, fromJust
, module Scheme.Write
-- Data.Traversable
, forM -- Traversable.mapM with arguments flipped; avoid conflicts with Prelude.mapM
, module Framework
-- exceptions
, try, catch, IOException
) where
import Prelude hiding (catch)
import Scheme.Write
import Text.ParserCombinators.Parsec.Pos (SourcePos, sourceName)
import Control.Monad hiding (mapM,forM)
import Control.Monad.Trans
import Control.Monad.Identity (Identity, runIdentity)
import Control.Monad.State.Strict (StateT,runStateT,evalStateT,get,put,MonadState)
import qualified System.IO as IO
import Data.Maybe
import qualified Data.List as L
import Numeric
import Framework
import Data.Traversable (forM)
import Control.Exception
import CFA.Labels (Label)
import qualified Data.Map as M
message :: MonadIO m => String -> m ()
message s = liftIO (IO.hPutStrLn IO.stdout s)
warnAt str loc = do
let sLen = length str
let truncLoc = take (80 - sLen - 7) loc
warn $ str ++ " (at " ++ truncLoc ++ ")"
lift2 m = lift (lift m)
lift3 m = lift (lift2 m)
tryInt :: String -> Maybe Int
tryInt s = case readDec s of
[(n,"")] -> Just n
otherwise -> Nothing
-- ---------------------------------------------------------------------------------------------------------------------
data JsCFAState ct = JsCFAState {
xhrSend :: Maybe Label,
jscfasBuiltins :: M.Map String Label,
-- ^function sets passed to 'application'. Verify that they have at least one function and hopefully no more than
-- one function.
jscfaFns :: [(Label,ct)],
jscfaBranches :: [(Label,ct)],
jscfaOpts :: CFAOpts,
jscfaGlobals :: [Label] -- ^list of globals; this is augmented as JavaScript is dynamically loaded
}
--------------------------------------------------------------------------------
-- Options that affect the analysis
-- |Options that control the analysis
data CFAOpts = CFAOpts {
-- |A recursive function take time exponential (in the number of syntactic
-- recursive calls) to analyze. This behavior is also observable for
-- mutually recursive functions. By default, the analysis detects this
-- behavior and halts early. However, this can break certain libraries
-- such as Flapjax.
cfaOptUnlimitedRecursion :: [String],
-- |By default, we do not perform primitive arithmetic operations. Instead,
-- their results are approximated by 'AnyNum'. However, this approximation
-- can break common implementations of library functions, such as the
-- functions in the Flapjax library.
cfaOptsPreciseArithmetic :: [String],
-- |The analysis disregards the test expression in conditionals by default.
cfaOptsPreciseConditionals :: [String]
} deriving (Show)
-- |No options specified. These are effectively "defaults." By default,
-- "flapjax/flapjax.js" and "../flapjax/flapjax.js" are permitted to
-- recurse exponentially. However, in practice, this does not happen, but
-- just allows combinators from flapjax.js to weave through application-specific
-- code.
emptyCFAOpts :: CFAOpts
emptyCFAOpts =
CFAOpts ["flapjax/flapjax.js","../flapjax/flapjax.js","DOM.js"]
["flapjax/flapjax.js","../flapjax/flapjax.js","DOM.js"]
["flapjax/flapjax.js","../flapjax/flapjax.js","DOM.js"]
updateCFAOpts :: (CFAOpts -> CFAOpts) -> JsCFAState ct -> JsCFAState ct
updateCFAOpts f st@JsCFAState{jscfaOpts=opts} = st{jscfaOpts=f opts}
enableUnlimitedRecursion path =
updateCFAOpts $ \opts -> opts { cfaOptUnlimitedRecursion = path:(cfaOptUnlimitedRecursion opts) }
enablePreciseArithmetic path =
updateCFAOpts $ \opts -> opts { cfaOptsPreciseArithmetic = path:(cfaOptsPreciseArithmetic opts) }
enablePreciseConditionals path =
updateCFAOpts $ \opts -> opts { cfaOptsPreciseConditionals = path:(cfaOptsPreciseConditionals opts) }
| brownplt/ovid | src/Ovid/Prelude.hs | bsd-2-clause | 4,321 | 0 | 13 | 686 | 842 | 506 | 336 | 72 | 2 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QTreeWidget_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:27
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QTreeWidget_h where
import Foreign.C.Types
import Qtc.Enums.Base
import Qtc.Enums.Gui.QItemSelectionModel
import Qtc.Enums.Gui.QAbstractItemView
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Enums.Gui.QAbstractItemDelegate
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui_h
import Qtc.ClassTypes.Gui
import Foreign.Marshal.Array
instance QunSetUserMethod (QTreeWidget ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTreeWidget_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QTreeWidget_unSetUserMethod" qtc_QTreeWidget_unSetUserMethod :: Ptr (TQTreeWidget a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QTreeWidgetSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTreeWidget_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QTreeWidget ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTreeWidget_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QTreeWidgetSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTreeWidget_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QTreeWidget ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTreeWidget_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QTreeWidgetSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTreeWidget_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QTreeWidget ()) (QTreeWidget x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QTreeWidget setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QTreeWidget_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QTreeWidget_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setUserMethod" qtc_QTreeWidget_setUserMethod :: Ptr (TQTreeWidget a) -> CInt -> Ptr (Ptr (TQTreeWidget x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QTreeWidget :: (Ptr (TQTreeWidget x0) -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QTreeWidget_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QTreeWidgetSc a) (QTreeWidget x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QTreeWidget setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QTreeWidget_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QTreeWidget_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QTreeWidget ()) (QTreeWidget x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QTreeWidget setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QTreeWidget_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QTreeWidget_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setUserMethodVariant" qtc_QTreeWidget_setUserMethodVariant :: Ptr (TQTreeWidget a) -> CInt -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QTreeWidget :: (Ptr (TQTreeWidget x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QTreeWidget_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QTreeWidgetSc a) (QTreeWidget x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QTreeWidget setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QTreeWidget_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QTreeWidget_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QTreeWidget ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QTreeWidget_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QTreeWidget_unSetHandler" qtc_QTreeWidget_unSetHandler :: Ptr (TQTreeWidget a) -> CWString -> IO (CBool)
instance QunSetHandler (QTreeWidgetSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QTreeWidget_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler1" qtc_QTreeWidget_setHandler1 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget1 :: (Ptr (TQTreeWidget x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQEvent t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QdropEvent_h (QTreeWidget ()) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dropEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_dropEvent" qtc_QTreeWidget_dropEvent :: Ptr (TQTreeWidget a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent_h (QTreeWidgetSc a) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dropEvent cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QTreeWidgetItem t1 -> Int -> QObject t3 -> DropAction -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQTreeWidgetItem t1) -> CInt -> Ptr (TQObject t3) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2 x3 x4
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let x2int = fromCInt x2
x3obj <- qObjectFromPtr x3
let x4enum = qEnum_fromInt $ fromCLong x4
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2int x3obj x4enum
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler2" qtc_QTreeWidget_setHandler2 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQTreeWidgetItem t1) -> CInt -> Ptr (TQObject t3) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget2 :: (Ptr (TQTreeWidget x0) -> Ptr (TQTreeWidgetItem t1) -> CInt -> Ptr (TQObject t3) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQTreeWidgetItem t1) -> CInt -> Ptr (TQObject t3) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QTreeWidgetItem t1 -> Int -> QObject t3 -> DropAction -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQTreeWidgetItem t1) -> CInt -> Ptr (TQObject t3) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2 x3 x4
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let x2int = fromCInt x2
x3obj <- qObjectFromPtr x3
let x4enum = qEnum_fromInt $ fromCLong x4
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2int x3obj x4enum
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QdropMimeData_h (QTreeWidget ()) ((QTreeWidgetItem t1, Int, QMimeData t3, DropAction)) where
dropMimeData_h x0 (x1, x2, x3, x4)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_dropMimeData cobj_x0 cobj_x1 (toCInt x2) cobj_x3 (toCLong $ qEnum_toInt x4)
foreign import ccall "qtc_QTreeWidget_dropMimeData" qtc_QTreeWidget_dropMimeData :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> CInt -> Ptr (TQMimeData t3) -> CLong -> IO CBool
instance QdropMimeData_h (QTreeWidgetSc a) ((QTreeWidgetItem t1, Int, QMimeData t3, DropAction)) where
dropMimeData_h x0 (x1, x2, x3, x4)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_dropMimeData cobj_x0 cobj_x1 (toCInt x2) cobj_x3 (toCLong $ qEnum_toInt x4)
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler3" qtc_QTreeWidget_setHandler3 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget3 :: (Ptr (TQTreeWidget x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qevent_h (QTreeWidget ()) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_event cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_event" qtc_QTreeWidget_event :: Ptr (TQTreeWidget a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent_h (QTreeWidgetSc a) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_event cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> IO (DropActions)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO (CLong)
setHandlerWrapper x0
= do x0obj <- qTreeWidgetFromPtr x0
let rv =
if (objectIsNull x0obj)
then withQFlagsResult $ return $ toCLong 0
else _handler x0obj
rvf <- rv
return (toCLong $ qFlags_toInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler4" qtc_QTreeWidget_setHandler4 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> IO (CLong)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget4 :: (Ptr (TQTreeWidget x0) -> IO (CLong)) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> IO (CLong)))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> IO (DropActions)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO (CLong)
setHandlerWrapper x0
= do x0obj <- qTreeWidgetFromPtr x0
let rv =
if (objectIsNull x0obj)
then withQFlagsResult $ return $ toCLong 0
else _handler x0obj
rvf <- rv
return (toCLong $ qFlags_toInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsupportedDropActions_h (QTreeWidget ()) (()) where
supportedDropActions_h x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_supportedDropActions cobj_x0
foreign import ccall "qtc_QTreeWidget_supportedDropActions" qtc_QTreeWidget_supportedDropActions :: Ptr (TQTreeWidget a) -> IO CLong
instance QsupportedDropActions_h (QTreeWidgetSc a) (()) where
supportedDropActions_h x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_supportedDropActions cobj_x0
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QModelIndex t1 -> QModelIndex t2 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler5" qtc_QTreeWidget_setHandler5 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget5 :: (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QModelIndex t1 -> QModelIndex t2 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QdataChanged_h (QTreeWidget ()) ((QModelIndex t1, QModelIndex t2)) where
dataChanged_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTreeWidget_dataChanged cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QTreeWidget_dataChanged" qtc_QTreeWidget_dataChanged :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO ()
instance QdataChanged_h (QTreeWidgetSc a) ((QModelIndex t1, QModelIndex t2)) where
dataChanged_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTreeWidget_dataChanged cobj_x0 cobj_x1 cobj_x2
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO ()
setHandlerWrapper x0
= do x0obj <- qTreeWidgetFromPtr x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler6" qtc_QTreeWidget_setHandler6 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget6 :: (Ptr (TQTreeWidget x0) -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO ()
setHandlerWrapper x0
= do x0obj <- qTreeWidgetFromPtr x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QdoItemsLayout_h (QTreeWidget ()) (()) where
doItemsLayout_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_doItemsLayout cobj_x0
foreign import ccall "qtc_QTreeWidget_doItemsLayout" qtc_QTreeWidget_doItemsLayout :: Ptr (TQTreeWidget a) -> IO ()
instance QdoItemsLayout_h (QTreeWidgetSc a) (()) where
doItemsLayout_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_doItemsLayout cobj_x0
instance QdragMoveEvent_h (QTreeWidget ()) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dragMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_dragMoveEvent" qtc_QTreeWidget_dragMoveEvent :: Ptr (TQTreeWidget a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent_h (QTreeWidgetSc a) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dragMoveEvent cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QPainter t1 -> QRect t2 -> QModelIndex t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQPainter t1) -> Ptr (TQRect t2) -> Ptr (TQModelIndex t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
x3obj <- objectFromPtr_nf x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler7" qtc_QTreeWidget_setHandler7 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQPainter t1) -> Ptr (TQRect t2) -> Ptr (TQModelIndex t3) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget7 :: (Ptr (TQTreeWidget x0) -> Ptr (TQPainter t1) -> Ptr (TQRect t2) -> Ptr (TQModelIndex t3) -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQPainter t1) -> Ptr (TQRect t2) -> Ptr (TQModelIndex t3) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QPainter t1 -> QRect t2 -> QModelIndex t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQPainter t1) -> Ptr (TQRect t2) -> Ptr (TQModelIndex t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
x3obj <- objectFromPtr_nf x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqdrawBranches_h (QTreeWidget ()) ((QPainter t1, QRect t2, QModelIndex t3)) where
qdrawBranches_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_drawBranches cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QTreeWidget_drawBranches" qtc_QTreeWidget_drawBranches :: Ptr (TQTreeWidget a) -> Ptr (TQPainter t1) -> Ptr (TQRect t2) -> Ptr (TQModelIndex t3) -> IO ()
instance QqdrawBranches_h (QTreeWidgetSc a) ((QPainter t1, QRect t2, QModelIndex t3)) where
qdrawBranches_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_drawBranches cobj_x0 cobj_x1 cobj_x2 cobj_x3
instance QdrawBranches_h (QTreeWidget ()) ((QPainter t1, Rect, QModelIndex t3)) where
drawBranches_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCRect x2 $ \crect_x2_x crect_x2_y crect_x2_w crect_x2_h ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_drawBranches_qth cobj_x0 cobj_x1 crect_x2_x crect_x2_y crect_x2_w crect_x2_h cobj_x3
foreign import ccall "qtc_QTreeWidget_drawBranches_qth" qtc_QTreeWidget_drawBranches_qth :: Ptr (TQTreeWidget a) -> Ptr (TQPainter t1) -> CInt -> CInt -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO ()
instance QdrawBranches_h (QTreeWidgetSc a) ((QPainter t1, Rect, QModelIndex t3)) where
drawBranches_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCRect x2 $ \crect_x2_x crect_x2_y crect_x2_w crect_x2_h ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_drawBranches_qth cobj_x0 cobj_x1 crect_x2_x crect_x2_y crect_x2_w crect_x2_h cobj_x3
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QPainter t1 -> QStyleOption t2 -> QModelIndex t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
x3obj <- objectFromPtr_nf x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler8" qtc_QTreeWidget_setHandler8 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget8 :: (Ptr (TQTreeWidget x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QPainter t1 -> QStyleOption t2 -> QModelIndex t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
x3obj <- objectFromPtr_nf x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QdrawRow_h (QTreeWidget ()) ((QPainter t1, QStyleOptionViewItem t2, QModelIndex t3)) where
drawRow_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_drawRow cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QTreeWidget_drawRow" qtc_QTreeWidget_drawRow :: Ptr (TQTreeWidget a) -> Ptr (TQPainter t1) -> Ptr (TQStyleOptionViewItem t2) -> Ptr (TQModelIndex t3) -> IO ()
instance QdrawRow_h (QTreeWidgetSc a) ((QPainter t1, QStyleOptionViewItem t2, QModelIndex t3)) where
drawRow_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_drawRow cobj_x0 cobj_x1 cobj_x2 cobj_x3
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qTreeWidgetFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler9" qtc_QTreeWidget_setHandler9 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget9 :: (Ptr (TQTreeWidget x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qTreeWidgetFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QhorizontalOffset_h (QTreeWidget ()) (()) where
horizontalOffset_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_horizontalOffset cobj_x0
foreign import ccall "qtc_QTreeWidget_horizontalOffset" qtc_QTreeWidget_horizontalOffset :: Ptr (TQTreeWidget a) -> IO CInt
instance QhorizontalOffset_h (QTreeWidgetSc a) (()) where
horizontalOffset_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_horizontalOffset cobj_x0
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QPoint t1 -> IO (QModelIndex t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex t0))
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler10" qtc_QTreeWidget_setHandler10 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget10 :: (Ptr (TQTreeWidget x0) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex t0))) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex t0))))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QPoint t1 -> IO (QModelIndex t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex t0))
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QindexAt_h (QTreeWidget ()) ((Point)) where
indexAt_h x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QTreeWidget_indexAt_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QTreeWidget_indexAt_qth" qtc_QTreeWidget_indexAt_qth :: Ptr (TQTreeWidget a) -> CInt -> CInt -> IO (Ptr (TQModelIndex ()))
instance QindexAt_h (QTreeWidgetSc a) ((Point)) where
indexAt_h x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QTreeWidget_indexAt_qth cobj_x0 cpoint_x1_x cpoint_x1_y
instance QqindexAt_h (QTreeWidget ()) ((QPoint t1)) where
qindexAt_h x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_indexAt cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_indexAt" qtc_QTreeWidget_indexAt :: Ptr (TQTreeWidget a) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex ()))
instance QqindexAt_h (QTreeWidgetSc a) ((QPoint t1)) where
qindexAt_h x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_indexAt cobj_x0 cobj_x1
instance QkeyPressEvent_h (QTreeWidget ()) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_keyPressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_keyPressEvent" qtc_QTreeWidget_keyPressEvent :: Ptr (TQTreeWidget a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent_h (QTreeWidgetSc a) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_keyPressEvent cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> String -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQString ()) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1str <- stringFromPtr x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1str
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler11" qtc_QTreeWidget_setHandler11 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQString ()) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget11 :: (Ptr (TQTreeWidget x0) -> Ptr (TQString ()) -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQString ()) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget11_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> String -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQString ()) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1str <- stringFromPtr x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1str
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QkeyboardSearch_h (QTreeWidget ()) ((String)) where
keyboardSearch_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTreeWidget_keyboardSearch cobj_x0 cstr_x1
foreign import ccall "qtc_QTreeWidget_keyboardSearch" qtc_QTreeWidget_keyboardSearch :: Ptr (TQTreeWidget a) -> CWString -> IO ()
instance QkeyboardSearch_h (QTreeWidgetSc a) ((String)) where
keyboardSearch_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTreeWidget_keyboardSearch cobj_x0 cstr_x1
instance QmouseDoubleClickEvent_h (QTreeWidget ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mouseDoubleClickEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_mouseDoubleClickEvent" qtc_QTreeWidget_mouseDoubleClickEvent :: Ptr (TQTreeWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent_h (QTreeWidgetSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mouseDoubleClickEvent cobj_x0 cobj_x1
instance QmouseMoveEvent_h (QTreeWidget ()) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mouseMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_mouseMoveEvent" qtc_QTreeWidget_mouseMoveEvent :: Ptr (TQTreeWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent_h (QTreeWidgetSc a) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mouseMoveEvent cobj_x0 cobj_x1
instance QmousePressEvent_h (QTreeWidget ()) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mousePressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_mousePressEvent" qtc_QTreeWidget_mousePressEvent :: Ptr (TQTreeWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent_h (QTreeWidgetSc a) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mousePressEvent cobj_x0 cobj_x1
instance QmouseReleaseEvent_h (QTreeWidget ()) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mouseReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_mouseReleaseEvent" qtc_QTreeWidget_mouseReleaseEvent :: Ptr (TQTreeWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent_h (QTreeWidgetSc a) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mouseReleaseEvent cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> CursorAction -> KeyboardModifiers -> IO (QModelIndex t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> CLong -> CLong -> IO (Ptr (TQModelIndex t0))
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let x2flags = qFlags_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum x2flags
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler12" qtc_QTreeWidget_setHandler12 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> CLong -> CLong -> IO (Ptr (TQModelIndex t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget12 :: (Ptr (TQTreeWidget x0) -> CLong -> CLong -> IO (Ptr (TQModelIndex t0))) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> CLong -> CLong -> IO (Ptr (TQModelIndex t0))))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget12_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> CursorAction -> KeyboardModifiers -> IO (QModelIndex t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> CLong -> CLong -> IO (Ptr (TQModelIndex t0))
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let x2flags = qFlags_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum x2flags
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QmoveCursor_h (QTreeWidget ()) ((CursorAction, KeyboardModifiers)) where
moveCursor_h x0 (x1, x2)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_moveCursor cobj_x0 (toCLong $ qEnum_toInt x1) (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QTreeWidget_moveCursor" qtc_QTreeWidget_moveCursor :: Ptr (TQTreeWidget a) -> CLong -> CLong -> IO (Ptr (TQModelIndex ()))
instance QmoveCursor_h (QTreeWidgetSc a) ((CursorAction, KeyboardModifiers)) where
moveCursor_h x0 (x1, x2)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_moveCursor cobj_x0 (toCLong $ qEnum_toInt x1) (toCLong $ qFlags_toInt x2)
instance QpaintEvent_h (QTreeWidget ()) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_paintEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_paintEvent" qtc_QTreeWidget_paintEvent :: Ptr (TQTreeWidget a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent_h (QTreeWidgetSc a) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_paintEvent cobj_x0 cobj_x1
instance Qreset_h (QTreeWidget ()) (()) (IO ()) where
reset_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_reset cobj_x0
foreign import ccall "qtc_QTreeWidget_reset" qtc_QTreeWidget_reset :: Ptr (TQTreeWidget a) -> IO ()
instance Qreset_h (QTreeWidgetSc a) (()) (IO ()) where
reset_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_reset cobj_x0
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QModelIndex t1 -> Int -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let x2int = fromCInt x2
let x3int = fromCInt x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2int x3int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler13" qtc_QTreeWidget_setHandler13 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget13 :: (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget13_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QModelIndex t1 -> Int -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let x2int = fromCInt x2
let x3int = fromCInt x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2int x3int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QrowsAboutToBeRemoved_h (QTreeWidget ()) ((QModelIndex t1, Int, Int)) where
rowsAboutToBeRemoved_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_rowsAboutToBeRemoved cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QTreeWidget_rowsAboutToBeRemoved" qtc_QTreeWidget_rowsAboutToBeRemoved :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()
instance QrowsAboutToBeRemoved_h (QTreeWidgetSc a) ((QModelIndex t1, Int, Int)) where
rowsAboutToBeRemoved_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_rowsAboutToBeRemoved cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
instance QrowsInserted_h (QTreeWidget ()) ((QModelIndex t1, Int, Int)) where
rowsInserted_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_rowsInserted cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QTreeWidget_rowsInserted" qtc_QTreeWidget_rowsInserted :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()
instance QrowsInserted_h (QTreeWidgetSc a) ((QModelIndex t1, Int, Int)) where
rowsInserted_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_rowsInserted cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> Int -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> CInt -> CInt -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
let x1int = fromCInt x1
let x2int = fromCInt x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int x2int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler14" qtc_QTreeWidget_setHandler14 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> CInt -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget14 :: (Ptr (TQTreeWidget x0) -> CInt -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> CInt -> CInt -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget14_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> Int -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> CInt -> CInt -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
let x1int = fromCInt x1
let x2int = fromCInt x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int x2int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QscrollContentsBy_h (QTreeWidget ()) ((Int, Int)) where
scrollContentsBy_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_scrollContentsBy cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTreeWidget_scrollContentsBy" qtc_QTreeWidget_scrollContentsBy :: Ptr (TQTreeWidget a) -> CInt -> CInt -> IO ()
instance QscrollContentsBy_h (QTreeWidgetSc a) ((Int, Int)) where
scrollContentsBy_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_scrollContentsBy cobj_x0 (toCInt x1) (toCInt x2)
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QModelIndex t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler15" qtc_QTreeWidget_setHandler15 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget15 :: (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget15_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QModelIndex t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QModelIndex t1 -> ScrollHint -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> CLong -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2enum
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler16" qtc_QTreeWidget_setHandler16 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> CLong -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget16 :: (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> CLong -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> CLong -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget16_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QModelIndex t1 -> ScrollHint -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> CLong -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2enum
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QscrollTo_h (QTreeWidget ()) ((QModelIndex t1)) where
scrollTo_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_scrollTo cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_scrollTo" qtc_QTreeWidget_scrollTo :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> IO ()
instance QscrollTo_h (QTreeWidgetSc a) ((QModelIndex t1)) where
scrollTo_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_scrollTo cobj_x0 cobj_x1
instance QscrollTo_h (QTreeWidget ()) ((QModelIndex t1, ScrollHint)) where
scrollTo_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_scrollTo1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QTreeWidget_scrollTo1" qtc_QTreeWidget_scrollTo1 :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> CLong -> IO ()
instance QscrollTo_h (QTreeWidgetSc a) ((QModelIndex t1, ScrollHint)) where
scrollTo_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_scrollTo1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QselectAll_h (QTreeWidget ()) (()) where
selectAll_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_selectAll cobj_x0
foreign import ccall "qtc_QTreeWidget_selectAll" qtc_QTreeWidget_selectAll :: Ptr (TQTreeWidget a) -> IO ()
instance QselectAll_h (QTreeWidgetSc a) (()) where
selectAll_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_selectAll cobj_x0
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QObject t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQObject t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- qObjectFromPtr x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler17" qtc_QTreeWidget_setHandler17 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQObject t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget17 :: (Ptr (TQTreeWidget x0) -> Ptr (TQObject t1) -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQObject t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget17_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QObject t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQObject t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- qObjectFromPtr x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetModel_h (QTreeWidget ()) ((QAbstractItemModel t1)) where
setModel_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setModel cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_setModel" qtc_QTreeWidget_setModel :: Ptr (TQTreeWidget a) -> Ptr (TQAbstractItemModel t1) -> IO ()
instance QsetModel_h (QTreeWidgetSc a) ((QAbstractItemModel t1)) where
setModel_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setModel cobj_x0 cobj_x1
instance QsetRootIndex_h (QTreeWidget ()) ((QModelIndex t1)) where
setRootIndex_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setRootIndex cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_setRootIndex" qtc_QTreeWidget_setRootIndex :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> IO ()
instance QsetRootIndex_h (QTreeWidgetSc a) ((QModelIndex t1)) where
setRootIndex_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setRootIndex cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QRect t1 -> SelectionFlags -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget18 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget18_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQRect t1) -> CLong -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let x2flags = qFlags_fromInt $ fromCLong x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2flags
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler18" qtc_QTreeWidget_setHandler18 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQRect t1) -> CLong -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget18 :: (Ptr (TQTreeWidget x0) -> Ptr (TQRect t1) -> CLong -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQRect t1) -> CLong -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget18_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QRect t1 -> SelectionFlags -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget18 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget18_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQRect t1) -> CLong -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let x2flags = qFlags_fromInt $ fromCLong x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2flags
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqsetSelection_h (QTreeWidget ()) ((QRect t1, SelectionFlags)) where
qsetSelection_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setSelection cobj_x0 cobj_x1 (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QTreeWidget_setSelection" qtc_QTreeWidget_setSelection :: Ptr (TQTreeWidget a) -> Ptr (TQRect t1) -> CLong -> IO ()
instance QqsetSelection_h (QTreeWidgetSc a) ((QRect t1, SelectionFlags)) where
qsetSelection_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setSelection cobj_x0 cobj_x1 (toCLong $ qFlags_toInt x2)
instance QsetSelection_h (QTreeWidget ()) ((Rect, SelectionFlags)) where
setSelection_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QTreeWidget_setSelection_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QTreeWidget_setSelection_qth" qtc_QTreeWidget_setSelection_qth :: Ptr (TQTreeWidget a) -> CInt -> CInt -> CInt -> CInt -> CLong -> IO ()
instance QsetSelection_h (QTreeWidgetSc a) ((Rect, SelectionFlags)) where
setSelection_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QTreeWidget_setSelection_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h (toCLong $ qFlags_toInt x2)
instance QsetSelectionModel_h (QTreeWidget ()) ((QItemSelectionModel t1)) where
setSelectionModel_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setSelectionModel cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_setSelectionModel" qtc_QTreeWidget_setSelectionModel :: Ptr (TQTreeWidget a) -> Ptr (TQItemSelectionModel t1) -> IO ()
instance QsetSelectionModel_h (QTreeWidgetSc a) ((QItemSelectionModel t1)) where
setSelectionModel_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setSelectionModel cobj_x0 cobj_x1
instance QverticalOffset_h (QTreeWidget ()) (()) where
verticalOffset_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_verticalOffset cobj_x0
foreign import ccall "qtc_QTreeWidget_verticalOffset" qtc_QTreeWidget_verticalOffset :: Ptr (TQTreeWidget a) -> IO CInt
instance QverticalOffset_h (QTreeWidgetSc a) (()) where
verticalOffset_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_verticalOffset cobj_x0
instance QviewportEvent_h (QTreeWidget ()) ((QEvent t1)) where
viewportEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_viewportEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_viewportEvent" qtc_QTreeWidget_viewportEvent :: Ptr (TQTreeWidget a) -> Ptr (TQEvent t1) -> IO CBool
instance QviewportEvent_h (QTreeWidgetSc a) ((QEvent t1)) where
viewportEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_viewportEvent cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QModelIndex t1 -> IO (QRect t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget19 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget19_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler19 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect t0))
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler19" qtc_QTreeWidget_setHandler19 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget19 :: (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect t0))) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect t0))))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget19_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QModelIndex t1 -> IO (QRect t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget19 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget19_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler19 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect t0))
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqvisualRect_h (QTreeWidget ()) ((QModelIndex t1)) where
qvisualRect_h x0 (x1)
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_visualRect cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_visualRect" qtc_QTreeWidget_visualRect :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect ()))
instance QqvisualRect_h (QTreeWidgetSc a) ((QModelIndex t1)) where
qvisualRect_h x0 (x1)
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_visualRect cobj_x0 cobj_x1
instance QvisualRect_h (QTreeWidget ()) ((QModelIndex t1)) where
visualRect_h x0 (x1)
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_visualRect_qth cobj_x0 cobj_x1 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QTreeWidget_visualRect_qth" qtc_QTreeWidget_visualRect_qth :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
instance QvisualRect_h (QTreeWidgetSc a) ((QModelIndex t1)) where
visualRect_h x0 (x1)
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_visualRect_qth cobj_x0 cobj_x1 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QItemSelection t1 -> IO (QRegion t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget20 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget20_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler20 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQRegion t0))
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler20" qtc_QTreeWidget_setHandler20 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQRegion t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget20 :: (Ptr (TQTreeWidget x0) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQRegion t0))) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQRegion t0))))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget20_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QItemSelection t1 -> IO (QRegion t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget20 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget20_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler20 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQRegion t0))
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QvisualRegionForSelection_h (QTreeWidget ()) ((QItemSelection t1)) where
visualRegionForSelection_h x0 (x1)
= withQRegionResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_visualRegionForSelection cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_visualRegionForSelection" qtc_QTreeWidget_visualRegionForSelection :: Ptr (TQTreeWidget a) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQRegion ()))
instance QvisualRegionForSelection_h (QTreeWidgetSc a) ((QItemSelection t1)) where
visualRegionForSelection_h x0 (x1)
= withQRegionResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_visualRegionForSelection cobj_x0 cobj_x1
instance QdragEnterEvent_h (QTreeWidget ()) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dragEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_dragEnterEvent" qtc_QTreeWidget_dragEnterEvent :: Ptr (TQTreeWidget a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent_h (QTreeWidgetSc a) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dragEnterEvent cobj_x0 cobj_x1
instance QdragLeaveEvent_h (QTreeWidget ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dragLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_dragLeaveEvent" qtc_QTreeWidget_dragLeaveEvent :: Ptr (TQTreeWidget a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent_h (QTreeWidgetSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dragLeaveEvent cobj_x0 cobj_x1
instance QfocusInEvent_h (QTreeWidget ()) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_focusInEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_focusInEvent" qtc_QTreeWidget_focusInEvent :: Ptr (TQTreeWidget a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent_h (QTreeWidgetSc a) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_focusInEvent cobj_x0 cobj_x1
instance QfocusOutEvent_h (QTreeWidget ()) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_focusOutEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_focusOutEvent" qtc_QTreeWidget_focusOutEvent :: Ptr (TQTreeWidget a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent_h (QTreeWidgetSc a) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_focusOutEvent cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget21 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget21_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler21 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler21" qtc_QTreeWidget_setHandler21 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget21 :: (Ptr (TQTreeWidget x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> CLong -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget21_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget21 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget21_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler21 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QinputMethodQuery_h (QTreeWidget ()) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QTreeWidget_inputMethodQuery" qtc_QTreeWidget_inputMethodQuery :: Ptr (TQTreeWidget a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery_h (QTreeWidgetSc a) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
instance QresizeEvent_h (QTreeWidget ()) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_resizeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_resizeEvent" qtc_QTreeWidget_resizeEvent :: Ptr (TQTreeWidget a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent_h (QTreeWidgetSc a) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_resizeEvent cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget22 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget22_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler22 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler22" qtc_QTreeWidget_setHandler22 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget22 :: (Ptr (TQTreeWidget x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> CInt -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget22_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget22 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget22_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler22 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsizeHintForRow_h (QTreeWidget ()) ((Int)) where
sizeHintForRow_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sizeHintForRow cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTreeWidget_sizeHintForRow" qtc_QTreeWidget_sizeHintForRow :: Ptr (TQTreeWidget a) -> CInt -> IO CInt
instance QsizeHintForRow_h (QTreeWidgetSc a) ((Int)) where
sizeHintForRow_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sizeHintForRow cobj_x0 (toCInt x1)
instance QcontextMenuEvent_h (QTreeWidget ()) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_contextMenuEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_contextMenuEvent" qtc_QTreeWidget_contextMenuEvent :: Ptr (TQTreeWidget a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent_h (QTreeWidgetSc a) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_contextMenuEvent cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget23 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget23_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler23 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qTreeWidgetFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler23" qtc_QTreeWidget_setHandler23 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget23 :: (Ptr (TQTreeWidget x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> IO (Ptr (TQSize t0))))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget23_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget23 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget23_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler23 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qTreeWidgetFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqminimumSizeHint_h (QTreeWidget ()) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_minimumSizeHint cobj_x0
foreign import ccall "qtc_QTreeWidget_minimumSizeHint" qtc_QTreeWidget_minimumSizeHint :: Ptr (TQTreeWidget a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint_h (QTreeWidgetSc a) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_minimumSizeHint cobj_x0
instance QminimumSizeHint_h (QTreeWidget ()) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QTreeWidget_minimumSizeHint_qth" qtc_QTreeWidget_minimumSizeHint_qth :: Ptr (TQTreeWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint_h (QTreeWidgetSc a) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QqsizeHint_h (QTreeWidget ()) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sizeHint cobj_x0
foreign import ccall "qtc_QTreeWidget_sizeHint" qtc_QTreeWidget_sizeHint :: Ptr (TQTreeWidget a) -> IO (Ptr (TQSize ()))
instance QqsizeHint_h (QTreeWidgetSc a) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sizeHint cobj_x0
instance QsizeHint_h (QTreeWidget ()) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QTreeWidget_sizeHint_qth" qtc_QTreeWidget_sizeHint_qth :: Ptr (TQTreeWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint_h (QTreeWidgetSc a) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QwheelEvent_h (QTreeWidget ()) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_wheelEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_wheelEvent" qtc_QTreeWidget_wheelEvent :: Ptr (TQTreeWidget a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent_h (QTreeWidgetSc a) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_wheelEvent cobj_x0 cobj_x1
instance QchangeEvent_h (QTreeWidget ()) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_changeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_changeEvent" qtc_QTreeWidget_changeEvent :: Ptr (TQTreeWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent_h (QTreeWidgetSc a) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_changeEvent cobj_x0 cobj_x1
instance QactionEvent_h (QTreeWidget ()) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_actionEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_actionEvent" qtc_QTreeWidget_actionEvent :: Ptr (TQTreeWidget a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent_h (QTreeWidgetSc a) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_actionEvent cobj_x0 cobj_x1
instance QcloseEvent_h (QTreeWidget ()) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_closeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_closeEvent" qtc_QTreeWidget_closeEvent :: Ptr (TQTreeWidget a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent_h (QTreeWidgetSc a) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_closeEvent cobj_x0 cobj_x1
instance QdevType_h (QTreeWidget ()) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_devType cobj_x0
foreign import ccall "qtc_QTreeWidget_devType" qtc_QTreeWidget_devType :: Ptr (TQTreeWidget a) -> IO CInt
instance QdevType_h (QTreeWidgetSc a) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_devType cobj_x0
instance QenterEvent_h (QTreeWidget ()) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_enterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_enterEvent" qtc_QTreeWidget_enterEvent :: Ptr (TQTreeWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent_h (QTreeWidgetSc a) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_enterEvent cobj_x0 cobj_x1
instance QheightForWidth_h (QTreeWidget ()) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_heightForWidth cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTreeWidget_heightForWidth" qtc_QTreeWidget_heightForWidth :: Ptr (TQTreeWidget a) -> CInt -> IO CInt
instance QheightForWidth_h (QTreeWidgetSc a) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_heightForWidth cobj_x0 (toCInt x1)
instance QhideEvent_h (QTreeWidget ()) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_hideEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_hideEvent" qtc_QTreeWidget_hideEvent :: Ptr (TQTreeWidget a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent_h (QTreeWidgetSc a) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_hideEvent cobj_x0 cobj_x1
instance QkeyReleaseEvent_h (QTreeWidget ()) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_keyReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_keyReleaseEvent" qtc_QTreeWidget_keyReleaseEvent :: Ptr (TQTreeWidget a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent_h (QTreeWidgetSc a) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_keyReleaseEvent cobj_x0 cobj_x1
instance QleaveEvent_h (QTreeWidget ()) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_leaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_leaveEvent" qtc_QTreeWidget_leaveEvent :: Ptr (TQTreeWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent_h (QTreeWidgetSc a) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_leaveEvent cobj_x0 cobj_x1
instance QmoveEvent_h (QTreeWidget ()) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_moveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_moveEvent" qtc_QTreeWidget_moveEvent :: Ptr (TQTreeWidget a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent_h (QTreeWidgetSc a) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_moveEvent cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget24 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget24_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler24 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qTreeWidgetFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler24" qtc_QTreeWidget_setHandler24 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> IO (Ptr (TQPaintEngine t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget24 :: (Ptr (TQTreeWidget x0) -> IO (Ptr (TQPaintEngine t0))) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> IO (Ptr (TQPaintEngine t0))))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget24_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget24 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget24_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler24 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qTreeWidgetFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QpaintEngine_h (QTreeWidget ()) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_paintEngine cobj_x0
foreign import ccall "qtc_QTreeWidget_paintEngine" qtc_QTreeWidget_paintEngine :: Ptr (TQTreeWidget a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine_h (QTreeWidgetSc a) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_paintEngine cobj_x0
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget25 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget25_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler25 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler25" qtc_QTreeWidget_setHandler25 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> CBool -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget25 :: (Ptr (TQTreeWidget x0) -> CBool -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> CBool -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget25_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget25 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget25_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler25 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetVisible_h (QTreeWidget ()) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_setVisible cobj_x0 (toCBool x1)
foreign import ccall "qtc_QTreeWidget_setVisible" qtc_QTreeWidget_setVisible :: Ptr (TQTreeWidget a) -> CBool -> IO ()
instance QsetVisible_h (QTreeWidgetSc a) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_setVisible cobj_x0 (toCBool x1)
instance QshowEvent_h (QTreeWidget ()) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_showEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_showEvent" qtc_QTreeWidget_showEvent :: Ptr (TQTreeWidget a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent_h (QTreeWidgetSc a) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_showEvent cobj_x0 cobj_x1
instance QtabletEvent_h (QTreeWidget ()) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_tabletEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_tabletEvent" qtc_QTreeWidget_tabletEvent :: Ptr (TQTreeWidget a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent_h (QTreeWidgetSc a) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_tabletEvent cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget26 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget26_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler26 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler26" qtc_QTreeWidget_setHandler26 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget26 :: (Ptr (TQTreeWidget x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget26_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget26 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget26_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler26 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QeventFilter_h (QTreeWidget ()) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTreeWidget_eventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QTreeWidget_eventFilter" qtc_QTreeWidget_eventFilter :: Ptr (TQTreeWidget a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter_h (QTreeWidgetSc a) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTreeWidget_eventFilter cobj_x0 cobj_x1 cobj_x2
| keera-studios/hsQt | Qtc/Gui/QTreeWidget_h.hs | bsd-2-clause | 132,988 | 0 | 18 | 29,090 | 44,415 | 21,297 | 23,118 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Lens
import Data.Bool (bool)
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import Network.URI (URI)
import Hackerspace.Space
import qualified Network.Browser as Browser
import qualified Network.HTTP as HTTP
import qualified Network.URI as URI
import qualified Data.Aeson as Aeson
import qualified Data.Text as Text (intercalate)
import qualified Data.Text.IO as Text (putStrLn)
hackerspace :: URI
hackerspace =
let uri = "http://hackerspace-bielefeld.de/status.json" in
fromMaybe URI.nullURI $ URI.parseURI uri
spaceInfo :: Space -> Text
spaceInfo s =
Text.intercalate "\n"
[ view space s
, view (location . address) s
, "closed" `bool` "open" $ view (state . open) s
, fromMaybe "" $ view (contact . phone) s
]
main :: IO ()
main = do
(_, rsp) <- Browser.browse $ do
Browser.setOutHandler (const $ return ())
Browser.request $ HTTP.mkRequest HTTP.GET hackerspace
either
(putStrLn . ("<error>: " ++))
(Text.putStrLn . spaceInfo)
(Aeson.eitherDecode (HTTP.rspBody rsp))
| HackerspaceBielefeld/hackerspaceapi-haskell | src/Main.hs | bsd-2-clause | 1,121 | 0 | 15 | 221 | 361 | 202 | 159 | 34 | 1 |
{- OPTIONS_GHC -fplugin Brisk.Plugin #-}
{- OPTIONS_GHC -fplugin-opt Brisk.Plugin:main #-}
{-# LANGUAGE TemplateHaskell #-}
module SpawnSym where
import Control.Monad (forM, foldM)
import Control.Distributed.Process
import Control.Distributed.BriskStatic
import Control.Distributed.Process.Closure
import Control.Distributed.Process.SymmetricProcess
import GHC.Base.Brisk
p :: ProcessId -> Process ()
p who = do self <- getSelfPid
c <- liftIO $ getChar
msg <- if c == 'x' then return (0 :: Int) else return 1
send who msg
expect :: Process ()
return ()
remotable ['p]
ack :: ProcessId -> Process ()
ack p = send p ()
req = expect :: Process Int
broadCast :: SymSet ProcessId -> Process ()
broadCast pids = do
forM pids $ \p -> req
forM pids $ \p -> ack p
return ()
main :: [NodeId] -> Process ()
main nodes = do me <- getSelfPid
symSet <- spawnSymmetric nodes $ $(mkBriskClosure 'p) me
broadCast symSet
return ()
| abakst/brisk-prelude | tests/pos/SpawnSymForM.hs | bsd-3-clause | 1,036 | 0 | 12 | 266 | 337 | 169 | 168 | 29 | 2 |
{-# language CPP #-}
-- | = Name
--
-- VK_EXT_physical_device_drm - device extension
--
-- == VK_EXT_physical_device_drm
--
-- [__Name String__]
-- @VK_EXT_physical_device_drm@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
-- 354
--
-- [__Revision__]
-- 1
--
-- [__Extension and Version Dependencies__]
--
-- - Requires Vulkan 1.0
--
-- - Requires @VK_KHR_get_physical_device_properties2@
--
-- [__Contact__]
--
-- - Simon Ser
-- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_physical_device_drm] @emersion%0A<<Here describe the issue or question you have about the VK_EXT_physical_device_drm extension>> >
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
-- 2021-06-09
--
-- [__IP Status__]
-- No known IP claims.
--
-- [__Contributors__]
--
-- - Simon Ser
--
-- == Description
--
-- This extension provides new facilities to query DRM properties for
-- physical devices, enabling users to match Vulkan physical devices with
-- DRM nodes on Linux.
--
-- Its functionality closely overlaps with
-- @EGL_EXT_device_drm@<https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_EXT_physical_device_drm-fn1 1>^.
-- Unlike the EGL extension, this extension does not expose a string
-- containing the name of the device file and instead exposes device minor
-- numbers.
--
-- DRM defines multiple device node types. Each physical device may have
-- one primary node and one render node associated. Physical devices may
-- have no primary node (e.g. if the device does not have a display
-- subsystem), may have no render node (e.g. if it is a software rendering
-- engine), or may have neither (e.g. if it is a software rendering engine
-- without a display subsystem).
--
-- To query DRM properties for a physical device, chain
-- 'PhysicalDeviceDrmPropertiesEXT' to
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceProperties2'.
--
-- == New Structures
--
-- - Extending
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceProperties2':
--
-- - 'PhysicalDeviceDrmPropertiesEXT'
--
-- == New Enum Constants
--
-- - 'EXT_PHYSICAL_DEVICE_DRM_EXTENSION_NAME'
--
-- - 'EXT_PHYSICAL_DEVICE_DRM_SPEC_VERSION'
--
-- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType':
--
-- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PHYSICAL_DEVICE_DRM_PROPERTIES_EXT'
--
-- == References
--
-- 1. #VK_EXT_physical_device_drm-fn1#
-- <https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_device_drm.txt EGL_EXT_device_drm>
--
-- == Version History
--
-- - Revision 1, 2021-06-09
--
-- - First stable revision
--
-- == See Also
--
-- 'PhysicalDeviceDrmPropertiesEXT'
--
-- == Document Notes
--
-- For more information, see the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_EXT_physical_device_drm Vulkan Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module Vulkan.Extensions.VK_EXT_physical_device_drm ( PhysicalDeviceDrmPropertiesEXT(..)
, EXT_PHYSICAL_DEVICE_DRM_SPEC_VERSION
, pattern EXT_PHYSICAL_DEVICE_DRM_SPEC_VERSION
, EXT_PHYSICAL_DEVICE_DRM_EXTENSION_NAME
, pattern EXT_PHYSICAL_DEVICE_DRM_EXTENSION_NAME
) where
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Ptr (nullPtr)
import Foreign.Ptr (plusPtr)
import Vulkan.CStruct (FromCStruct)
import Vulkan.CStruct (FromCStruct(..))
import Vulkan.CStruct (ToCStruct)
import Vulkan.CStruct (ToCStruct(..))
import Vulkan.Zero (Zero(..))
import Data.String (IsString)
import Data.Typeable (Typeable)
import Foreign.Storable (Storable)
import Foreign.Storable (Storable(peek))
import Foreign.Storable (Storable(poke))
import qualified Foreign.Storable (Storable(..))
import GHC.Generics (Generic)
import Data.Int (Int64)
import Foreign.Ptr (Ptr)
import Data.Kind (Type)
import Vulkan.Core10.FundamentalTypes (bool32ToBool)
import Vulkan.Core10.FundamentalTypes (boolToBool32)
import Vulkan.Core10.FundamentalTypes (Bool32)
import Vulkan.Core10.Enums.StructureType (StructureType)
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_DRM_PROPERTIES_EXT))
-- | VkPhysicalDeviceDrmPropertiesEXT - Structure containing DRM information
-- of a physical device
--
-- = Description
--
-- If the 'PhysicalDeviceDrmPropertiesEXT' structure is included in the
-- @pNext@ chain of the
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceProperties2'
-- structure passed to
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceProperties2',
-- it is filled in with each corresponding implementation-dependent
-- property.
--
-- These are properties of the DRM information of a physical device.
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_physical_device_drm VK_EXT_physical_device_drm>,
-- 'Vulkan.Core10.FundamentalTypes.Bool32',
-- 'Vulkan.Core10.Enums.StructureType.StructureType'
data PhysicalDeviceDrmPropertiesEXT = PhysicalDeviceDrmPropertiesEXT
{ -- | @hasPrimary@ is a boolean indicating whether the physical device has a
-- DRM primary node.
hasPrimary :: Bool
, -- | @hasRender@ is a boolean indicating whether the physical device has a
-- DRM render node.
hasRender :: Bool
, -- | @primaryMajor@ is the DRM primary node major number, if any.
primaryMajor :: Int64
, -- | @primaryMinor@ is the DRM primary node minor number, if any.
primaryMinor :: Int64
, -- | @renderMajor@ is the DRM render node major number, if any.
renderMajor :: Int64
, -- | @renderMinor@ is the DRM render node minor number, if any.
renderMinor :: Int64
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PhysicalDeviceDrmPropertiesEXT)
#endif
deriving instance Show PhysicalDeviceDrmPropertiesEXT
instance ToCStruct PhysicalDeviceDrmPropertiesEXT where
withCStruct x f = allocaBytes 56 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PhysicalDeviceDrmPropertiesEXT{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_DRM_PROPERTIES_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (hasPrimary))
poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (hasRender))
poke ((p `plusPtr` 24 :: Ptr Int64)) (primaryMajor)
poke ((p `plusPtr` 32 :: Ptr Int64)) (primaryMinor)
poke ((p `plusPtr` 40 :: Ptr Int64)) (renderMajor)
poke ((p `plusPtr` 48 :: Ptr Int64)) (renderMinor)
f
cStructSize = 56
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_DRM_PROPERTIES_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero))
poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (zero))
poke ((p `plusPtr` 24 :: Ptr Int64)) (zero)
poke ((p `plusPtr` 32 :: Ptr Int64)) (zero)
poke ((p `plusPtr` 40 :: Ptr Int64)) (zero)
poke ((p `plusPtr` 48 :: Ptr Int64)) (zero)
f
instance FromCStruct PhysicalDeviceDrmPropertiesEXT where
peekCStruct p = do
hasPrimary <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32))
hasRender <- peek @Bool32 ((p `plusPtr` 20 :: Ptr Bool32))
primaryMajor <- peek @Int64 ((p `plusPtr` 24 :: Ptr Int64))
primaryMinor <- peek @Int64 ((p `plusPtr` 32 :: Ptr Int64))
renderMajor <- peek @Int64 ((p `plusPtr` 40 :: Ptr Int64))
renderMinor <- peek @Int64 ((p `plusPtr` 48 :: Ptr Int64))
pure $ PhysicalDeviceDrmPropertiesEXT
(bool32ToBool hasPrimary) (bool32ToBool hasRender) primaryMajor primaryMinor renderMajor renderMinor
instance Storable PhysicalDeviceDrmPropertiesEXT where
sizeOf ~_ = 56
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PhysicalDeviceDrmPropertiesEXT where
zero = PhysicalDeviceDrmPropertiesEXT
zero
zero
zero
zero
zero
zero
type EXT_PHYSICAL_DEVICE_DRM_SPEC_VERSION = 1
-- No documentation found for TopLevel "VK_EXT_PHYSICAL_DEVICE_DRM_SPEC_VERSION"
pattern EXT_PHYSICAL_DEVICE_DRM_SPEC_VERSION :: forall a . Integral a => a
pattern EXT_PHYSICAL_DEVICE_DRM_SPEC_VERSION = 1
type EXT_PHYSICAL_DEVICE_DRM_EXTENSION_NAME = "VK_EXT_physical_device_drm"
-- No documentation found for TopLevel "VK_EXT_PHYSICAL_DEVICE_DRM_EXTENSION_NAME"
pattern EXT_PHYSICAL_DEVICE_DRM_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern EXT_PHYSICAL_DEVICE_DRM_EXTENSION_NAME = "VK_EXT_physical_device_drm"
| expipiplus1/vulkan | src/Vulkan/Extensions/VK_EXT_physical_device_drm.hs | bsd-3-clause | 9,168 | 0 | 14 | 1,634 | 1,499 | 897 | 602 | -1 | -1 |
module Sexy.Instances.Show.Double () where
import Sexy.Classes (Show(..))
import Sexy.Data (Double)
import qualified Prelude as P
instance Show Double where
show = P.show
| DanBurton/sexy | src/Sexy/Instances/Show/Double.hs | bsd-3-clause | 176 | 0 | 6 | 27 | 56 | 36 | 20 | 6 | 0 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeFamilyDependencies #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
module Singletons where
import GHC.TypeLits
import GHC.Types
import Data.Proxy
import Test.Hspec
-- | Demote should be injective
type family Demote (k :: Type) = r | r -> k
type family TypeOf (a :: k) where TypeOf (a :: k) = k
reify :: forall a. Reflect a => Demote (TypeOf a)
reify = reflect (Proxy @a)
class Reflect (a :: k) where
reflect :: Proxy a -> Demote k
type instance Demote () = ()
instance Reflect '() where
reflect _ = ()
type instance Demote Symbol = String
instance (KnownSymbol s) => Reflect (s :: Symbol) where
reflect p = symbolVal p
type instance Demote Nat = Integer
instance (KnownNat n) => Reflect (n :: Nat) where
reflect p = natVal p
type instance Demote (Maybe k) = Maybe (Demote k)
instance (Reflect x) => Reflect (Just x :: Maybe a) where
reflect _ = Just (reflect (Proxy @x))
instance Reflect (Nothing :: Maybe a) where
reflect _ = Nothing
type instance Demote (Either j k) = Either (Demote j) (Demote k)
instance (Reflect x) => Reflect (Left x :: Either a b) where
reflect _ = Left (reflect (Proxy @x))
instance (Reflect y) => Reflect (Right y :: Either a b) where
reflect _ = Right (reflect (Proxy @y))
type instance Demote (a, b) = ((Demote a), (Demote b))
instance (Reflect x, Reflect y) => Reflect ('(x, y) :: (a, b)) where
reflect _ = (reflect (Proxy @x), reflect (Proxy @y))
spec = do
describe "reify" $ do
it "works for Unit" $ do
reify @'() `shouldBe` ()
it "works for Symbol" $ do
reify @"hello" `shouldBe` "hello"
it "works for Maybe" $ do
reify @(Just "hello") `shouldBe` Just "hello"
reify @(Nothing :: Maybe Symbol) `shouldBe` Nothing
reify @(Nothing :: Maybe (Maybe Symbol)) `shouldBe` Nothing
it "works for Either" $ do
reify @(Left "hello" :: Either Symbol Nat) `shouldBe` Left "hello"
reify @(Right 123 :: Either Symbol Nat) `shouldBe` Right 123
it "works for Tuples" $ do
reify @'("hello", 123) `shouldBe` ("hello", 123)
reify @'( '(123, "hello"), '()) `shouldBe` ((123, "hello"), ())
| sleexyz/haskell-fun | Singletons.hs | bsd-3-clause | 2,511 | 65 | 9 | 512 | 938 | 510 | 428 | 63 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
--
-- A Mandelbrot set generator.
-- Originally submitted by Simon Marlow as part of Issue #49.
--
module Mandel (
-- Types
View, Render, Bitmap,
-- Pretty pictures
mandelbrot, prettyRGBA,
) where
import Prelude as P
import Data.Array.Accelerate as A
import Data.Array.Accelerate.IO as A
import Data.Array.Accelerate.Data.Complex
-- Types -----------------------------------------------------------------------
-- Current view into the complex plane
type View a = (a, a, a, a)
-- Image data
type Bitmap = Array DIM2 RGBA32
-- Action to render a frame
type Render a = Scalar (View a) -> Bitmap
-- Mandelbrot Set --------------------------------------------------------------
-- Compute the mandelbrot as repeated application of the recurrence relation:
--
-- Z_{n+1} = c + Z_n^2
--
-- This returns the iteration depth 'i' at divergence.
--
mandelbrot
:: forall a. (Elt a, IsFloating a)
=> Int
-> Int
-> Int
-> a
-> Acc (Scalar (View a))
-> Acc (Array DIM2 Int32)
mandelbrot screenX screenY depth radius view =
generate (constant (Z:.screenY:.screenX))
(\ix -> let c = initial ix
in A.snd $ A.while (\zi -> A.snd zi A.<* cMAX &&* dot (A.fst zi) A.<* rMAX)
(\zi -> lift1 (next c) zi)
(lift (c, constant 0)))
where
-- The view plane
(xmin,ymin,xmax,ymax) = unlift (the view)
sizex = xmax - xmin
sizey = ymax - ymin
viewx = constant (P.fromIntegral screenX)
viewy = constant (P.fromIntegral screenY)
-- initial conditions for a given pixel in the window, translated to the
-- corresponding point in the complex plane
initial :: Exp DIM2 -> Exp (Complex a)
initial ix = lift ( (xmin + (x * sizex) / viewx) :+ (ymin + (y * sizey) / viewy) )
where
pr = unindex2 ix
x = A.fromIntegral (A.snd pr :: Exp Int)
y = A.fromIntegral (A.fst pr :: Exp Int)
-- take a single step of the iteration
next :: Exp (Complex a) -> (Exp (Complex a), Exp Int32) -> (Exp (Complex a), Exp Int32)
next c (z, i) = (c + (z * z), i+1)
dot c = let r :+ i = unlift c
in r*r + i*i
cMAX = P.fromIntegral depth
rMAX = constant (radius * radius)
-- Rendering -------------------------------------------------------------------
{--}
prettyRGBA :: Exp Int32 -> Exp Int32 -> Exp RGBA32
prettyRGBA cmax c = c ==* cmax ? ( 0xFF000000, escapeToColour (cmax - c) )
-- Directly convert the iteration count on escape to a colour. The base set
-- (x,y,z) yields a dark background with light highlights.
--
-- Note that OpenGL reads pixel data in AGBR format, rather than RGBA.
--
escapeToColour :: Exp Int32 -> Exp RGBA32
escapeToColour m = constant 0xFFFFFFFF - (packRGBA32 $ lift (r,g,b,a))
where
r = A.fromIntegral (3 * m)
g = A.fromIntegral (5 * m)
b = A.fromIntegral (7 * m)
a = constant 0
--}
{--
-- A simple colour scheme
--
prettyRGBA :: Elt a => Exp Int -> Exp (Complex a, Int) -> Exp RGBA32
prettyRGBA lIMIT s' = r + g + b + a
where
s = A.snd s'
t = A.fromIntegral $ ((lIMIT - s) * 255) `quot` lIMIT
r = (t `rem` 128 + 64) * 0x1000000
g = (t * 2 `rem` 128 + 64) * 0x10000
b = (t * 3 `rem` 256 ) * 0x100
a = 0xFF
--}
{--
prettyRGBA :: Exp Int32 -> Exp Int32 -> Exp RGBA32
prettyRGBA cmax' c' =
let cmax = A.fromIntegral cmax' :: Exp Float
c = A.fromIntegral c' / cmax
in
c A.>* 0.98 ? ( 0xFF000000, rampColourHotToCold 0 1 c )
-- Standard Hot-to-Cold hypsometric colour ramp. Colour sequence is
-- Red, Yellow, Green, Cyan, Blue
--
rampColourHotToCold
:: (Elt a, IsFloating a)
=> Exp a -- ^ minimum value of the range
-> Exp a -- ^ maximum value of the range
-> Exp a -- ^ data value
-> Exp RGBA32
rampColourHotToCold vmin vmax vNotNorm
= let v = vmin `max` vNotNorm `min` vmax
dv = vmax - vmin
--
result = v A.<* vmin + 0.28 * dv
? ( lift ( constant 0.0
, 4 * (v-vmin) / dv
, constant 1.0
, constant 1.0 )
, v A.<* vmin + 0.5 * dv
? ( lift ( constant 0.0
, constant 1.0
, 1 + 4 * (vmin + 0.25 * dv - v) / dv
, constant 1.0 )
, v A.<* vmin + 0.75 * dv
? ( lift ( 4 * (v - vmin - 0.5 * dv) / dv
, constant 1.0
, constant 0.0
, constant 1.0 )
, lift ( constant 1.0
, 1 + 4 * (vmin + 0.75 * dv - v) / dv
, constant 0.0
, constant 1.0 )
)))
in
rgba32OfFloat result
--}
| vollmerm/shallow-fission | tests/mandelbrot/src-acc/Mandel.hs | bsd-3-clause | 5,237 | 0 | 19 | 1,931 | 895 | 490 | 405 | 50 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ViewPatterns #-}
module Physics.Bullet.PointToPointConstraint where
import qualified Language.C.Inline.Cpp as C
import Foreign.C
import Linear.Extra
import Control.Monad.Trans
import Data.Monoid
import Physics.Bullet.Types
-----------------
-- Springs
-- See http://bulletphysics.org/Bullet/BulletFull/classbtGeneric6DofSpring2Constraint.html
-----------------
C.context (C.cppCtx <> C.funCtx)
C.include "<btBulletDynamicsCommon.h>"
addWorldPointToPointConstraint :: (Real a, MonadIO m)
=> DynamicsWorld
-> RigidBody -> V3 a
-> m PointToPointConstraint
addWorldPointToPointConstraint (DynamicsWorld dynamicsWorld)
(toCollisionObjectPointer->rigidBodyA) (fmap realToFrac -> V3 aX aY aZ) = PointToPointConstraint <$> liftIO [C.block| void * {
btDiscreteDynamicsWorld *dynamicsWorld = (btDiscreteDynamicsWorld *)$(void *dynamicsWorld);
btRigidBody *rigidBodyA = (btRigidBody *)$(void *rigidBodyA);
btVector3 pivotInA = btVector3($(float aX), $(float aY), $(float aZ));
btPoint2PointConstraint *point2Point = new btPoint2PointConstraint(
*rigidBodyA, pivotInA
);
dynamicsWorld->addConstraint(point2Point);
return point2Point;
}|]
addPointToPointConstraint :: (Real a, MonadIO m)
=> DynamicsWorld
-> RigidBody -> V3 a
-> RigidBody -> V3 a
-> m PointToPointConstraint
addPointToPointConstraint (DynamicsWorld dynamicsWorld)
(toCollisionObjectPointer->rigidBodyA) (fmap realToFrac -> V3 aX aY aZ)
(toCollisionObjectPointer->rigidBodyB) (fmap realToFrac -> V3 bX bY bZ) = PointToPointConstraint <$> liftIO [C.block| void * {
btDiscreteDynamicsWorld *dynamicsWorld = (btDiscreteDynamicsWorld *)$(void *dynamicsWorld);
btRigidBody *rigidBodyA = (btRigidBody *)$(void *rigidBodyA);
btRigidBody *rigidBodyB = (btRigidBody *)$(void *rigidBodyB);
btVector3 pivotInA = btVector3($(float aX), $(float aY), $(float aZ));
btVector3 pivotInB = btVector3($(float bX), $(float bY), $(float bZ));
btPoint2PointConstraint *point2Point = new btPoint2PointConstraint(
*rigidBodyA, *rigidBodyB,
pivotInA, pivotInB
);
dynamicsWorld->addConstraint(point2Point);
return point2Point;
}|]
| lukexi/bullet-mini | src/Physics/Bullet/PointToPointConstraint.hs | bsd-3-clause | 2,693 | 0 | 11 | 605 | 308 | 169 | 139 | 31 | 1 |
module CC.Language where
import Data.List (transpose)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
--
-- * Syntax
--
-- | Minimal, generic, binary choice calculus syntax.
data CC t e =
Obj (e (CC t e))
| Chc t (CC t e) (CC t e)
class Obj e where
mapCC :: (CC t e -> a) -> e (CC t e) -> e a
foldCC :: (CC t e -> a -> a) -> a -> e (CC t e) -> a
showObj :: Tag t => e (CC t e) -> String
class Tag t where
-- | The configuration options referenced in this tag.
tagOpts :: t -> Set Option
-- | Resolve or simplify a tag given a configuration.
resolve :: Config -> t -> Either t Bool
-- | Pretty print a tag.
showTag :: t -> String
showCC :: (Tag t, Obj e) => CC t e -> String
showCC (Obj e) = showObj e
showCC (Chc t l r) = showTag t ++ "<" ++ showCC l ++ "," ++ showCC r ++ ">"
instance (Tag t, Obj e) => Show (CC t e) where
show = showCC
--
-- * Semantics
--
-- | Configure option.
type Option = String
-- | Configuration option setting: on or off.
type Setting = (Option, Bool)
-- | (Potentially partial) configuration.
type Config = Map Option Bool
-- | Plain types correspond to the fixed-point of the object language
-- type constructor.
newtype Plain f = P { unP :: f (Plain f) }
-- | Denotational semantics.
type Semantics e = Map Config (Plain e)
-- | The set of all configuration options referred to in an expression.
options :: (Tag t, Obj e) => CC t e -> Set Option
options (Obj e) = foldCC (Set.union . options) Set.empty e
options (Chc t l r) = Set.unions [tagOpts t, options l, options r]
-- | All configurations of an expression.
configs :: (Tag t, Obj e) => CC t e -> [Config]
configs e = (map Map.fromList . transpose) [[(o,True),(o,False)] | o <- os]
where os = Set.toList (options e)
-- | Apply a (potentially partial) configuration to an expression.
configure :: (Tag t, Obj e) => Config -> CC t e -> CC t e
configure c (Obj e) = Obj (mapCC (configure c) e)
configure c (Chc t l r) =
case resolve c t of
Left t' -> Chc t' l' r'
Right b -> if b then l' else r'
where l' = configure c l
r' = configure c r
-- | Convert an expression without choices into a plain expression.
toPlain :: (Tag t, Obj e) => CC t e -> Plain e
toPlain (Obj e) = P (mapCC toPlain e)
toPlain e = error $ "toPlain: not plain: " ++ show e
-- | Compute the denotational semantics.
semantics :: (Tag t, Obj e) => CC t e -> Semantics e
semantics e = Map.fromList [(c, toPlain (configure c e)) | c <- configs e]
| walkie/CC-Minimal | src/CC/Language.hs | bsd-3-clause | 2,559 | 0 | 12 | 616 | 1,003 | 528 | 475 | 46 | 3 |
module Language.Interpreter.StdLib.BlockHandling
( addBlockHandlingStdLib
)
where
import Language.Ast ( Value(Null) )
import Language.Interpreter.Types ( InterpreterProcess
, setBuiltIn
, withGfxCtx
)
import Gfx.Context ( pushScope
, popScope
)
addBlockHandlingStdLib :: InterpreterProcess ()
addBlockHandlingStdLib = do
setBuiltIn "pushScope" pushGfxScope
setBuiltIn "popScope" popGfxScope
pushGfxScope :: [Value] -> InterpreterProcess Value
pushGfxScope _ = withGfxCtx pushScope >> return Null
popGfxScope :: [Value] -> InterpreterProcess Value
popGfxScope _ = withGfxCtx popScope >> return Null
| rumblesan/proviz | src/Language/Interpreter/StdLib/BlockHandling.hs | bsd-3-clause | 923 | 0 | 7 | 393 | 154 | 83 | 71 | 16 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
module Prosper.Commands
( invest
, account
, allListings
, notes
, listingFromNote
, listingCSV
, AccountException (..)
, UnauthorizedException (..)
) where
import Control.Exception (Exception, throwIO)
import Control.Monad (when)
import Data.ByteString.Char8 as C
import Data.Maybe (listToMaybe)
import Data.Monoid ((<>))
import Data.Typeable (Typeable)
import Data.Vector (Vector)
import Network.Http.Client
import System.IO.Streams (InputStream)
import Prosper.Account
import Prosper.Internal.JSON
import Prosper.Internal.CSV
import Prosper.Invest
import Prosper.Listing
import Prosper.Money
import Prosper.Note
import Prosper.User
-- | An investment request. This requires a 'User', an amount of 'Money', and a 'Listing'.
invest :: User -> Money -> Listing -> IO InvestResponse
invest user amt l = investRequest user (listingId l) amt
-- | Request 'Account' information from Prosper
account :: User -> IO Account
account user = jsonGetHandler user "Account" accountHandler
where
accountHandler resp is = do
let statusCode = getStatusCode resp
statusMsg = getStatusMessage resp
when (statusCode == 500) $
throwIO (AccountException statusMsg)
when (statusCode == 401) $
throwIO (UnauthorizedException statusMsg)
jsonHandler resp is
-- | Used as a hack around the 500 Critical Exception error
data AccountException = AccountException ByteString
deriving (Typeable, Show)
instance Exception AccountException
-- | If unauthorized response, send
data UnauthorizedException = UnauthorizedException ByteString
deriving (Typeable, Show)
instance Exception UnauthorizedException
-- | Request notes for a Prosper user
notes :: User -> IO (Vector Note)
notes user = jsonGet user "Notes"
-- | Given a 'Note', look up the associated 'Listing' by the ListingId
listingFromNote :: User -> Note -> IO (Maybe Listing)
listingFromNote user (Note { listingNumber = lid }) = do
ls <- jsonGet user command
return $ listToMaybe ls
where
command = "ListingsHistorical?$filter=ListingNumber eq " <> C.pack (show lid)
-- | Send a request to the Listings end-point at Prosper
allListings :: User -> IO (Vector Listing)
allListings user = jsonGet user "Listings"
-- | Request a particular 'Listing' via the CSV endpoint
listingCSV :: User -> Listing -> (InputStream ByteString -> IO a) -> IO a
listingCSV user l = csvGetStream user url
where
lid = listingId l
url = "Listings?$filter=ListingNumber%20eq%20" <> C.pack (show lid)
| WraithM/prosper | src/Prosper/Commands.hs | bsd-3-clause | 2,860 | 0 | 12 | 728 | 628 | 336 | 292 | 59 | 1 |
module Lint where
import Control.Monad.Writer
import Data.List (intercalate)
import Statement
import Expression (Name, Expr(..))
-- Quick 'n dirty! Unused variables are any variable that's in an assignment
-- statement, but not in any expression. As a proof-of-concept, we do directly
-- this, and first make a pass over the program to get any defined variable names,
-- then do a second pass and get all of the variable names that appear in an
-- expression. The difference of these two lists is then all of the
-- declared, but unused variables.
usedVars :: Statement -> [Name]
usedVars (s1 :. s2 ) = usedVars s1 ++ usedVars s2
usedVars (Print e) = getVars e
usedVars (If e _ _) = getVars e
usedVars (While e _) = getVars e
usedVars _ = mempty
getVars :: Expr -> [Name]
getVars (Var name) = [name]
getVars (Add e1 e2) = getVars e1 ++ getVars e2
getVars (Sub e1 e2) = getVars e1 ++ getVars e2
getVars (Mul e1 e2) = getVars e1 ++ getVars e2
getVars (Div e1 e2) = getVars e1 ++ getVars e2
getVars (And e1 e2) = getVars e1 ++ getVars e2
getVars (Or e1 e2) = getVars e1 ++ getVars e2
getVars (Not e1 ) = getVars e1
getVars (Eq e1 e2) = getVars e1 ++ getVars e2
getVars (Gt e1 e2) = getVars e1 ++ getVars e2
getVars (Lt e1 e2) = getVars e1 ++ getVars e2
getVars (Const _) = mempty
declaredVars :: Statement -> [Name]
declaredVars (s1 :. s2) = declaredVars s1 ++ declaredVars s2
declaredVars (Assign name _) = [name]
declaredVars _ = []
unusedVarMessage :: Statement -> Maybe String
unusedVarMessage stmt = go $ declaredVars stmt `less` usedVars stmt
where xs `less` ys = [x | x <- xs, x `notElem` ys]
go [] = Nothing
go [x] = Just $! "Yikes, variable " ++ x ++ " is defined but never used!"
go xs = Just $! "Great Scott! The variables " ++ (intercalate ", " xs) ++ " are defined, but never used!"
| shawa/delorean | src/Lint.hs | bsd-3-clause | 1,872 | 0 | 10 | 420 | 639 | 323 | 316 | 34 | 3 |
{-# LANGUAGE CPP #-}
module MacAddress where
import Data.Binary (decode)
import qualified Data.ByteString.Lazy as BSL
import Safe (headDef)
#ifdef ETA_VERSION
import Java
import Data.Maybe (catMaybes)
import Data.Traversable (for)
import Data.Word (Word64, Word8)
#else /* !defined ETA_VERSION */
import Data.Word (Word64)
import Network.Info (MAC (MAC), getNetworkInterfaces, mac)
#endif /* ETA_VERSION */
getMacAddress :: IO Word64
#ifdef ETA_VERSION
getMacAddress = java $ do
interfaces <- fromJava <$> getNetworkInterfaces
macs <- for interfaces (<.> getHardwareAddress)
let macBytes =
headDef (error "Can't get any non-zero MAC address of this machine")
$ catMaybes macs
let mac = foldBytes $ fromJava macBytes
pure mac
data NetworkInterface = NetworkInterface @java.net.NetworkInterface
deriving Class
foreign import java unsafe
"@static java.net.NetworkInterface.getNetworkInterfaces"
getNetworkInterfaces :: Java a (Enumeration NetworkInterface)
foreign import java unsafe
getHardwareAddress :: Java NetworkInterface (Maybe JByteArray)
foldBytes :: [Word8] -> Word64
foldBytes bytes = decode . BSL.pack $ replicate (8 - length bytes) 0 ++ bytes
#else /* !defined ETA_VERSION */
getMacAddress = decodeMac <$> getMac
getMac :: IO MAC
getMac =
headDef (error "Can't get any non-zero MAC address of this machine")
. filter (/= minBound)
. map mac
<$> getNetworkInterfaces
decodeMac :: MAC -> Word64
decodeMac (MAC b5 b4 b3 b2 b1 b0) =
decode $ BSL.pack [0, 0, b5, b4, b3, b2, b1, b0]
#endif /* ETA_VERSION */
| cblp/crdt | crdt/lib/MacAddress.hs | bsd-3-clause | 1,697 | 8 | 14 | 396 | 284 | 154 | 130 | 18 | 1 |
import System.Environment (getArgs)
import Data.List (sort)
bat :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> [Int] -> Int
bat l d n c s t tx xs | s > l - 6 = c
| s > tx - d && t == n = bat l d n c (tx+d) t (l-6+d) xs
| s > tx - d = bat l d n c (tx+d) (t+1) (head xs) (tail xs)
| otherwise = bat l d n (c+1) (s+d) t tx xs
bats :: [Int] -> Int
bats (a:d:n:xs) = bat a d n 0 6 0 (6-d) (sort xs)
main :: IO ()
main = do
[inpFile] <- getArgs
input <- readFile inpFile
putStr . unlines . map (show . bats . map read . words) $ lines input
| nikai3d/ce-challenges | moderate/bats.hs | bsd-3-clause | 680 | 0 | 13 | 280 | 396 | 199 | 197 | 14 | 1 |
{-
- Hacq (c) 2013 NEC Laboratories America, Inc. All rights reserved.
-
- This file is part of Hacq.
- Hacq is distributed under the 3-clause BSD license.
- See the LICENSE file for more details.
-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Data.MexSet (MexSet, empty, singleton, fromList, fromAscList, toList, null, member, notMember, insert, delete, mex) where
import Prelude hiding (null)
import Data.FingerTree (FingerTree, Measured, (<|), (><), ViewL((:<)))
import qualified Data.FingerTree as FingerTree
import qualified Data.Foldable as Foldable
import qualified Data.List as List
import Data.Monoid (Monoid)
import qualified Data.Monoid as Monoid
import Util (mergeAscLists)
data Mex a = Mex {
_getMin :: !a, -- ^minimum integer in the tree; 0 for empty tree
getMax :: !a, -- ^maximum integer in the tree; 0 for empty tree
_getNextHole :: !a -- ^minimum integer that is at least _getMin and does not appear in the tree; 0 for empty tree
}
instance Integral a => Monoid (Mex a) where
mempty = Mex 0 0 0
Mex _ _ 0 `mappend` mex2 = mex2
mex1 `mappend` Mex _ _ 0 = mex1
Mex mi1 _ ho1 `mappend` Mex mi2 ma2 ho2 =
Mex mi1 ma2 $ if ho1 == mi2 then ho2 else ho1
newtype Item a = Item {
getItem :: a
} deriving (Eq, Ord, Num, Real, Enum, Integral)
instance Show a => Show (Item a) where
showsPrec d (Item x) = showsPrec d x
instance Integral a => Measured (Mex a) (Item a) where
measure (Item x) =
Mex x x y
where
y = x + 1
newtype MexSet a = MexSet (FingerTree (Mex a) (Item a))
deriving (Eq, Ord, Show)
empty :: Integral a => MexSet a
empty = MexSet FingerTree.empty
singleton :: Integral a => a -> MexSet a
singleton x = MexSet $ FingerTree.singleton $ Item x
instance Integral a => Monoid (MexSet a) where
mempty = empty
MexSet t1 `mappend` MexSet t2 =
MexSet $ FingerTree.fromList $ mergeAscLists (Foldable.toList t1) (Foldable.toList t2)
fromList :: Integral a => [a] -> MexSet a
fromList =
fromAscList . List.sort
fromAscList :: Integral a => [a] -> MexSet a
fromAscList =
MexSet . FingerTree.fromList . map Item
toList :: Integral a => MexSet a -> [a]
toList (MexSet t) = map getItem $ Foldable.toList t
null :: Integral a => MexSet a -> Bool
null (MexSet t) = FingerTree.null t
member :: Integral a => a -> MexSet a -> Bool
member x (MexSet t) =
case FingerTree.viewl (FingerTree.dropUntil ((>= x) . getMax) t) of
Item x' :< _ | x == x' -> True
_ -> False
notMember :: Integral a => a -> MexSet a -> Bool
notMember a = not . member a
insert :: Integral a => a -> MexSet a -> MexSet a
insert x s@(MexSet t) =
case FingerTree.viewl r of
Item x' :< _ | x == x' -> s
_ -> MexSet $ l >< Item x <| r
where
(l, r) = FingerTree.split ((>= x) . getMax) t
delete :: Integral a => a -> MexSet a -> MexSet a
delete x s@(MexSet t) =
case FingerTree.viewl r of
Item x' :< r' | x == x' -> MexSet $ l >< r'
_ -> s
where
(l, r) = FingerTree.split ((>= x) . getMax) t
mex :: Integral a => MexSet a -> a
mex (MexSet t) =
if mi == 0 then
ho
else
0
where
Mex mi _ ho = FingerTree.measure t
| ti1024/hacq | src/Data/MexSet.hs | bsd-3-clause | 3,215 | 0 | 11 | 768 | 1,235 | 644 | 591 | 81 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.