code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators #-}
module Lib
( startApp
, app
) where
import Control.Monad.IO.Class (liftIO)
import Data.Aeson
import Data.Aeson.TH
import qualified Data.ByteString.Lazy as B
import Data.List (find)
import Data.Maybe (listToMaybe, maybeToList)
import Data.Text (Text (..))
import qualified Data.Text as T
import Data.Time
import Data.Time.LocalTime
import Destination
import Network.HTTP.Conduit (simpleHttp)
import Network.Wai
import Network.Wai.Handler.Warp
import Network.Wai.Logger
import PredictionsByStop (DirectionElt (..), ModeElt (..),
RouteElt (..), TripElt (..))
import qualified PredictionsByStop
import Servant
import StopsByLocation (StopElt (..))
import qualified StopsByLocation
newtype Latitude = Latitude Double
deriving (Eq, Show, Ord, ToJSON, FromJSON)
newtype Longitude = Longitude Double
deriving (Eq, Show, Ord, ToJSON, FromJSON)
data Commute = Commute
{ lat :: Latitude
, lon :: Longitude
, name :: Text
, leaving :: ZonedTime
, destination :: Destination
} deriving (Eq, Show)
deriving instance Eq ZonedTime
$(deriveJSON defaultOptions ''Commute)
type API = "commutes" :> Capture "person" Person :> Get '[JSON] [Commute]
:<|> "commutes" :> Capture "person" Person :> Capture "location" Location :> Get '[JSON] [Commute]
startApp :: IO ()
startApp = do
putStrLn "running on 127.0.0.1:8080"
withStdoutLogger $ \aplogger -> do
let settings = setPort 8080 . setHost "*" $ setLogger aplogger defaultSettings
runSettings settings app
app :: Application
app = serve api server
api :: Proxy API
api = Proxy
server :: Server API
server = commutesByPerson
:<|> commutesByPersonAndLocation
commutesByPerson person = liftIO $ do
work <- getCommutes (Destination person Work)
appt <- getCommutes (Destination person Appt)
return $ work ++ appt
commutesByPersonAndLocation person location = liftIO $ getCommutes (Destination person location)
getCommutes :: Destination -> IO [Commute]
getCommutes destination = do
maybePredictions <- fmap decode $ getPredictionsJSON destination
maybeStops <- fmap decode getStopsJSON
tz <- getCurrentTimeZone
let maybeCommute = do
predictions <- maybePredictions
stops <- maybeStops
topLevelToCommute tz destination stops predictions
pure $ maybeToList maybeCommute
outboundPredictionsURL :: StopId -> String
outboundPredictionsURL (StopId stopId) = "http://realtime.mbta.com/developer/api/v2/predictionsbystop?api_key=wX9NwuHnZU2ToO7GmGR9uw&stop=" ++ stopId ++ "&format=json"
getPredictionsJSON :: Destination -> IO B.ByteString
getPredictionsJSON destination = simpleHttp (outboundPredictionsURL $ toStopId destination)
stopsByLocationURL :: String
stopsByLocationURL = "http://realtime.mbta.com/developer/api/v2/stopsbylocation?api_key=wX9NwuHnZU2ToO7GmGR9uw&lat=42.3097361&lon=-71.1151431&format=json"
getStopsJSON :: IO B.ByteString
getStopsJSON = simpleHttp stopsByLocationURL
topLevelToCommute :: TimeZone -> Destination -> StopsByLocation.TopLevel -> PredictionsByStop.TopLevel -> Maybe Commute
topLevelToCommute tz destination (StopsByLocation.TopLevel {..}) (PredictionsByStop.TopLevel {..}) = Commute <$> lat <*> lon <*> name <*> timestamp <*> pure destination
where
stop = find (\(StopElt {..}) -> stopEltStopId == topLevelStopId ) topLevelStop
name = pure topLevelStopName
lat = fmap (Latitude . read . T.unpack . stopEltStopLat) stop
lon = fmap (Longitude . read . T.unpack . stopEltStopLon) stop
timestamp = do
ModeElt {modeEltRoute} <- listToMaybe topLevelMode
RouteElt {routeEltDirection} <- listToMaybe modeEltRoute
DirectionElt {directionEltTrip} <- listToMaybe routeEltDirection
TripElt {tripEltPreDt} <- listToMaybe directionEltTrip
let utcTime = parseTimeOrError True defaultTimeLocale "%s" (T.unpack tripEltPreDt)
pure $ utcToZonedTime tz utcTime
| thesietch/homOS | homOS-backend/src/Lib.hs | mit | 4,528 | 0 | 16 | 1,029 | 1,086 | 575 | 511 | 96 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Chorale.Geo.Coordinates
-- Copyright : 2014-2016 Franz-Benjamin Mocnik
-- License : MIT
--
-- Maintainer : [email protected]
-- Stability : stable
-- Portability : portable
--
-----------------------------------------------------------------------------
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
module Chorale.Geo.Coordinates (
-- * Constants
radiusEarth,
-- * Geo Functions
degreeToRad,
radToDegree,
-- * Coordinates
Coordinates(..),
CoordinatesCartesian(..),
CoordinatesWGS84(..),
-- * Coordinate Transformations
transformWGS84toCartesian) where
import Chorale.Common
import qualified Data.Binary as B
import GHC.Generics (Generic)
-- --== CONSTANTS
-- | radius of the Earth in km
radiusEarth :: Double
radiusEarth = 6371.009
-- --== GEO FUNCTIONS
-- | degree to rad
degreeToRad :: Double -> Double
degreeToRad d = d * pi / 180
-- | rad to degree
radToDegree :: Double -> Double
radToDegree r = r * 180 / pi
-- --== GEOMETRY
-- | norm of a vector
norm :: Floating a => [a] -> a
norm = sqrt . sum . uncurry (zipWith (*)) . make2
-- --== COORDINATES
-- | Coordinate class
class (Ord c, Eq c, Show c) => Coordinates c where
toTuple :: c -> (Double, Double)
distance :: c -> c -> Double
azimuth :: c -> c -> Double
-- --== COORDINATES CARTESIAN
-- | Cartesian coordinates
newtype CoordinatesCartesian = CoordinatesCartesian (Double, Double) deriving (Ord, Eq, Show, Generic)
instance B.Binary CoordinatesCartesian
instance Coordinates CoordinatesCartesian where
toTuple (CoordinatesCartesian x) = x
distance = curry $ norm . uncurry (zipWith (-)) . map12 (tupleToList2 . toTuple)
azimuth (CoordinatesCartesian (x1, y1)) (CoordinatesCartesian (x2, y2)) = alpha (x2 - x1, y2 - y1) where
alpha (x, y)
| x == 0 && y == 0 = error "azimuth cannot be computed between two identical vectors"
| az < 0 = az + 2 * pi
| otherwise = az where
az = - atan2 y x + pi / 2
instance Coordinates (Double, Double) where
toTuple = id
distance = curry $ uncurry distance . map12 CoordinatesCartesian
azimuth = curry $ uncurry azimuth . map12 CoordinatesCartesian
-- --== COORDINATES WGS84
-- | Geographic coordinates (WGS84)
newtype CoordinatesWGS84 = CoordinatesWGS84 (Double, Double) deriving (Ord, Eq, Show, Generic)
instance B.Binary CoordinatesWGS84
instance Coordinates CoordinatesWGS84 where
toTuple (CoordinatesWGS84 x) = x
distance cs1 cs2 = radiusEarth * sqrt (diffAngle lat2 lat1 ** 2 + (cos ((lat2 + lat1) / 2) * diffAngle lon2 lon1)**2) where
[lat1, lon1] = map degreeToRad . tupleToList2 . toTuple $ cs1
[lat2, lon2] = map degreeToRad . tupleToList2 . toTuple $ cs2
diffAngle y x
| abs (y - x) < pi / 2 = y - x
| otherwise = diffAngle y (x + signum (y - x) * pi)
-- Vincenty's formulae
azimuth (CoordinatesWGS84 (lat1', lon1')) (CoordinatesWGS84 (lat2', lon2'))
| lat1' - lat2' == 0 && lon1' - lon2' == 0 = error "azimuth cannot be computed between two identical vectors"
| az < 0 = az + 2 * pi
| otherwise = az where
az = atan2 (cos u2 * sin lambda) (cos u1 * sin u2 - sin u1 * cos u2 * cos lambda)
lat1 = degreeToRad lat1'
lat2 = degreeToRad lat2'
lon1 = degreeToRad lon1'
lon2 = degreeToRad lon2'
f = 1 / 298.257223563
u1 = atan ((1 - f) * tan lat1)
u2 = atan ((1 - f) * tan lat2)
l = lon2 - lon1
lambda = recursiveFunction l
recursiveFunction x
| abs (x - x') < 10e-12 = x'
| otherwise = recursiveFunction x' where
sins = sqrt $ (cos u2 * sin x)**2 + (cos u1 * sin u2 - sin u1 * cos u2 * cos x)**2
coss = sin u1 * sin u2 + cos u1 * cos u2 * cos x
s = atan (sins / coss)
sina = (cos u1 * cos u2 * sin x) / sins
cos2a = 1 - sina**2
cos2sm = sqrt cos2a - 2 * sin u1 * sin u2 / cos2a
c = f / 16 * cos2a * (4 + f * (4 - 3 * cos2a))
x' = l + (1 - c) * f * sina * (s + c * sins * (cos2sm + c * coss * (-1 + 2 * cos2sm**2)))
-- --== COORDINATE TRANSFORMATIONS
-- | transform 'CoordinatesWGS84' to 'CoordinatesCartesian'
transformWGS84toCartesian :: Double -> CoordinatesWGS84 -> CoordinatesCartesian
transformWGS84toCartesian k (CoordinatesWGS84 (lat, lon)) = CoordinatesCartesian (128 / pi * 2**k * (degreeToRad lon + pi), 128 / pi * 2**k * (pi - log (tan (pi / 4 + degreeToRad lat / 2))))
| mocnik-science/chorale-geo | src/Chorale/Geo/Coordinates.hs | mit | 4,793 | 1 | 19 | 1,337 | 1,559 | 818 | 741 | 77 | 1 |
module Librato (
withLibrato,
module Librato.Metrics,
module Librato.Types
) where
import Librato.Internal
import Librato.Types
import Librato.Metrics
--data DisplayAttribute
-- = Color
-- | DisplayMax
-- | DisplayMin
-- | DisplayUnitsLong
-- | DisplayUnitsShort
-- | DisplayStacked
-- | DisplayTransform
--data GaugeAttribute
-- = SummarizeFunction
-- | Aggregate
--data Metric =
-- Gauge
-- {
-- ,
-- }
-- Counter
-- { }
--data Measurement = Measurement
-- { name
-- , value
-- , measureTime
-- , source
-- , }
| iand675/librato | src/Librato.hs | mit | 555 | 0 | 5 | 124 | 60 | 47 | 13 | 7 | 0 |
-- |
-- Module : Graphics.WaveFront.Foreign
-- Description : Foreign function interface
-- Copyright : (c) Jonatan H Sundqvist, 2015
-- License : MIT
-- Maintainer : Jonatan H Sundqvist
-- Stability : experimental|stable
-- Portability : POSIX (not sure)
-- February 24 2015
-- TODO | - Possible to get rid of newtypes (?)
-- - Decide on an API
-- SPEC | -
-- -
-- TODO: Why do some extensions start with 'X'?
{-# LANGUAGE ForeignFunctionInterface #-}
--------------------------------------------------------------------------------------------------------------------------------------------
-- API
--------------------------------------------------------------------------------------------------------------------------------------------
module Graphics.WaveFront.Foreign where
--------------------------------------------------------------------------------------------------------------------------------------------
-- We'll need these
--------------------------------------------------------------------------------------------------------------------------------------------
-- import System.IO.Unsafe (unsafePerformIO)
-- import Foreign.Storable
-- import qualified Foreign.C as C
-- import Graphics.WaveFront.Types
-- import qualified Graphics.WaveFront.Parse as Parse
--------------------------------------------------------------------------------------------------------------------------------------------
-- Functions
--------------------------------------------------------------------------------------------------------------------------------------------
-- -- |
-- -- I feel dirty...
-- parseOBJ :: C.CString -> COBJ
-- parseOBJ = COBJ . Parsers.parseOBJ . unsafePerformIO . C.peekCString
--
-- -- |
-- parseMTL :: C.CString -> CMTL
-- parseMTL = CMTL . Parsers.parseMTL . unsafePerformIO . C.peekCString
-- -- |
-- newtype COBJ = COBJ OBJ
--
--
-- -- |
-- newtype CMTL = CMTL MTL
--
--
-- -- | We
-- instance Storable COBJ where
-- sizeOf = const 0
-- alignment = const 0
-- peek _ = error "Work in progress"
-- poke _ = error "Work in progress"
--
--
-- -- | We
-- instance Storable CMTL where
-- sizeOf = const 0
-- alignment = const 0
-- peek _ = error "Work in progress"
-- poke _ = error "Work in progress"
--------------------------------------------------------------------------------------------------------------------------------------------
-- Pure foreign function interface
--------------------------------------------------------------------------------------------------------------------------------------------
-- I feel the urge to make a joke about 'Unacceptable argument in foreign declaration'
-- foreign export ccall parseOBJ :: C.CString -> COBJ
-- foreign export ccall parseMTL :: C.CString -> CMTL
| SwiftsNamesake/3DWaves | src/Graphics/WaveFront/Foreign.hs | mit | 2,829 | 0 | 3 | 381 | 72 | 70 | 2 | 2 | 0 |
module Yahtzee.Scoring where
import Text.Show.Functions
import Data.Tuple.Select
import Data.List
-- Upper section
scoreN :: Int -> [Int] -> Int
scoreN n = sum . filter (==n)
-- Straights
isSmallStraight :: [Int] -> Bool
isSmallStraight roll = or [[1,2,3,4] `isInfixOf` r,
[2,3,4,5] `isInfixOf` r,
[3,4,5,6] `isInfixOf` r]
where r = (map head . group . sort) roll
isLargeStraight :: [Int] -> Bool
isLargeStraight roll = or [[1,2,3,4,5] `isInfixOf` r,
[2,3,4,5,6] `isInfixOf` r]
where r = (map head . group . sort) roll
scoreSmallStraight :: [Int] -> Int
scoreSmallStraight vals = if isSmallStraight vals then 30 else 0
scoreLargeStraight :: [Int] -> Int
scoreLargeStraight vals = if isLargeStraight vals then 40 else 0
-- N of a kind
isThreeOfAKind :: [Int] -> Bool
isThreeOfAKind = hasNAlike 3
isFourOfAKind :: [Int] -> Bool
isFourOfAKind = hasNAlike 4
scoreThreeOfAKind :: [Int] -> Int
scoreThreeOfAKind vals = if isThreeOfAKind vals then sum vals else 0
scoreFourOfAKind :: [Int] -> Int
scoreFourOfAKind vals = if isFourOfAKind vals then sum vals else 0
hasNAlike :: Int -> [Int] -> Bool
hasNAlike n = any (>=n) . map length . group . sort
-- House
isFullHouse :: [Int] -> Bool
isFullHouse roll = [2,3] == (sort . map length . group . sort) roll
scoreFullHouse :: [Int] -> Int
scoreFullHouse vals = if isFullHouse vals then 25 else 0
-- Chance
scoreChance :: [Int] -> Int
scoreChance = sum
-- Yahtzee
isYahtzee :: [Int] -> Bool
isYahtzee (x:rest) = all (== x) rest
scoreYahtzee :: [Int] -> Int
scoreYahtzee vals = if isYahtzee vals then 50 else 0
| kvalle/yahtzee.hs | src/Yahtzee/Scoring.hs | mit | 1,668 | 0 | 11 | 378 | 651 | 369 | 282 | 39 | 2 |
{-# LANGUAGE CPP #-}
-- This example requires manual rebuild (as opposed to dynamic ones, automatically rebuilding the
-- config upon changes). This config is useful for distribution of the editor in binary form as such
-- a build have almost all libraries statically linked in.
-- Here's a building example with "stack":
-- 1. Edit "stack.yaml" file so that "location: " would point to the root of the Yi source code
-- 2. Run "stack install"
-- (You can add "--flag yi-all-static:-vty" for example to leave out the vty
-- frontend, see the package.yaml file for all available flags)
-- 3. Run the built with "stack exec yi" (or just "yi" if you have $PATH
-- configured acc.)
-- (Please look at the command line options with "stack exec yi -- -h")
-- The final name of the executable can be changed in the "package.yaml" file.
import Control.Monad.State.Lazy (execStateT)
import Data.List (intersperse)
import Lens.Micro.Platform ((.=))
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
import Options.Applicative
import Yi hiding (option)
import Yi.Config.Simple.Types
import Yi.Buffer.Misc (lineMoveRel)
import Yi.Config.Default.HaskellMode (configureHaskellMode)
import Yi.Config.Default.JavaScriptMode (configureJavaScriptMode)
import Yi.Config.Default.MiscModes (configureMiscModes)
#ifdef VIM
import Yi.Config.Default.Vim (configureVim)
#endif
#ifdef VTY
import Yi.Config.Default.Vty (configureVty)
#endif
#ifdef EMACS
import Yi.Config.Default.Emacs (configureEmacs)
#endif
#ifdef PANGO
import Yi.Config.Default.Pango (configurePango)
#endif
frontends :: [(String, ConfigM ())]
frontends = [
#ifdef PANGO
("pango", configurePango),
#endif
#ifdef VTY
("vty", configureVty),
#endif
("", return ())
]
keymaps :: [(String, ConfigM ())]
keymaps = [
#ifdef EMACS
("emacs", configureEmacs),
#endif
#ifdef VIM
("vim", configureVim),
#endif
("", return ())
]
data CommandLineOptions = CommandLineOptions {
frontend :: Maybe String
, keymap :: Maybe String
, startOnLine :: Maybe Int
, files :: [String]
}
commandLineOptions :: Parser (Maybe CommandLineOptions)
commandLineOptions = flag' Nothing
( long "version"
<> short 'v'
<> help "Show the version number")
<|> (Just <$> (CommandLineOptions
<$> optional (strOption
( long "frontend"
<> short 'f'
<> metavar "FRONTEND"
<> help "The frontend to use (default is pango)"))
<*> optional (strOption
( long "keymap"
<> short 'k'
<> metavar "KEYMAP"
<> help "The keymap to use (default is emacs)"))
<*> optional (option auto
( long "line"
<> short 'l'
<> metavar "NUM"
<> help "Open the (last) file on line NUM"))
<*> many (argument str (metavar "FILES..."))
))
main :: IO ()
main = do
mayClo <- execParser opts
case mayClo of
Nothing -> putStrLn "Yi 0.14.1"
Just clo -> do
let openFileActions = intersperse (EditorA newTabE) (map (YiA . openNewFile) (files clo))
moveLineAction = YiA $ withCurrentBuffer (lineMoveRel (fromMaybe 0 (startOnLine clo)))
cfg <- execStateT
(runConfigM (myConfig (frontend clo) (keymap clo) >> (startActionsA .= (openFileActions ++ [moveLineAction]))))
defaultConfig
startEditor cfg Nothing
where
opts = info (helper <*> commandLineOptions)
( fullDesc
<> progDesc "Edit files"
<> header "Yi - a flexible and extensible text editor written in haskell")
myConfig :: Maybe String -> Maybe String -> ConfigM ()
myConfig f k = do
-- Lookup f in the frontends list or pick the first element of the frontends list if
-- f is nothing or do nothing if f is not found in the frontends list.
case f of
Nothing -> snd (head frontends)
Just f' -> fromMaybe (return ()) (lookup f' frontends)
-- Same as above, but then with k and keymaps
case k of
Nothing -> snd (head keymaps)
Just k' -> fromMaybe (return ()) (lookup k' keymaps)
configureHaskellMode
configureJavaScriptMode
configureMiscModes
| ethercrow/yi | example-configs/yi-all-static/Main.hs | gpl-2.0 | 4,167 | 4 | 22 | 962 | 945 | 513 | 432 | 73 | 3 |
{- |
Module : ./HasCASL/MatchCAD.hs
Description : MatchCAD program
Copyright : (c) Ewaryst Schulz, DFKI Bremen 2010
License : similar to LGPL, see HetCATS/LICENSE.txt or LIZENZ.txt
Maintainer : [email protected]
Stability : experimental
Portability : non-portable (via imports)
Program for matching to HasCASL exported CAD designs against design patterns
-}
import System.Environment
import System.Console.GetOpt
import HasCASL.InteractiveTests
import Data.Bits
import Data.Maybe
import Data.List
main :: IO ()
main = do
args <- getArgs
case processArgs args of
Left msg -> putStrLn $ "Design Matching: " ++ msg ++ "\n\n" ++ dmUsage
Right st -> runProg st >>= putStrLn
runProg :: ProgSettings -> IO String
runProg st
| translate st = matchTranslate (lib st) (spec st) (pattern st) $ design st
| otherwise = matchDesign (lib st) (spec st) (pattern st) $ design st
-- ----------------------- Input Arguments -------------------------
processArgs :: [String] -> Either String ProgSettings
processArgs args =
let (flags, noopts, unrecopts, errs) = getOpt' (ReturnInOrder PFLib) options args
msgl = checkFlags flags
f str (l, s) = if null l then str else str ++ "\n" ++ s ++ unlines l
msg = foldl f ""
[ (noopts, "non-handled extra arguments encountered ")
, (unrecopts, "unrecognized flags encountered ")
, (errs, "")
, (msgl, "")
]
in if null msg then Right $ getSettings flags else Left msg
dmHeader :: String
dmHeader = unlines
[ "Usage: matchcad [OPTION...] [file]"
, ""
, "matchcad /tmp/flange.het -sMatch -pFlangePattern -dComponent"
, ""
]
dmUsage :: String
dmUsage = usageInfo dmHeader options
{- | 'options' describes all available options and is used to generate usage
information -}
options :: [OptDescr ProgFlag]
-- Option [Char] [String] (ArgDescr a) String
options = map f
[ ( "lib", "Path to the hets file", ReqArg PFLib "FILE")
, ( "spec"
, "Name of specification importing both, the pattern and the design specification"
, ReqArg PFSpec "SPECNAME")
, ( "pattern", "Name of the pattern specification"
, ReqArg PFPattern "SPECNAME")
, ( "design", "Name of the design specification"
, ReqArg PFDesign "SPECNAME")
, ( "translate"
, "If this flag is set the match is further translated to an EnCL specification"
, NoArg PFTrans)
, ( "verbosity"
, "A value from 0=quiet to 4=print out all information during processing"
, OptArg (PFVerbosity . read . fromMaybe "4") "0-4")
, ( "quiet", "Equal to -v0", NoArg PFQuiet)
] where
f (fs, descr, arg) = Option [head fs] [fs] arg descr
checkFlags :: [ProgFlag] -> [String]
checkFlags = g . mapAccumL f (0 :: Int) where
f i (PFLib _) = (setBit i 0, ())
f i (PFSpec _) = (setBit i 1, ())
f i (PFPattern _) = (setBit i 2, ())
f i (PFDesign _) = (setBit i 3, ())
f i _ = (i, ())
g (i, _) = mapMaybe (h i) [ (0, "lib")
, (1, "spec")
, (2, "pattern")
, (3, "design") ]
h i (j, s)
| testBit i j = Nothing
| otherwise = Just $ s ++ " argument is missing"
data ProgSettings =
ProgSettings
{ lib :: String
, spec :: String
, pattern :: String
, design :: String
, translate :: Bool
, verbosity :: Int }
defaultSettings :: ProgSettings
defaultSettings = ProgSettings
{ lib = error "uninitialized settings"
, spec = error "uninitialized settings"
, pattern = error "uninitialized settings"
, design = error "uninitialized settings"
, translate = False
, verbosity = 4 }
data ProgFlag =
PFLib String
| PFSpec String
| PFPattern String
| PFDesign String
| PFVerbosity Int
| PFQuiet
| PFTrans
makeSettings :: ProgSettings -> ProgFlag -> ProgSettings
makeSettings settings flg =
case flg of
PFLib s -> settings { lib = s }
PFSpec s -> settings { spec = s }
PFPattern s -> settings { pattern = s }
PFDesign s -> settings { design = s }
PFVerbosity i -> settings { verbosity = i }
PFQuiet -> settings { verbosity = 0 }
PFTrans -> settings { translate = True }
getSettings :: [ProgFlag] -> ProgSettings
getSettings = foldl makeSettings defaultSettings
| gnn/Hets | HasCASL/MatchCAD.hs | gpl-2.0 | 4,678 | 21 | 13 | 1,460 | 1,225 | 660 | 565 | 103 | 7 |
--
-- Statistics collection
--
-- Copyright © 2012 Operational Dynamics Consulting, Pty Ltd
--
-- The code in this file, and the program it is a part of, is made available
-- to you by its authors as open source software: you can redistribute it
-- and/or modify it under the terms of the GNU General Public License version
-- 2 ("GPL") as published by the Free Software Foundation.
--
-- 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 GPL for more details.
--
-- You should have received a copy of the GPL along with this program. If not,
-- see http://www.gnu.org/licenses/. The authors of this program may be
-- contacted through http://research.operationaldynamics.com/
--
{-# LANGUAGE OverloadedStrings #-}
module ParseCommandAttoparsec where
import Prelude hiding (catch)
import Data.ByteString (ByteString)
import Control.Applicative
import Data.Attoparsec.ByteString.Char8
{-
import Control.Monad.Trans (liftIO)
import Control.Monad.CatchIO (catch)
import Control.Exception (SomeException)
-}
--
-- Parse a single "command" line coming from collectd, of the form
--
-- PUTVAL sirius.lhr.operationaldynamics.com/cpu-2/cpu-user interval=10.000 1351756697.945:0.103719
-- PUTVAL sirius.lhr.operationaldynamics.com/interface-eth0/if_packets interval=10.000 1351756688.304:1.79711:1.69727
-- PUTVAL sirius.lhr.operationaldynamics.com/load/load interval=10.000 1351756797.945:0.000000:0.010000:0.050000
--
-- as transmitted by the write_http plugin.
--
data Metric = Metric {
mIdentifier :: Identifier,
mInterval :: Double,
mTime :: Double,
mValue :: ByteString
} deriving (Show)
-- We'll be making a non linear shift from Collectd's measurements to a
-- datatype here, considering interface-eth0 to be a measurement but all the
-- cpu-* be a single measurement, cpu. We start by ignoring the plugin /
-- plugin-instance and type / type-instance distinction.
data Identifier = Identifier {
iHostname :: ByteString,
iPlugin :: ByteString,
iType :: ByteString
} deriving (Show, Eq)
parseLine :: Parser Metric
parseLine = do
i <- string "PUTVAL" *> skipSpace *> identifier
l <- skipSpace *> interval
t <- skipSpace *> timestamp
v <- value <* endOfLine
return Metric { mIdentifier = i, mInterval = l, mTime = t, mValue = v }
--
-- Parse a fragment in the following form
-- sirius.lhr.operationaldynamics.com/cpu-2/cpu-user
--
identifier :: Parser Identifier
identifier = do
h <- takeTill isSlash <* char '/'
p <- takeTill isSlash <* char '/'
t <- takeTill isSpace
return Identifier { iHostname = h, iPlugin = p, iType = t }
where
isSlash :: Char -> Bool
isSlash c = c == '/'
--
interval :: Parser Double
interval = do
string "interval=" *> double
timestamp :: Parser Double
timestamp =
double <* char ':'
value :: Parser ByteString
value =
takeTill theEnd
--
-- Annoyingly, isEndOfLine has type (Word8 -> Bool), so we have to cast.
--
theEnd :: Char -> Bool
theEnd c = isEndOfLine $ fromIntegral $ fromEnum c
parseLines :: Parser [Metric]
parseLines = many (many endOfLine *> parseLine)
processInputA :: ByteString -> Either String [Metric]
processInputA x' = parseOnly parseLines x'
| afcowie/metrics | src/ParseCommandAttoparsec.hs | gpl-2.0 | 3,353 | 0 | 10 | 606 | 502 | 286 | 216 | 47 | 1 |
-- collect all nodes from a tree
-- at a specific level
data Tree a = Empty | Branch a (Tree a) (Tree a) deriving Show
p62b :: Tree a -> Int -> [a]
p62b _ 0 = []
p62b Empty _ = []
p62b (Branch t l r) 1 = [t]
p62b (Branch t l r) n = p62b l (n-1) ++ p62b r (n-1)
| yalpul/CENG242 | H99/61-69/p62b.hs | gpl-3.0 | 263 | 2 | 9 | 68 | 161 | 79 | 82 | 6 | 1 |
{-# LANGUAGE Arrows #-}
{-# LANGUAGE FlexibleContexts #-}
module SugarScape.Agent.Trading
( agentTrade
, replyTradingOffer
) where
import Data.Maybe
import Control.Monad.Random
import Control.Monad.State.Strict
import Data.MonadicStreamFunction
import SugarScape.Agent.Common
import SugarScape.Agent.Interface
import SugarScape.Agent.Utils
import SugarScape.Core.Common
import SugarScape.Core.Discrete
import SugarScape.Core.Model
import SugarScape.Core.Random
import SugarScape.Core.Scenario
import SugarScape.Core.Utils
agentTrade :: RandomGen g
=> AgentLocalMonad g (SugAgentOut g, Maybe (EventHandler g))
-> AgentLocalMonad g (SugAgentOut g, Maybe (EventHandler g))
agentTrade cont =
ifThenElseM
((not . spTradingEnabled) <$> scenario)
cont
(tradingRound cont [])
tradingRound :: RandomGen g
=> AgentLocalMonad g (SugAgentOut g, Maybe (EventHandler g))
-> [TradeInfo]
-> AgentLocalMonad g (SugAgentOut g, Maybe (EventHandler g))
tradingRound cont tradeInfos = do
myCoord <- agentProperty sugAgCoord
-- (re-)fetch neighbours from environment, to get up-to-date information
ns <- envRun $ neighbours myCoord False
myMrs <- mrsM
-- filter out unoccupied sites and traders with same MRS (VERY unlikely with floating point)
let potentialTraders = mapMaybe (sugEnvSiteOccupier . snd) $ filter (\(_, ss) ->
case sugEnvSiteOccupier ss of
Nothing -> False
Just occ -> sugEnvOccMRS occ /= myMrs) ns
if null potentialTraders
then cont -- NOTE: no need to put tradeInfos into observable, because when no potential traders tradeInfos is guaranteed to be null
else do
potentialTraders' <- randLift $ fisherYatesShuffleM potentialTraders
tradeWith cont tradeInfos False potentialTraders'
tradeWith :: RandomGen g
=> AgentLocalMonad g (SugAgentOut g, Maybe (EventHandler g))
-> [TradeInfo]
-> Bool
-> [SugEnvSiteOccupier]
-> AgentLocalMonad g (SugAgentOut g, Maybe (EventHandler g))
tradeWith cont tradeInfos tradeOccured [] -- iterated through all potential traders => trading round has finished
| tradeOccured = tradingRound cont tradeInfos -- if we have traded with at least one agent, try another round
| otherwise = do
(ao, mhdl) <- cont
-- NOTE: at this point we add the trades to the observable output because finished with trading in this time-step
let ao' = observableTrades tradeInfos ao
return (ao', mhdl)
tradeWith cont tradeInfos tradeOccured (trader : ts) = do -- trade with next one
myState <- get
let myMrsBefore = mrsState myState -- agents mrs BEFORE trade
traderMrsBefore = sugEnvOccMRS trader -- trade-partners MRS BEFORE trade
(price, sugEx, spiEx) = computeExchange myMrsBefore traderMrsBefore -- amount of sugar / spice to trade
myWfBefore = agentWelfareState myState -- agents welfare BEFORE trade
myWfAfter = agentWelfareChangeState myState sugEx spiEx -- agents welfare AFTER trade
myMrsAfter = mrsStateChange myState sugEx spiEx -- agents mrs AFTER trade
-- NOTE: can't check crossover yet because don't have access to other traders internal state
-- the crossover will be checked by the other trader and in case of a crossover, the
-- trade will be refused. To compute the crossover we need to send the MRS after the
-- trade as well.
-- NOTE: check if it makes this agent better off: does it increase the agents welfare?
if myWfAfter <= myWfBefore
then tradeWith cont tradeInfos tradeOccured ts -- not better off, continue with next trader
else do
let evtHandler = tradingHandler cont tradeInfos tradeOccured ts (price, sugEx, spiEx)
-- expecting reply => use synchronous interaction channels
(receiveCh, replyCh) <- sendEventToWithReply (sugEnvOccId trader) (TradingOffer myMrsBefore myMrsAfter)
ao <- switchInteractionChannels receiveCh replyCh <$> agentObservableM
return (ao, Just evtHandler)
tradingHandler :: RandomGen g
=> AgentLocalMonad g (SugAgentOut g, Maybe (EventHandler g))
-> [TradeInfo]
-> Bool
-> [SugEnvSiteOccupier]
-> (Double, Double, Double)
-> EventHandler g
tradingHandler cont0 tradeInfos tradeOccured traders (price, sugEx, spiEx) =
continueWithAfter
(proc evt ->
case evt of
(Reply traderId (TradingReply r) _ _) ->
arrM (uncurry (handleTradingReply cont0)) -< (traderId, r)
_ -> do
aid <- constM myId -< ()
returnA -< error $ "Agent " ++ show aid ++ ": received unexpected event " ++ show evt ++ " during active Trading, terminating simulation!")
where
handleTradingReply :: RandomGen g
=> AgentLocalMonad g (SugAgentOut g, Maybe (EventHandler g))
-> AgentId
-> TradingReply
-> AgentLocalMonad g (SugAgentOut g, Maybe (EventHandler g))
handleTradingReply cont _ (RefuseTrade _) =
-- the sender refuses the trading-offer, continue with the next trader
tradeWith cont tradeInfos tradeOccured traders
handleTradingReply cont traderId AcceptTrade = do -- the sender accepts the trading-offer
-- NOTE: at this point the trade-partner agent is better off as well, MRS won't cross over and the other agent has already transacted
let tradeInfos' = TradeInfo price sugEx spiEx traderId : tradeInfos
transactTradeWealth sugEx spiEx
-- continue with next trader
tradeWith cont tradeInfos' True traders
replyTradingOffer :: RandomGen g
=> AgentId
-> SugReplyChannel
-> SugReplyChannel
-> Double
-> Double
-> AgentLocalMonad g (SugAgentOut g)
replyTradingOffer _traderId _receiveCh replyCh traderMrsBefore traderMrsAfter = do
myState <- get
let myMrsBefore = mrsState myState -- agents mrs BEFORE trade
-- amount of sugar / spice to trade
(_, sugEx, spiEx) = computeExchange myMrsBefore traderMrsBefore
myWfBefore = agentWelfareState myState -- agents welfare BEFORE trade
myWfAfter = agentWelfareChangeState myState sugEx spiEx -- agents welfare AFTER trade
myMrsAfter = mrsStateChange myState sugEx spiEx -- agents mrs AFTER trade
if myWfAfter <= myWfBefore
-- not better off, turn offer down and switch into queue-processing
then reply replyCh (TradingReply $ RefuseTrade NoWelfareIncrease) >> agentObservableM
else
if mrsCrossover myMrsBefore traderMrsBefore myMrsAfter traderMrsAfter
-- MRS cross-over, turn offer down and switch into queue-processing
then reply replyCh (TradingReply $ RefuseTrade MRSCrossover) >> agentObservableM
else do
-- all good, transact and accept offer
transactTradeWealth sugEx spiEx
-- reply accept
reply replyCh (TradingReply AcceptTrade)
-- switch back into queue-processing
agentObservableM
mrsCrossover :: Double
-> Double
-> Double
-> Double
-> Bool
mrsCrossover mrs1Pre mrs2Pre mrs1Post mrs2Post
= compare mrs1Pre mrs2Pre /= compare mrs1Post mrs2Post
computeExchange :: Double
-> Double
-> (Double, Double, Double)
computeExchange myMrs otherMrs
| myMrs > otherMrs = (price, sugEx, -spiEx) -- spice flows from agent with higher mrs (myMrs) to agent with lower (otherMrs) => subtract spice from this agent and add sugar
| otherwise = (price, -sugEx, spiEx) -- sugar flows from agent with lower mrs (myMrs) to agent with higher (otherMrs) => subtract sugar for this agent and add spice
where
(price, sugEx, spiEx) = exchangeRates myMrs otherMrs
exchangeRates :: Double
-> Double
-> (Double, Double, Double)
exchangeRates myMrs otherMrs
| price > 1 = (price, 1, price) -- trading p units of spice for 1 unit of sugar
| otherwise = (price, 1 / price, 1) -- trading 1/p units of sugar for 1 unit of spice
where
price = sqrt (myMrs * otherMrs) -- price is the geometric mean
transactTradeWealth :: RandomGen g
=> Double
-> Double
-> AgentLocalMonad g ()
transactTradeWealth sugEx spiEx = do
-- NOTE: negative values shouldn't happen due to welfare increase / MRS crossover restrictions
-- but for security reasons make sure that we cap at 0 and cant go below
updateAgentState (\s -> s { sugAgSugarLevel = max (sugAgSugarLevel s + sugEx) 0
, sugAgSpiceLevel = max (sugAgSpiceLevel s + spiEx) 0 })
-- NOTE: need to update occupier-info in environment because wealth has (and MRS) changed
updateSiteOccupied | thalerjonathan/phd | public/towards/SugarScape/experimental/concurrent/src/SugarScape/Agent/Trading.hs | gpl-3.0 | 9,098 | 1 | 18 | 2,449 | 1,761 | 908 | 853 | 148 | 3 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Language.VHDL.Pretty
( pprr
, pprrText
) where
import Data.Char (intToDigit)
import Data.Data (Data)
import qualified Data.Text as T
import Data.Text.Lazy (toStrict)
import Numeric (showIntAtBase)
import Text.PrettyPrint.Mainland
import Text.PrettyPrint.Mainland.Class
import Language.VHDL.Parser.Util
import Language.VHDL.Syntax
--------------------------------------------------------------------------------
-- ** Pretty printing instances
instance Pretty AbstractLiteral where
ppr (ALitDecimal d) = ppr d
ppr (ALitBased b) = ppr b
instance Pretty AccessTypeDefinition where
ppr (AccessTypeDefinition s) = text "access" <+> ppr s
instance Pretty ActualDesignator where
ppr (ADExpression e) = ppr e
ppr (ADSignal n) = ppr n
ppr (ADVariable n) = ppr n
ppr (ADFile n) = ppr n
ppr ADOpen = text "open"
instance Pretty ActualPart where
ppr (APDesignator a) = ppr a
ppr (APFunction f a) = ppr f <+> parens (ppr a)
ppr (APType t a) = ppr t <+> parens (ppr a)
instance Pretty Aggregate where
ppr (Aggregate es) = parens (commasep $ map ppr es)
instance Pretty AliasDeclaration where
ppr (AliasDeclaration a sub n sig) =
hang' $
text "alias" <+>
ppr a <+> cond (colon <+>) sub <+> text "is" <+/> ppr n <> ppr' sig <> semi
instance Pretty AliasDesignator where
ppr (ADIdentifier i) = ppr i
ppr (ADCharacter c) = ppr c
ppr (ADOperator o) = ppr o
instance Pretty Allocator where
ppr (AllocSub s) = text "new" <+> ppr s
ppr (AllocQual q) = text "new" <+> ppr q
instance Pretty ArchitectureBody where
ppr (ArchitectureBody i n d s) =
stack [header, indent' (vppr d), text "begin", indent' (vppr s), footer]
where
header =
text "architecture" <+> ppr i <+> text "of" <+> ppr n <+> text "is"
footer = text "end architecture" <+> ppr i <> semi
instance Pretty ArrayTypeDefinition where
ppr (ArrU u) = ppr u
ppr (ArrC c) = ppr c
instance Pretty Assertion where
ppr (Assertion c r s) = stack [text "assert" <+> ppr c, report, severity]
where
report = indent' $ hang' $ cond (text "report" <+>) r
severity = indent' $ cond (text "severity" <+>) s
instance Pretty AssertionStatement where
ppr (AssertionStatement l a) = label l <+> ppr a <> semi
instance Pretty AssociationElement where
ppr (AssociationElement f a) = condR (text "=>") f <+> ppr a
ppr e@(AntiAssocEl s) = pprAnti e s
ppr e@(AntiAssocEls s) = pprAnti e s
instance Pretty AssociationList where
ppr (AssociationList as) = commasepBreak $ map ppr as
funCallAssocList :: AssociationList -> Doc
funCallAssocList (AssociationList as) = commasep $ map ppr as
instance Pretty AttributeDeclaration where
ppr (AttributeDeclaration i t) =
text "attribute" <+> ppr i <> colon <+> ppr t <> semi
instance Pretty AttributeName where
ppr (AttributeName p s d e) =
ppr p <> ppr' s <> char '\'' <> ppr d <> ppr (appL parens e)
instance Pretty AttributeSpecification where
ppr (AttributeSpecification d s e) =
hang' $
text "attribute" <+>
ppr d <+> text "of" <+/> ppr s <+> text "is" <+/> ppr e <> semi
instance Pretty BaseSpecifier where
ppr BinaryBase = text "B"
ppr OctalBase = text "O"
ppr HexBase = text "X"
ppr UnsignedBinaryBase = text "UB"
ppr UnsignedOctalBase = text "UO"
ppr UnsignedHexBase = text "UX"
ppr SignedBinaryBase = text "SB"
ppr SignedHoctalBase = text "SO"
ppr SignedHexBase = text "SX"
ppr Decimal = text "D"
instance Pretty BasedLiteral where
ppr (BasedLiteral b i f e) =
ppr b <> char '#' <> text (intToBase b i) <> condL' (char '.') (text <$> f) <>
char '#' <>
ppr e
instance Pretty BindingIndication where
ppr (BindingIndication e g p) =
stack [condL (text "use") e, ppr g, ppr p]
instance Pretty BitStringLiteral where
ppr (BitStringLiteral l b v) = ppr l <> ppr b <> ppr v
instance Pretty BitValue where
ppr (BitValue s) = ppr s
instance Pretty BlockConfiguration where
ppr (BlockConfiguration s u c) =
stack
[ text "for" <+> ppr s
, indent' $ pprlStack u
, indent' $ pprlStack c
, text "end for" <> semi
]
instance Pretty BlockDeclarativeItem where
ppr (BDISubprogDecl d) = ppr d
ppr (BDISubprogBody b) = ppr b
ppr (BDIType t) = ppr t
ppr (BDISubtype s) = ppr s
ppr (BDIConstant c) = ppr c
ppr (BDISignal s) = ppr s
ppr (BDIShared v) = ppr v
ppr (BDIFile f) = ppr f
ppr (BDIAlias a) = ppr a
ppr (BDIComp c) = ppr c
ppr (BDIAttrDecl a) = ppr a
ppr (BDIAttrSepc a) = ppr a
ppr (BDIConfigSepc c) = ppr c
ppr (BDIDisconSpec d) = ppr d
ppr (BDIUseClause u) = ppr u
ppr (BDIGroupTemp g) = ppr g
ppr (BDIGroup g) = ppr g
ppr e@(AntiBlockDecl s) = pprAnti e s
ppr e@(AntiBlockDecls s) = pprAnti e s
instance Pretty BlockHeader where
ppr (BlockHeader p g) = stack [go p, go g]
where
go
:: (Pretty a, Pretty b)
=> Maybe (a, Maybe b) -> Doc
go Nothing = empty
go (Just (a, mb)) = ppr a </> cond (indent' . (<> semi)) mb
instance Pretty BlockSpecification where
ppr (BSArch n) = ppr n
ppr (BSBlock l) = ppr l
ppr (BSGen l i) = ppr l <+> cond parens i
instance Pretty BlockStatement where
ppr (BlockStatement l g h d s) =
ppr l <> colon <+> stack [header, body, footer]
where
header =
text "block" <+>
cond parens g <+> text "is" `hangs` stack (ppr h : line : map ppr d)
body = text "begin" `hangs` stack (map ppr s)
footer = text "end block" <+> ppr l <> semi
instance Pretty CaseStatement where
ppr (CaseStatement l e cs) = labels l $ stack [header, body, footer]
where
header = text "case" <+> ppr e <+> text "is"
body = indent' $ stack $ map ppr cs
footer = text "end case" <> ppr' l <> semi
instance Pretty CaseStatementAlternative where
ppr (CaseStatementAlternative c ss) =
stack [text "when" <+> ppr c <+> text "=>", indent' $ stack $ map ppr ss]
ppr e@(AntiCasealt s) = pprAnti e s
ppr e@(AntiCasealts s) = pprAnti e s
instance Pretty CharacterLiteral where
ppr (CLit c) = char '\'' <> char c <> char '\''
ppr a@(AntiClit c) = pprAnti a c
instance Pretty Choice where
ppr (ChoiceSimple s) = ppr s
ppr (ChoiceRange r) = ppr r
ppr (ChoiceName n) = ppr n
ppr ChoiceOthers = text "others"
instance Pretty Choices where
ppr (Choices cs) = pipeSep $ map ppr cs
instance Pretty ComponentConfiguration where
ppr (ComponentConfiguration s i c) =
stack
[ text "for" <+> ppr s
, indent' $ stack [condR' semi i, ppr c]
, text "end for" <> semi
]
instance Pretty ComponentDeclaration where
ppr (ComponentDeclaration i g p) =
stack
[ text "component" <+> ppr i <+> text "is"
, indent' $ stack [ppr g, ppr p]
, text "end component" <+> ppr i <> semi
]
instance Pretty ComponentInstantiationStatement where
ppr (ComponentInstantiationStatement l u g p) =
ppr l <> colon <+> (ppr u `hangs` stack [ppr g, ppr p]) <> semi
instance Pretty ComponentSpecification where
ppr (ComponentSpecification ls n) = ppr ls <> colon <+> ppr n
instance Pretty CompositeTypeDefinition where
ppr (CTDArray at) = ppr at
ppr (CTDRecord rt) = ppr rt
instance Pretty ConcurrentAssertionStatement where
ppr (ConcurrentAssertionStatement l p a) = postponed l p a <> semi
instance Pretty ConcurrentProcedureCallStatement where
ppr (ConcurrentProcedureCallStatement l p a) = postponed l p a <> semi
instance Pretty ConcurrentSignalAssignmentStatement where
ppr (CSASCond l p a) = postponed l p a
ppr (CSASSelect l p a) = postponed l p a
instance Pretty ConcurrentStatement where
ppr (ConBlock b) = ppr b
ppr (ConProcess p) = ppr p
ppr (ConProcCall c) = ppr c
ppr (ConAssertion a) = ppr a
ppr (ConSignalAss s) = ppr s
ppr (ConComponent c) = ppr c
ppr (ConGenerate g) = ppr g
ppr a@(AntiConStm s) = pprAnti a s
ppr a@(AntiConStms s) = pprAnti a s
instance Pretty ConditionClause where
ppr (ConditionClause e) = text "until" <+> ppr e
instance Pretty ConditionalSignalAssignment where
ppr (ConditionalSignalAssignment t o w) =
hang' $ ppr t <+> text "<=" <+/> ppr o <+> ppr w <> semi
instance Pretty ConditionalWaveforms where
ppr (ConditionalWaveforms ws (w, c)) =
stack ws' <+> ppr w <+> condL (text "when") c
where
ws' =
map (\(w', c') -> ppr w' <+> text "when" <+> ppr c' <+> text "else") ws
instance Pretty ConfigurationDeclaration where
ppr (ConfigurationDeclaration i n d b) =
stack
[ text "configuration" <+> ppr i <+> text "of" <+> ppr n <+> text "is"
, indent' $ stack (map ppr d ++ [ppr b])
, text "end configuration" <+> ppr i <> semi
]
instance Pretty ConfigurationDeclarativeItem where
ppr (CDIUse u) = ppr u
ppr (CDIAttrSpec a) = ppr a
ppr (CDIGroup g) = ppr g
instance Pretty ConfigurationItem where
ppr (CIBlock b) = ppr b
ppr (CIComp c) = ppr c
instance Pretty ConfigurationSpecification where
ppr (ConfigurationSpecification s i) = text "for" <+> ppr s <+> ppr i <> semi
instance Pretty ConstantDeclaration where
ppr (ConstantDeclaration is s e) =
hang' $ text "constant" <+>
commasep (fmap ppr is) <> colon <+/> ppr s <+> condL (text ":=") e <> semi
instance Pretty ConstrainedArrayDefinition where
ppr (ConstrainedArrayDefinition i s) =
text "array" <+> ppr i <+> text "of" <+> ppr s
instance Pretty Constraint where
ppr (CRange r) = ppr r
ppr (CIndex i) = ppr i
instance Pretty ContextClause where
ppr (ContextClause items) = stack $ fmap ppr items
instance Pretty ContextItem where
ppr (ContextLibrary l) = ppr l
ppr (ContextUse u) = ppr u
ppr e@(AntiContextItem i) = pprAnti e i
ppr e@(AntiContextItems i) = pprAnti e i
instance Pretty DecimalLiteral where
ppr (DecimalLiteral i f e) = ppr i <> condL' (char '.') (text <$> f) <> ppr e
instance Pretty Declaration where
ppr (DType t) = ppr t
ppr (DSubtype s) = ppr s
ppr (DObject o) = ppr o
ppr (DAlias a) = ppr a
ppr (DComponent c) = ppr c
ppr (DAttribute a) = ppr a
ppr (DGroupTemplate g) = ppr g
ppr (DGroup g) = ppr g
ppr (DEntity e) = ppr e
ppr (DConfiguration c) = ppr c
ppr (DSubprogram s) = ppr s
ppr (DPackage p) = ppr p
instance Pretty DelayMechanism where
ppr DMechTransport = text "transport"
ppr (DMechInertial e) = condL (text "reject") e <+> text "inertial"
instance Pretty DesignFile where
ppr (DesignFile units) = stack $ fmap ppr units
instance Pretty DesignUnit where
ppr (DesignUnit ctxt lib) = stack [ppr ctxt, ppr lib]
ppr a@(AntiDesignUnit s) = pprAnti a s
ppr a@(AntiDesignUnits s) = pprAnti a s
instance Pretty Designator where
ppr (DId i) = ppr i
ppr (DOp o) = ppr o
instance Pretty Direction where
ppr To = text "to"
ppr DownTo = text "downto"
instance Pretty DisconnectionSpecification where
ppr (DisconnectionSpecification g e) =
text "disconnect" <+> ppr g <+> text "after" <+> ppr e <> semi
instance Pretty DiscreteRange where
ppr (DRSub s) = ppr s
ppr (DRRange r) = ppr r
instance Pretty ElementAssociation where
ppr (ElementAssociation c e) = condR (text "=>") c <+> ppr e
ppr a@(AntiElAssoc s) = pprAnti a s
ppr a@(AntiElAssocs s) = pprAnti a s
instance Pretty ElementDeclaration where
ppr (ElementDeclaration is s) = commasep (map ppr is) <> colon <+> ppr s <> semi
instance Pretty EntityAspect where
ppr (EAEntity n i) = text "entity" <+> ppr n <+> cond parens i
ppr (EAConfig n) = text "configuration" <+> ppr n
ppr EAOpen = text "open"
instance Pretty EntityClass where
ppr ENTITY = text "entity"
ppr ARCHITECTURE = text "architecture"
ppr CONFIGURATION = text "configuration"
ppr PROCEDURE = text "procedure"
ppr FUNCTION = text "function"
ppr PACKAGE = text "package"
ppr TYPE = text "type"
ppr SUBTYPE = text "subtype"
ppr CONSTANT = text "constant"
ppr SIGNAL = text "signal"
ppr VARIABLE = text "variable"
ppr COMPONENT = text "Component"
ppr LABEL = text "Label"
ppr LITERAL = text "literal"
ppr UNITS = text "units"
ppr GROUP = text "group"
ppr FILE = text "file"
instance Pretty EntityClassEntry where
ppr (EntityClassEntry c m) = ppr c <+> when m (text "<>")
instance Pretty EntityDeclaration where
ppr (EntityDeclaration i h d s) =
stack
[ line
, text "entity" <+> ppr i <+> text "is"
, indent' $ stack (ppr h : map ppr d)
, hang' $ ppr (catL (text "begin" <> line) stack <$> (map ppr <$> s))
, text "end entity" <+> ppr i <> semi </> text ""
]
instance Pretty EntityDeclarativeItem where
ppr (EDISubprogDecl s) = ppr s
ppr (EDISubprogBody b) = ppr b
ppr (EDIType t) = ppr t
ppr (EDISubtype s) = ppr s
ppr (EDIConstant c) = ppr c
ppr (EDISignal s) = ppr s
ppr (EDIShared s) = ppr s
ppr (EDIFile f) = ppr f
ppr (EDIAlias a) = ppr a
ppr (EDIAttrDecl a) = ppr a
ppr (EDIAttrSpec a) = ppr a
ppr (EDIDiscSpec d) = ppr d
ppr (EDIUseClause u) = ppr u
ppr (EDIGroupTemp g) = ppr g
ppr (EDIGroup g) = ppr g
instance Pretty EntityDesignator where
ppr (EntityDesignator t s) = ppr t <> ppr' s
instance Pretty EntityHeader where
ppr (EntityHeader g p) = stack [cond indent' g, cond indent' p]
instance Pretty EntityNameList where
ppr (ENLDesignators es) = commasep $ fmap ppr es
ppr ENLOthers = text "others"
ppr ENLAll = text "all"
instance Pretty EntitySpecification where
ppr (EntitySpecification ns c) = ppr ns <> colon <+> ppr c
instance Pretty EntityStatement where
ppr (ESConcAssert a) = ppr a
ppr (ESPassiveConc p) = ppr p
ppr (ESPassiveProc p) = ppr p
instance Pretty EntityTag where
ppr (ETName n) = ppr n
ppr (ETChar c) = ppr c
ppr (ETOp o) = ppr o
instance Pretty EnumerationLiteral where
ppr (EId i) = ppr i
ppr (EChar c) = ppr c
instance Pretty EnumerationTypeDefinition where
ppr (EnumerationTypeDefinition es) = parens $ commasep $ fmap ppr es
instance Pretty ExitStatement where
ppr (ExitStatement l b c) =
label l <+> text "exit" <> ppr' b <> condL (space <> text "when") c <> semi
instance Pretty Exponent where
ppr (ExponentPos i) = char 'e' <> ppr i
ppr (ExponentNeg i) = char 'e' <> char '-' <> ppr i
instance Pretty Expression where
ppr (Unary op@Identity e) = ppr op <> ppr e
ppr (Unary op@Negation e) = ppr op <> ppr e
ppr (Unary op e) = ppr op <+> ppr e
ppr (Binary op e1 e2) = ppr e1 <+> ppr op <+/> ppr e2
ppr (PrimName n) = ppr n
ppr (PrimLit l) = ppr l
ppr (PrimAgg a) = ppr a
ppr (PrimFun f) = ppr f
ppr (PrimQual q) = ppr q
ppr (PrimTCon t) = ppr t
ppr (PrimAlloc a) = ppr a
ppr (PrimExp e) = text "(" <> ppr e <> text ")"
ppr a@(AntiExpr e) = pprAnti a e
instance Pretty BinOp where
ppr And = text "and"
ppr Or = text "or"
ppr Nand = text "nand"
ppr Nor = text "nor"
ppr Xor = text "xor"
ppr Xnor = text "xnor"
ppr Eq = text "="
ppr Neq = text "/="
ppr Lt = text "<"
ppr Lte = text "<="
ppr Gt = text ">"
ppr Gte = text ">="
ppr Sll = text "sll"
ppr Srl = text "srl"
ppr Sla = text "sla"
ppr Sra = text "sra"
ppr Rol = text "rol"
ppr Ror = text "ror"
ppr Times = text "*"
ppr Div = text "/"
ppr Mod = text "mod"
ppr Rem = text "rem"
ppr Plus = text "+"
ppr Minus = text "-"
ppr Concat = text "&"
ppr Exp = text "**"
instance Pretty UnOp where
ppr Identity = text "+"
ppr Negation = text "-"
ppr Abs = text "abs"
ppr Not = text "not"
instance Pretty FileDeclaration where
ppr (FileDeclaration is s o) =
hang' $ text "file" <+>
commasep (fmap ppr is) <> colon <+/> ppr s <> ppr' o <> semi
instance Pretty FileOpenInformation where
ppr (FileOpenInformation e n) = condL (text "open") e <+> text "is" <+> ppr n
instance Pretty FileTypeDefinition where
ppr (FileTypeDefinition t) = text "file of" <+> ppr t
instance Pretty FormalDesignator where
ppr (FDGeneric n) = ppr n
ppr (FDPort n) = ppr n
ppr (FDParameter n) = ppr n
instance Pretty FormalPart where
ppr (FPDesignator d) = ppr d
ppr (FPFunction n d) = ppr n <+> parens (ppr d)
ppr (FPType t d) = ppr t <+> parens (ppr d)
instance Pretty FullTypeDeclaration where
ppr (FullTypeDeclaration i t) =
hang' $ text "type" <+> ppr i <+> text "is" <+/> ppr t <> semi
instance Pretty FunctionCall where
ppr (FunctionCall n p) = ppr n <> ppr (parens . funCallAssocList <$> p)
instance Pretty FunctionName where
ppr (FNSelected n) = ppr n
ppr (FNSimple n) = ppr n
ppr (FNOp n) = ppr n
instance Pretty GenerateStatement where
ppr (GenerateStatement l g d s) =
ppr l <> colon `hangs`
stack
[ ppr g <+> text "generate"
, cond indent' (pprlStack <$> d)
, cond (const $ text "begin") d
, indent' $ stack $ fmap ppr s
, text "end generate" <+> ppr l <> semi
]
instance Pretty GenerationScheme where
ppr (GSFor p) = text "for" <+> ppr p
ppr (GSIf c) = text "if" <+> ppr c
instance Pretty GenericClause where
ppr (GenericClause ls) = text "generic" <+> parens (ppr ls) <> semi
instance Pretty GenericMapAspect where
ppr (GenericMapAspect as) = text "generic map" <+> parens (ppr as)
instance Pretty GroupConstituent where
ppr (GCName n) = ppr n
ppr (GCChar c) = ppr c
instance Pretty GroupTemplateDeclaration where
ppr (GroupTemplateDeclaration i cs) =
text "group" <+>
ppr i <+> text "is" <+> parens (commasep (map ppr cs)) <> semi
instance Pretty GroupDeclaration where
ppr (GroupDeclaration i n cs) =
text "group" <+>
ppr i <> colon <+> ppr n <+> parens (commasep (map ppr cs)) <> semi
instance Pretty GuardedSignalSpecification where
ppr (GuardedSignalSpecification ss t) = ppr ss <> colon <+> ppr t
instance Pretty Identifier where
ppr (Ident i) = ppr i
ppr (ExtendedIdent i) = char '\\' <> ppr i <> char '\\'
ppr a@(AntiIdent i) = pprAnti a i
instance Pretty IfStatement where
ppr (IfStatement l (tc, ts) a e) =
labels l $
stack
[ (text "if" <+> ppr tc <+> text "then") `hangs` vppr ts
, elseIf' a
, else' e
, text "end if" <> ppr' l <> semi
]
where
elseIf' :: [(Condition, SequenceOfStatements)] -> Doc
elseIf' =
stack .
fmap
(\(c, ss) -> (text "elsif" <+> ppr c <+> text "then") `hangs` vppr ss)
else' :: Maybe SequenceOfStatements -> Doc
else' Nothing = empty
else' (Just ss) = text "else" `hangs` vppr ss
instance Pretty IncompleteTypeDeclaration where
ppr (IncompleteTypeDeclaration i) = text "type" <+> ppr i <> semi
instance Pretty IndexConstraint where
ppr (IndexConstraint rs) = parens (commasep $ map ppr rs)
instance Pretty IndexSpecification where
ppr (ISRange r) = ppr r
ppr (ISExp e) = ppr e
instance Pretty IndexSubtypeDefinition where
ppr (IndexSubtypeDefinition t) = ppr t <+> text "range" <+> text "<>"
instance Pretty IndexedName where
ppr (IndexedName p es) = ppr p <> enclosesep lparen rparen comma (map ppr es)
instance Pretty InstantiatedUnit where
ppr (IUComponent n) = text "component" <+> ppr n
ppr (IUEntity n i) = text "entity" <+> ppr n <+> cond parens i
ppr (IUConfig n) = text "configuration" <+> ppr n
instance Pretty InstantiationList where
ppr (ILLabels ls) = commasep $ map ppr ls
ppr ILOthers = text "others"
ppr ILAll = text "all"
instance Pretty InterfaceDeclaration where
ppr (InterfaceVariableDeclaration is m s e) =
text "variable" <+>
commasep (fmap ppr is) <> colon <>
ppr' m <+> ppr s <+> condL (text ":=") e
ppr (InterfaceSignalDeclaration is m s b e) =
text "signal" <+>
commasep (fmap ppr is) <> colon <>
ppr' m <+> ppr s <+> when b (text "bus") <+> condL (text ":=") e
ppr (InterfaceConstantDeclaration is s e) =
text "constant" <+>
commasep (fmap ppr is) <> colon <+>
text "in" <+> ppr s <+> condL (text ":=") e
ppr (InterfaceFileDeclaration is s) =
text "file" <+> commasep (fmap ppr is) <> colon <+> ppr s
ppr a@(AntiIfaceDecl s) = pprAnti a s
ppr a@(AntiIfaceDecls s) = pprAnti a s
instance Pretty InterfaceList where
ppr (InterfaceList es) = stack $ map hang' $ punctuate semi $ map ppr es
instance Pretty IterationScheme where
ppr (IterWhile c) = text "while" <+> ppr c
ppr (IterFor p) = text "for" <+> ppr p
instance Pretty LibraryClause where
ppr (LibraryClause ns) = text "library" <+> ppr ns <> semi
instance Pretty LibraryUnit where
ppr (LibraryPrimary p) = ppr p
ppr (LibrarySecondary s) = ppr s
ppr a@(AntiLibraryUnit s) = pprAnti a s
instance Pretty Literal where
ppr (LitNum n) = ppr n
ppr (LitEnum e) = ppr e
ppr (LitString s) = ppr s
ppr (LitBitString b) = ppr b
ppr LitNull = text "null"
ppr a@(AntiLit s) = pprAnti a s
instance Pretty LogicalNameList where
ppr (LogicalNameList ns) = commasep $ fmap ppr ns
instance Pretty LoopStatement where
ppr (LoopStatement l i ss) =
labels l $
stack
[ (ppr i <+> text "loop") `hangs` vppr ss
, text "end loop" <> ppr' l <> semi
]
instance Pretty Mode where
ppr In = text "in"
ppr Out = text "out"
ppr InOut = text "inout"
ppr Buffer = text "buffer"
ppr Linkage = text "linkage"
instance Pretty Name where
ppr (NSimple n) = ppr n
ppr (NOp o) = ppr o
ppr (NSelect s) = ppr s
ppr (NIndex i) = ppr i
ppr (NSlice s) = ppr s
ppr (NAttr a) = ppr a
ppr a@(AntiName n) = pprAnti a n
instance Pretty NextStatement where
ppr (NextStatement l b c) =
label l <+> text "next" <> ppr' b <> condL (space <> text "when") c <> semi
instance Pretty NullStatement where
ppr (NullStatement l) = label l <+> text "null" <> semi
instance Pretty NumericLiteral where
ppr (NLitAbstract a) = ppr a
ppr (NLitPhysical p) = ppr p
ppr a@(AntiLitnum n) = pprAnti a n
instance Pretty ObjectDeclaration where
ppr (ObjConst c) = ppr c
ppr (ObjSig s) = ppr s
ppr (ObjVar v) = ppr v
ppr (ObjFile f) = ppr f
instance Pretty Options where
ppr (Options g d) = when g (text "guarded") <> ppr' d
instance Pretty PackageBody where
ppr (PackageBody n d) =
stack
[ text "package body" <+> ppr n <+> text "is"
, indent' $ block d
, text "end package body" <+> ppr n <> semi
]
instance Pretty PackageBodyDeclarativeItem where
ppr (PBDISubprogDecl s) = ppr s
ppr (PBDISubprogBody b) = ppr b
ppr (PBDIType t) = ppr t
ppr (PBDISubtype s) = ppr s
ppr (PBDIConstant c) = ppr c
ppr (PBDIShared s) = ppr s
ppr (PBDIFile f) = ppr f
ppr (PBDIAlias a) = ppr a
ppr (PBDIUseClause u) = ppr u
ppr (PBDIGroupTemp g) = ppr g
ppr (PBDIGroup g) = ppr g
instance Pretty PackageDeclaration where
ppr (PackageDeclaration i d) =
stack
[ text "package" <+> ppr i <+> text "is"
, indent' $ block d
, text "end package" <+> ppr i <> semi
]
instance Pretty PackageDeclarativeItem where
ppr (PHDISubprogDecl s) = ppr s
ppr (PHDISubprogBody b) = ppr b
ppr (PHDIType t) = ppr t
ppr (PHDISubtype s) = ppr s
ppr (PHDIConstant c) = ppr c
ppr (PHDISignal s) = ppr s
ppr (PHDIShared v) = ppr v
ppr (PHDIFile f) = ppr f
ppr (PHDIAlias a) = ppr a
ppr (PHDIComp c) = ppr c
ppr (PHDIAttrDecl a) = ppr a
ppr (PHDIAttrSpec a) = ppr a
ppr (PHDIDiscSpec d) = ppr d
ppr (PHDIUseClause u) = ppr u
ppr (PHDIGroupTemp g) = ppr g
ppr (PHDIGroup g) = ppr g
ppr a@(AntiPackDeclIt s) = pprAnti a s
ppr a@(AntiPackDeclIts s) = pprAnti a s
instance Pretty ParameterSpecification where
ppr (ParameterSpecification i r) = ppr i <+> text "in" <+> ppr r
instance Pretty PhysicalLiteral where
ppr (PhysicalLiteral a n) = ppr a <+> ppr n
instance Pretty PhysicalTypeDefinition where
ppr (PhysicalTypeDefinition c p s n) =
ppr c `hangs`
stack
[ text "units"
, indent' $ stack [ppr p <> semi, stack $ map (\x -> ppr x <> semi) s]
, text "end units" <> ppr' n
]
instance Pretty PortClause where
ppr (PortClause ls) = text "port" <+> parens (ppr ls) <> semi
instance Pretty PortMapAspect where
ppr (PortMapAspect as) = text "port map" <+> parens (ppr as)
instance Pretty Prefix where
ppr (PName n) = ppr n
ppr (PFun f) = ppr f
instance Pretty PrimaryUnit where
ppr (PrimaryEntity e) = ppr e
ppr (PrimaryConfig c) = ppr c
ppr (PrimaryPackage p) = ppr p
ppr a@(AntiPrimaryUnit p) = pprAnti a p
instance Pretty ProcedureCall where
ppr (ProcedureCall n ap) = ppr n <> ppr (parens . funCallAssocList <$> ap)
instance Pretty ProcedureCallStatement where
ppr (ProcedureCallStatement l p) = label l <+> ppr p <> semi
instance Pretty ProcessDeclarativeItem where
ppr (PDISubprogDecl s) = ppr s
ppr (PDISubprogBody b) = ppr b
ppr (PDIType t) = ppr t
ppr (PDISubtype s) = ppr s
ppr (PDIConstant c) = ppr c
ppr (PDIVariable v) = ppr v
ppr (PDIFile f) = ppr f
ppr (PDIAlias a) = ppr a
ppr (PDIAttrDecl a) = ppr a
ppr (PDIAttrSpec a) = ppr a
ppr (PDIUseClause u) = ppr u
ppr a@(AntiProcDecl s) = pprAnti a s
ppr a@(AntiProcDecls s) = pprAnti a s
instance Pretty ProcessStatement where
ppr (ProcessStatement l p ss d s) =
labels l $
stack
[ (post <+> cond parens ss <+> text "is") `hangs` vppr d
, text "begin" `hangs` vppr s
, text "end" <+> post <> ppr' l <> semi
]
where
post = when p (text "postponed") <+> text "process"
instance Pretty QualifiedExpression where
ppr (QualExp t e) = ppr t <> char '\'' <> parens (ppr e)
ppr (QualAgg t a) = ppr t <> char '\'' <> ppr a
instance Pretty Range where
ppr (RAttr a) = ppr a
ppr (RSimple l d u) = ppr l <+> ppr d <+> ppr u
instance Pretty RangeConstraint where
ppr (RangeConstraint r) = text "range" <+> ppr r
instance Pretty RecordTypeDefinition where
ppr (RecordTypeDefinition es n) =
stack [text "record", stack $ map ppr es, text "end record" <> ppr' n]
instance Pretty ReportStatement where
ppr (ReportStatement l e s) =
hang'
(labels l (text "report" <+> ppr e <> condL (indent' $ text "severity") s) <>
semi)
instance Pretty ReturnStatement where
ppr (ReturnStatement l e) = label l <+> text "return" <> ppr' e <> semi
instance Pretty ScalarTypeDefinition where
ppr (ScalarEnum e) = ppr e
ppr (ScalarInt i) = ppr i
ppr (ScalarFloat f) = ppr f
ppr (ScalarPhys p) = ppr p
instance Pretty SecondaryUnit where
ppr (SecondaryArchitecture a) = ppr a
ppr (SecondaryPackage p) = ppr p
ppr a@(AntiSecondaryUnit v) = pprAnti a v
instance Pretty SecondaryUnitDeclaration where
ppr (SecondaryUnitDeclaration i p) = ppr i <+> equals <+> ppr p
instance Pretty SelectedName where
ppr (SelectedName p s) = ppr p <> char '.' <> ppr s
instance Pretty SelectedSignalAssignment where
ppr (SelectedSignalAssignment e t o w) =
text "with" <+>
ppr e <+>
text "select" `hangs` ppr t <+> text "<=" <+/> ppr o <+> ppr w <> semi
instance Pretty SelectedWaveforms where
ppr (SelectedWaveforms ws) = stack (punctuate comma sws)
where
sws = map f ws
f (w, c) = ppr w <+> text "when" <+> ppr c
instance Pretty SensitivityClause where
ppr (SensitivityClause ss) = text "on" <+> ppr ss
instance Pretty SensitivityList where
ppr (SensitivityList ns) = commasep $ map ppr ns
instance Pretty SequentialStatement where
ppr (SWait w) = ppr w
ppr (SAssert a) = ppr a
ppr (SReport r) = ppr r
ppr (SSignalAss s) = ppr s
ppr (SVarAss v) = ppr v
ppr (SProc p) = ppr p
ppr (SIf i) = ppr i
ppr (SCase c) = ppr c
ppr (SLoop l) = ppr l
ppr (SNext n) = ppr n
ppr (SExit e) = ppr e
ppr (SReturn r) = ppr r
ppr (SNull n) = ppr n
ppr a@(AntiSeqStm s) = pprAnti a s
ppr a@(AntiSeqStms s) = pprAnti a s
instance Pretty SignalAssignmentStatement where
ppr (SignalAssignmentStatement l t d w) =
hang' $
label l <+> ppr t <+> text "<=" <> ppr' d <> softline <> ppr w <> semi
instance Pretty SignalDeclaration where
ppr (SignalDeclaration is s k e) =
text "signal" <+>
commasep (fmap ppr is) <> colon <+>
ppr s <> ppr' k <> condL ( space <> text ":=") e <> semi
instance Pretty SignalKind where
ppr Register = text "register"
ppr Bus = text "bus"
instance Pretty SignalList where
ppr (SLName ns) = commasep $ map ppr ns
ppr SLOthers = text "others"
ppr SLAll = text "all"
instance Pretty Signature where
ppr (Signature (ts, t)) = brackets $ initial <+> condL (text "return") t
where
initial = commasep $ maybe [] (map ppr) ts
instance Pretty SliceName where
ppr (SliceName p r) = ppr p <> parens (ppr r)
instance Pretty StringLiteral where
ppr (SLit s) = char '\"' <> text (fixQuotes (T.unpack s)) <> char '\"'
where
fixQuote xs '"' = xs ++ "\"\""
fixQuote xs x = xs ++ [x]
fixQuotes = foldl fixQuote []
ppr a@(AntiSlit s) = pprAnti a s
instance Pretty SubprogramBody where
ppr (SubprogramBody s d st k de) =
stack
[ ppr s <+> text "is"
, indent' $ block d
, text "begin"
, indent' $ block st
, text "end" <> ppr' k <> ppr' de <> semi <> line
]
instance Pretty SubprogramDeclarativeItem where
ppr (SDISubprogDecl d) = ppr d
ppr (SDISubprogBody b) = ppr b
ppr (SDIType t) = ppr t
ppr (SDISubtype s) = ppr s
ppr (SDIConstant c) = ppr c
ppr (SDIVariable v) = ppr v
ppr (SDIFile f) = ppr f
ppr (SDIAlias a) = ppr a
ppr (SDIAttrDecl a) = ppr a
ppr (SDIAttrSpec a) = ppr a
ppr (SDIUseClause u) = ppr u
ppr (SDIGroupTemp g) = ppr g
ppr (SDIGroup g) = ppr g
instance Pretty SubprogramKind where
ppr Procedure = text "procedure"
ppr Function = text "function"
instance Pretty SubprogramDeclaration where
ppr (SubprogramDeclaration s) = ppr s <> semi
instance Pretty SubprogramSpecification where
ppr (SubprogramProcedure d fs) = text "procedure" <+> ppr d <+> cond parens fs
ppr (SubprogramFunction p d fs t) =
purity <+>
text "function" <+> ppr d <+> cond parens fs <+> text "return" <+> ppr t
where
purity =
case p of
Nothing -> empty
Just True -> text "pure"
Just False -> text "impure"
instance Pretty SubtypeDeclaration where
ppr (SubtypeDeclaration i s) =
hang' $ text "subtype" <+> ppr i <+> text "is" <+/> ppr s <> semi
instance Pretty SubtypeIndication where
ppr (SubtypeIndication n t c) = ppr' n <+> ppr t <> ppr' c
ppr a@(AntiSubtyInd s) = pprAnti a s
instance Pretty Suffix where
ppr (SSimple n) = ppr n
ppr (SChar c) = ppr c
ppr (SOp o) = ppr o
ppr SAll = text "all"
instance Pretty Target where
ppr (TargetName n) = ppr n
ppr (TargetAgg a) = ppr a
instance Pretty TimeoutClause where
ppr (TimeoutClause e) = text "for" <+> ppr e
instance Pretty TypeConversion where
ppr (TypeConversion t e) = ppr t <+> parens (ppr e)
instance Pretty TypeDeclaration where
ppr (TDFull ft) = ppr ft
ppr (TDPartial pt) = ppr pt
instance Pretty TypeDefinition where
ppr (TDScalar s) = ppr s
ppr (TDComposite c) = ppr c
ppr (TDAccess a) = ppr a
ppr (TDFile f) = ppr f
instance Pretty TypeMark where
ppr (TMType n) = ppr n
ppr (TMSubtype n) = ppr n
instance Pretty UnconstrainedArrayDefinition where
ppr (UnconstrainedArrayDefinition is s) =
text "array" <+> parens (commasep $ map ppr is) <+> text "of" <+> ppr s
instance Pretty UseClause where
ppr (UseClause ns) = text "use" <+> commasep (map ppr ns) <> semi
instance Pretty VariableAssignmentStatement where
ppr (VariableAssignmentStatement l t e) =
hang' $ label l <+> ppr t <+> text ":=" <+/> ppr e <> semi
instance Pretty VariableDeclaration where
ppr (VariableDeclaration s is sub e) =
hang' $
when s (text "shared") <+>
text "variable" <+>
commasep (fmap ppr is) <> colon <+/>
ppr sub <> condL (space <> text ":=") e <> semi
instance Pretty WaitStatement where
ppr (WaitStatement l sc cc tc) =
label l <+> text "wait" <> ppr' sc <> ppr' cc <> ppr' tc <> semi
instance Pretty Waveform where
ppr (WaveElem es) = commasep $ map ppr es
ppr WaveUnaffected = text "unaffected"
ppr a@(AntiWave v) = pprAnti a v
instance Pretty WaveformElement where
ppr (WaveEExp e te) = ppr e <+> condL (text "after") te
ppr (WaveENull te) = text "null" <+> condL (text "after") te
--------------------------------------------------------------------------------
-- * Some helpers
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- text sep.
pipeSep :: [Doc] -> Doc
pipeSep = align . sep . punctuate (space <> char '|')
--------------------------------------------------------------------------------
-- indentation
il :: Int
il = 4
indent' :: Doc -> Doc
indent' = indent il
hang' :: Doc -> Doc
hang' = hang il
hangs :: Doc -> Doc -> Doc
hangs d1 d2 = hang' (d1 </> d2)
labels
:: Pretty a
=> Maybe a -> Doc -> Doc
labels Nothing doc = doc
labels (Just a) doc = ppr a <> colon <+> doc
block
:: Pretty a
=> [a] -> Doc
block = stack . map ppr
--------------------------------------------------------------------------------
-- conditional print
cond
:: Pretty a
=> (Doc -> Doc) -> Maybe a -> Doc
cond f = maybe empty (f . ppr)
condR
:: Pretty a
=> Doc -> Maybe a -> Doc
condR s = cond (<+/> s)
-- No space variant of condR
condR'
:: Pretty a
=> Doc -> Maybe a -> Doc
condR' s = cond (<> s)
condL
:: Pretty a
=> Doc -> Maybe a -> Doc
condL s = cond (s <+/>)
condL'
:: Pretty a
=> Doc -> Maybe a -> Doc
condL' s = cond (s <>)
label
:: Pretty a
=> Maybe a -> Doc
label = cond (<> colon)
ppr'
:: Pretty a
=> Maybe a -> Doc
ppr' d = ppr $ catL space d
when :: Bool -> Doc -> Doc
when b a =
if b
then a
else empty
catL :: (Pretty a, Functor f) => Doc -> f a -> f Doc
catL d e = catL' d <$> e
catL' :: (Pretty a) => Doc -> a -> Doc
catL' d e = d <> ppr e
appL :: (Pretty a, Functor f) => (Doc -> Doc) -> f a -> f Doc
appL f e = appL' f <$> e
appL' :: (Pretty a) => (Doc -> Doc) -> a -> Doc
appL' f e = f $ ppr e
--------------------------------------------------------------------------------
-- some common things
vppr
:: Pretty a
=> [a] -> Doc
vppr = foldr ((</>) . ppr) empty
postponed
:: Pretty a
=> Maybe Label -> Bool -> a -> Doc
postponed l b a = label l <+> when b (text "postponed") <+> ppr a
pprr :: (Pretty a) => a -> String
pprr = pretty 80 . ppr
pprrText :: (Pretty a) => a -> T.Text
pprrText d = toStrict $ prettyLazyText 80 (ppr d)
pprAnti
:: (Data a)
=> a -> String -> Doc
pprAnti s t = char '$' <> text (toQQString s) <> char ':' <> text t
intToBase :: Integer -> Integer -> String
intToBase b n = showIntAtBase b intToDigit n ""
pprlStack :: (Pretty a) => [a] -> Doc
pprlStack d = stack $ map ppr d
commasepBreak :: [Doc] -> Doc
commasepBreak = align . stack . punctuate comma
--------------------------------------------------------------------------------
| truls/language-vhdl-quote | src/Language/VHDL/Pretty.hs | mpl-2.0 | 36,209 | 0 | 17 | 9,665 | 14,977 | 7,191 | 7,786 | 927 | 2 |
{-# 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.IAM.CreateRole
-- 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)
--
-- Creates a new role for your AWS account. For more information about
-- roles, go to
-- <http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html Working with Roles>.
-- For information about limitations on role names and the number of roles
-- you can create, go to
-- <http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html Limitations on IAM Entities>
-- in the /Using IAM/ guide.
--
-- The policy in the following example grants permission to an EC2 instance
-- to assume the role.
--
-- /See:/ <http://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html AWS API Reference> for CreateRole.
module Network.AWS.IAM.CreateRole
(
-- * Creating a Request
createRole
, CreateRole
-- * Request Lenses
, crPath
, crRoleName
, crAssumeRolePolicyDocument
-- * Destructuring the Response
, createRoleResponse
, CreateRoleResponse
-- * Response Lenses
, crrsResponseStatus
, crrsRole
) where
import Network.AWS.IAM.Types
import Network.AWS.IAM.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'createRole' smart constructor.
data CreateRole = CreateRole'
{ _crPath :: !(Maybe Text)
, _crRoleName :: !Text
, _crAssumeRolePolicyDocument :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateRole' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'crPath'
--
-- * 'crRoleName'
--
-- * 'crAssumeRolePolicyDocument'
createRole
:: Text -- ^ 'crRoleName'
-> Text -- ^ 'crAssumeRolePolicyDocument'
-> CreateRole
createRole pRoleName_ pAssumeRolePolicyDocument_ =
CreateRole'
{ _crPath = Nothing
, _crRoleName = pRoleName_
, _crAssumeRolePolicyDocument = pAssumeRolePolicyDocument_
}
-- | The path to the role. For more information about paths, see
-- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers>
-- in the /Using IAM/ guide.
--
-- This parameter is optional. If it is not included, it defaults to a
-- slash (\/).
crPath :: Lens' CreateRole (Maybe Text)
crPath = lens _crPath (\ s a -> s{_crPath = a});
-- | The name of the role to create.
crRoleName :: Lens' CreateRole Text
crRoleName = lens _crRoleName (\ s a -> s{_crRoleName = a});
-- | The policy that grants an entity permission to assume the role.
crAssumeRolePolicyDocument :: Lens' CreateRole Text
crAssumeRolePolicyDocument = lens _crAssumeRolePolicyDocument (\ s a -> s{_crAssumeRolePolicyDocument = a});
instance AWSRequest CreateRole where
type Rs CreateRole = CreateRoleResponse
request = postQuery iAM
response
= receiveXMLWrapper "CreateRoleResult"
(\ s h x ->
CreateRoleResponse' <$>
(pure (fromEnum s)) <*> (x .@ "Role"))
instance ToHeaders CreateRole where
toHeaders = const mempty
instance ToPath CreateRole where
toPath = const "/"
instance ToQuery CreateRole where
toQuery CreateRole'{..}
= mconcat
["Action" =: ("CreateRole" :: ByteString),
"Version" =: ("2010-05-08" :: ByteString),
"Path" =: _crPath, "RoleName" =: _crRoleName,
"AssumeRolePolicyDocument" =:
_crAssumeRolePolicyDocument]
-- | Contains the response to a successful CreateRole request.
--
-- /See:/ 'createRoleResponse' smart constructor.
data CreateRoleResponse = CreateRoleResponse'
{ _crrsResponseStatus :: !Int
, _crrsRole :: !Role
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateRoleResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'crrsResponseStatus'
--
-- * 'crrsRole'
createRoleResponse
:: Int -- ^ 'crrsResponseStatus'
-> Role -- ^ 'crrsRole'
-> CreateRoleResponse
createRoleResponse pResponseStatus_ pRole_ =
CreateRoleResponse'
{ _crrsResponseStatus = pResponseStatus_
, _crrsRole = pRole_
}
-- | The response status code.
crrsResponseStatus :: Lens' CreateRoleResponse Int
crrsResponseStatus = lens _crrsResponseStatus (\ s a -> s{_crrsResponseStatus = a});
-- | Information about the role.
crrsRole :: Lens' CreateRoleResponse Role
crrsRole = lens _crrsRole (\ s a -> s{_crrsRole = a});
| fmapfmapfmap/amazonka | amazonka-iam/gen/Network/AWS/IAM/CreateRole.hs | mpl-2.0 | 5,238 | 0 | 14 | 1,125 | 709 | 430 | 279 | 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.AndroidPublisher.InAppProducts.Update
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates the details of an in-app product.
--
-- /See:/ <https://developers.google.com/android-publisher Google Play Developer API Reference> for @androidpublisher.inappproducts.update@.
module Network.Google.Resource.AndroidPublisher.InAppProducts.Update
(
-- * REST Resource
InAppProductsUpdateResource
-- * Creating a Request
, inAppProductsUpdate
, InAppProductsUpdate
-- * Request Lenses
, iapuAutoConvertMissingPrices
, iapuPackageName
, iapuPayload
, iapuSKU
) where
import Network.Google.AndroidPublisher.Types
import Network.Google.Prelude
-- | A resource alias for @androidpublisher.inappproducts.update@ method which the
-- 'InAppProductsUpdate' request conforms to.
type InAppProductsUpdateResource =
"androidpublisher" :>
"v2" :>
"applications" :>
Capture "packageName" Text :>
"inappproducts" :>
Capture "sku" Text :>
QueryParam "autoConvertMissingPrices" Bool :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] InAppProduct :>
Put '[JSON] InAppProduct
-- | Updates the details of an in-app product.
--
-- /See:/ 'inAppProductsUpdate' smart constructor.
data InAppProductsUpdate = InAppProductsUpdate'
{ _iapuAutoConvertMissingPrices :: !(Maybe Bool)
, _iapuPackageName :: !Text
, _iapuPayload :: !InAppProduct
, _iapuSKU :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'InAppProductsUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'iapuAutoConvertMissingPrices'
--
-- * 'iapuPackageName'
--
-- * 'iapuPayload'
--
-- * 'iapuSKU'
inAppProductsUpdate
:: Text -- ^ 'iapuPackageName'
-> InAppProduct -- ^ 'iapuPayload'
-> Text -- ^ 'iapuSKU'
-> InAppProductsUpdate
inAppProductsUpdate pIapuPackageName_ pIapuPayload_ pIapuSKU_ =
InAppProductsUpdate'
{ _iapuAutoConvertMissingPrices = Nothing
, _iapuPackageName = pIapuPackageName_
, _iapuPayload = pIapuPayload_
, _iapuSKU = pIapuSKU_
}
-- | If true the prices for all regions targeted by the parent app that
-- don\'t have a price specified for this in-app product will be auto
-- converted to the target currency based on the default price. Defaults to
-- false.
iapuAutoConvertMissingPrices :: Lens' InAppProductsUpdate (Maybe Bool)
iapuAutoConvertMissingPrices
= lens _iapuAutoConvertMissingPrices
(\ s a -> s{_iapuAutoConvertMissingPrices = a})
-- | Unique identifier for the Android app with the in-app product; for
-- example, \"com.spiffygame\".
iapuPackageName :: Lens' InAppProductsUpdate Text
iapuPackageName
= lens _iapuPackageName
(\ s a -> s{_iapuPackageName = a})
-- | Multipart request metadata.
iapuPayload :: Lens' InAppProductsUpdate InAppProduct
iapuPayload
= lens _iapuPayload (\ s a -> s{_iapuPayload = a})
-- | Unique identifier for the in-app product.
iapuSKU :: Lens' InAppProductsUpdate Text
iapuSKU = lens _iapuSKU (\ s a -> s{_iapuSKU = a})
instance GoogleRequest InAppProductsUpdate where
type Rs InAppProductsUpdate = InAppProduct
type Scopes InAppProductsUpdate =
'["https://www.googleapis.com/auth/androidpublisher"]
requestClient InAppProductsUpdate'{..}
= go _iapuPackageName _iapuSKU
_iapuAutoConvertMissingPrices
(Just AltJSON)
_iapuPayload
androidPublisherService
where go
= buildClient
(Proxy :: Proxy InAppProductsUpdateResource)
mempty
| rueshyna/gogol | gogol-android-publisher/gen/Network/Google/Resource/AndroidPublisher/InAppProducts/Update.hs | mpl-2.0 | 4,563 | 0 | 16 | 1,066 | 545 | 324 | 221 | 86 | 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.IAM.ListAttachedGroupPolicies
-- 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)
--
-- Lists all managed policies that are attached to the specified group.
--
-- A group can also have inline policies embedded with it. To list the
-- inline policies for a group, use the ListGroupPolicies API. For
-- information about policies, refer to
-- <http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html Managed Policies and Inline Policies>
-- in the /IAM User Guide/.
--
-- You can paginate the results using the 'MaxItems' and 'Marker'
-- parameters. You can use the 'PathPrefix' parameter to limit the list of
-- policies to only those matching the specified path prefix. If there are
-- no policies attached to the specified group (or none that match the
-- specified path prefix), the action returns an empty list.
--
-- /See:/ <http://docs.aws.amazon.com/IAM/latest/APIReference/API_ListAttachedGroupPolicies.html AWS API Reference> for ListAttachedGroupPolicies.
module Network.AWS.IAM.ListAttachedGroupPolicies
(
-- * Creating a Request
listAttachedGroupPolicies
, ListAttachedGroupPolicies
-- * Request Lenses
, lagpPathPrefix
, lagpMarker
, lagpMaxItems
, lagpGroupName
-- * Destructuring the Response
, listAttachedGroupPoliciesResponse
, ListAttachedGroupPoliciesResponse
-- * Response Lenses
, lagprsAttachedPolicies
, lagprsMarker
, lagprsIsTruncated
, lagprsResponseStatus
) where
import Network.AWS.IAM.Types
import Network.AWS.IAM.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'listAttachedGroupPolicies' smart constructor.
data ListAttachedGroupPolicies = ListAttachedGroupPolicies'
{ _lagpPathPrefix :: !(Maybe Text)
, _lagpMarker :: !(Maybe Text)
, _lagpMaxItems :: !(Maybe Nat)
, _lagpGroupName :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListAttachedGroupPolicies' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lagpPathPrefix'
--
-- * 'lagpMarker'
--
-- * 'lagpMaxItems'
--
-- * 'lagpGroupName'
listAttachedGroupPolicies
:: Text -- ^ 'lagpGroupName'
-> ListAttachedGroupPolicies
listAttachedGroupPolicies pGroupName_ =
ListAttachedGroupPolicies'
{ _lagpPathPrefix = Nothing
, _lagpMarker = Nothing
, _lagpMaxItems = Nothing
, _lagpGroupName = pGroupName_
}
-- | The path prefix for filtering the results. This parameter is optional.
-- If it is not included, it defaults to a slash (\/), listing all
-- policies.
lagpPathPrefix :: Lens' ListAttachedGroupPolicies (Maybe Text)
lagpPathPrefix = lens _lagpPathPrefix (\ s a -> s{_lagpPathPrefix = a});
-- | Use this parameter only when paginating results and only after you
-- receive a response indicating that the results are truncated. Set it to
-- the value of the 'Marker' element in the response you received to inform
-- the next call about where to start.
lagpMarker :: Lens' ListAttachedGroupPolicies (Maybe Text)
lagpMarker = lens _lagpMarker (\ s a -> s{_lagpMarker = a});
-- | Use this only when paginating results to indicate the maximum number of
-- items you want in the response. If there are additional items beyond the
-- maximum you specify, the 'IsTruncated' response element is 'true'.
--
-- This parameter is optional. If you do not include it, it defaults to
-- 100. Note that IAM might return fewer results, even when there are more
-- results available. If this is the case, the 'IsTruncated' response
-- element returns 'true' and 'Marker' contains a value to include in the
-- subsequent call that tells the service where to continue from.
lagpMaxItems :: Lens' ListAttachedGroupPolicies (Maybe Natural)
lagpMaxItems = lens _lagpMaxItems (\ s a -> s{_lagpMaxItems = a}) . mapping _Nat;
-- | The name (friendly name, not ARN) of the group to list attached policies
-- for.
lagpGroupName :: Lens' ListAttachedGroupPolicies Text
lagpGroupName = lens _lagpGroupName (\ s a -> s{_lagpGroupName = a});
instance AWSRequest ListAttachedGroupPolicies where
type Rs ListAttachedGroupPolicies =
ListAttachedGroupPoliciesResponse
request = postQuery iAM
response
= receiveXMLWrapper "ListAttachedGroupPoliciesResult"
(\ s h x ->
ListAttachedGroupPoliciesResponse' <$>
(x .@? "AttachedPolicies" .!@ mempty >>=
may (parseXMLList "member"))
<*> (x .@? "Marker")
<*> (x .@? "IsTruncated")
<*> (pure (fromEnum s)))
instance ToHeaders ListAttachedGroupPolicies where
toHeaders = const mempty
instance ToPath ListAttachedGroupPolicies where
toPath = const "/"
instance ToQuery ListAttachedGroupPolicies where
toQuery ListAttachedGroupPolicies'{..}
= mconcat
["Action" =:
("ListAttachedGroupPolicies" :: ByteString),
"Version" =: ("2010-05-08" :: ByteString),
"PathPrefix" =: _lagpPathPrefix,
"Marker" =: _lagpMarker, "MaxItems" =: _lagpMaxItems,
"GroupName" =: _lagpGroupName]
-- | Contains the response to a successful ListAttachedGroupPolicies request.
--
-- /See:/ 'listAttachedGroupPoliciesResponse' smart constructor.
data ListAttachedGroupPoliciesResponse = ListAttachedGroupPoliciesResponse'
{ _lagprsAttachedPolicies :: !(Maybe [AttachedPolicy])
, _lagprsMarker :: !(Maybe Text)
, _lagprsIsTruncated :: !(Maybe Bool)
, _lagprsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListAttachedGroupPoliciesResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lagprsAttachedPolicies'
--
-- * 'lagprsMarker'
--
-- * 'lagprsIsTruncated'
--
-- * 'lagprsResponseStatus'
listAttachedGroupPoliciesResponse
:: Int -- ^ 'lagprsResponseStatus'
-> ListAttachedGroupPoliciesResponse
listAttachedGroupPoliciesResponse pResponseStatus_ =
ListAttachedGroupPoliciesResponse'
{ _lagprsAttachedPolicies = Nothing
, _lagprsMarker = Nothing
, _lagprsIsTruncated = Nothing
, _lagprsResponseStatus = pResponseStatus_
}
-- | A list of the attached policies.
lagprsAttachedPolicies :: Lens' ListAttachedGroupPoliciesResponse [AttachedPolicy]
lagprsAttachedPolicies = lens _lagprsAttachedPolicies (\ s a -> s{_lagprsAttachedPolicies = a}) . _Default . _Coerce;
-- | When 'IsTruncated' is 'true', this element is present and contains the
-- value to use for the 'Marker' parameter in a subsequent pagination
-- request.
lagprsMarker :: Lens' ListAttachedGroupPoliciesResponse (Maybe Text)
lagprsMarker = lens _lagprsMarker (\ s a -> s{_lagprsMarker = a});
-- | A flag that indicates whether there are more items to return. If your
-- results were truncated, you can make a subsequent pagination request
-- using the 'Marker' request parameter to retrieve more items. Note that
-- IAM might return fewer than the 'MaxItems' number of results even when
-- there are more results available. We recommend that you check
-- 'IsTruncated' after every call to ensure that you receive all of your
-- results.
lagprsIsTruncated :: Lens' ListAttachedGroupPoliciesResponse (Maybe Bool)
lagprsIsTruncated = lens _lagprsIsTruncated (\ s a -> s{_lagprsIsTruncated = a});
-- | The response status code.
lagprsResponseStatus :: Lens' ListAttachedGroupPoliciesResponse Int
lagprsResponseStatus = lens _lagprsResponseStatus (\ s a -> s{_lagprsResponseStatus = a});
| olorin/amazonka | amazonka-iam/gen/Network/AWS/IAM/ListAttachedGroupPolicies.hs | mpl-2.0 | 8,417 | 0 | 17 | 1,643 | 1,010 | 609 | 401 | 115 | 1 |
-- Copyright 2012-2014 Samplecount S.L.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators #-}
{-|
Description: Types and functions for working with target tool chains
-}
module Development.Shake.Language.C.ToolChain (
Linkage(..)
-- ** Working with toolchains
, ToolChain
, ToolChainVariant(..)
, toolDirectory -- | Directory prefix for tools in a `ToolChain`, e.g. @\/usr\/local\/linux-armv5-eabi\/bin@.
, toolPrefix -- | Prefix string for tools in a `ToolChain`, e.g. @"linux-armv5-eabi-"@.
, variant -- | Toolchain variant.
, compilerCommand -- | Compiler command, usually used in the `compiler` action.
, Compiler
, compiler -- | Compiler action for this `ToolChain`.
, archiverCommand -- | Archiver command, usually used in the `archiver` action.
, Archiver
, archiver -- | Archiver action for this `ToolChain`.
, linkerCommand -- | Linker command, usually used in the `linker` action.
, Linker
, LinkResult(..)
, linker -- | Linker action for this `ToolChain`.
, defaultBuildFlags -- | Action returning the default `BuildFlags` for this `ToolChain`.
-- ** Interfacing with other build systems
, applyEnv
, toEnv
-- ** Utilities for toolchain writers
, defaultToolChain
, defaultCompiler
, defaultArchiver
, defaultLinker
, toolFromString
, tool
) where
import Control.Applicative
import Data.Char (toLower)
import Data.List (isInfixOf, isSuffixOf)
import Data.Monoid (mempty)
import Development.Shake
import Development.Shake.FilePath
import Development.Shake.Util (needMakefileDependencies)
import Development.Shake.Language.C.Label
import Development.Shake.Language.C.BuildFlags
import Development.Shake.Language.C.Language (languageOf)
import Development.Shake.Language.C.Util
-- | Linkage type, static or shared.
data Linkage = Static | Shared deriving (Enum, Eq, Show)
-- | Link result type
data LinkResult =
Executable -- ^ Executable
| SharedLibrary -- ^ Shared (dynamically linked) library
| LoadableLibrary -- ^ Dynamically loadable library
deriving (Enum, Eq, Show)
-- | Toolchain variant.
data ToolChainVariant =
Generic -- ^ Unspecified toolchain
| GCC -- ^ GNU Compiler Collection (gcc) toolchain
| LLVM -- ^ Low-Level Virtual Machine (LLVM) toolchain
deriving (Eq, Show)
-- | `Action` type for producing an object file from a source file.
type Compiler =
ToolChain -- ^ Toolchain
-> BuildFlags -- ^ Compiler flags
-> FilePath -- ^ Input source file
-> FilePath -- ^ Output object file
-> Action ()
-- | `Action` type for linking object files into an executable or a library.
type Linker =
ToolChain -- ^ Toolchain
-> BuildFlags -- ^ Linker flags
-> [FilePath] -- ^ Input object files
-> FilePath -- ^ Output link product
-> Action ()
-- | `Action` type for archiving object files into a static library.
type Archiver =
ToolChain -- ^ Toolchain
-> BuildFlags -- ^ Archiver flags
-> [FilePath] -- ^ Input object files
-> FilePath -- ^ Output object archive (static library)
-> Action ()
data ToolChain = ToolChain {
_variant :: ToolChainVariant
, _toolDirectory :: Maybe FilePath
, _toolPrefix :: String
, _compilerCommand :: FilePath
, _compiler :: Compiler
, _archiverCommand :: FilePath
, _archiver :: Archiver
, _linkerCommand :: FilePath
, _linker :: LinkResult -> Linker
, _defaultBuildFlags :: Action (BuildFlags -> BuildFlags)
}
mkLabel ''ToolChain
-- | Default compiler action.
defaultCompiler :: Compiler
defaultCompiler toolChain buildFlags input output = do
need $ [input]
let depFile = output <.> "d"
command_ [] (tool toolChain compilerCommand)
$ concatMapFlag "-isystem" (get systemIncludes buildFlags)
++ mapFlag "-I" (get userIncludes buildFlags)
++ defineFlags buildFlags
++ get preprocessorFlags buildFlags
++ compilerFlagsFor (languageOf input) buildFlags
++ ["-MD", "-MF", depFile]
++ ["-c", "-o", output, input]
needMakefileDependencies depFile
-- | Default archiver action.
defaultArchiver :: Archiver
defaultArchiver toolChain buildFlags inputs output = do
need inputs
command_ [] (tool toolChain archiverCommand)
$ get archiverFlags buildFlags
++ [output]
++ inputs
-- | Default linker action.
defaultLinker :: Linker
defaultLinker toolChain buildFlags inputs output = do
let localLibs = get localLibraries buildFlags
buildFlags' = append libraryPath (map takeDirectory localLibs)
-- Local libraries must be passed to the linker before system libraries they depend on
. prepend libraries (map (strip.dropExtension.takeFileName) localLibs)
$ buildFlags
need $ inputs ++ localLibs
command_ [] (tool toolChain linkerCommand)
$ inputs
++ get linkerFlags buildFlags'
++ concatMapFlag "-L" (get libraryPath buildFlags')
++ concatMapFlag "-l" (get libraries buildFlags')
++ ["-o", output]
where
strip ('l':'i':'b':rest) = rest
strip x = x
-- | Default toolchain.
--
-- Probably not useful without modification.
defaultToolChain :: ToolChain
defaultToolChain =
ToolChain {
_variant = GCC
, _toolDirectory = Nothing
, _toolPrefix = ""
, _compilerCommand = "gcc"
, _compiler = defaultCompiler
, _archiverCommand = "ar"
, _archiver = defaultArchiver
, _linkerCommand = "gcc"
, _linker = \linkResult linkerCmd ->
case linkResult of
Executable -> defaultLinker linkerCmd
_ -> defaultLinker linkerCmd . append linkerFlags ["-shared"]
, _defaultBuildFlags = return id
}
-- | Given a tool chain command name, construct the command's full path, taking into account the toolchain's `toolPrefix`.
toolFromString ::
ToolChain -- ^ Toolchain
-> String -- ^ Command name
-> FilePath -- ^ Full command path
toolFromString toolChain name =
let c = _toolPrefix toolChain ++ name
in maybe c (</> c) (_toolDirectory toolChain)
-- | Construct the full path of a predefined tool given a `ToolChain` accessor.
tool ::
ToolChain -- ^ Toolchain
-> (ToolChain :-> String) -- ^ Toolchain accessor
-> FilePath -- ^ Full command path
tool toolChain getter = toolFromString toolChain (get getter toolChain)
-- | Apply the current environment and return a modified toolchain.
--
-- This function is experimental and subject to change!
--
-- Currently recognised environment variables are
--
-- [@CC@] Path to @C@ compiler.
--
-- [@LD@] Path to linker.
--
-- [@SHAKE_TOOLCHAIN_VARIANT@] One of the values of 'ToolChainVariant' (case insensitive). If this variable is not present, an attempt is made to determine the toolchain variant from the @C@ compiler command.
applyEnv :: ToolChain -> Action ToolChain
applyEnv toolChain = do
cc <- getEnv "CC"
ld <- getEnv "LD"
vendor <- getEnv "SHAKE_TOOLCHAIN_VARIANT"
return $ maybe id (set compilerCommand) cc
$ maybe id (set linkerCommand) ld
. maybe id (set variant) ((vendor >>= parseVendor) <|> (cc >>= vendorFromCommand))
$ toolChain
where
parseVendor s =
case map toLower s of
"gcc" -> Just GCC
"llvm" -> Just LLVM
"clang" -> Just LLVM
_ -> Nothing
vendorFromCommand path =
let x = takeFileName path
in if "gcc" `isInfixOf` x || "g++" `isInfixOf` x
then Just GCC
else if "clang" `isInfixOf` x
then Just LLVM
else Just Generic
-- | Export a 'ToolChain' definition to a list of environment variable mappings, suitable e.g. for calling third-party configure scripts in cross-compilation mode.
--
-- Needs some fleshing out; currently only works for "standard" binutil toolchains.
toEnv :: ToolChain -> Action [(String,String)]
toEnv tc = do
flags <- (\f -> f mempty) <$> get defaultBuildFlags tc
let cflags = concatMapFlag "-I" (map escapeSpaces (get systemIncludes flags))
++ concatMapFlag "-I" (map escapeSpaces (get userIncludes flags))
++ defineFlags flags
++ get preprocessorFlags flags
++ compilerFlagsFor (Just C) flags
cxxflags = cflags ++ compilerFlagsFor (Just Cpp) flags
ldflags = get linkerFlags flags
++ concatMapFlag "-L" (get libraryPath flags)
++ concatMapFlag "-l" (get libraries flags)
c2cxx path = let x = takeFileName path
in if "gcc" `isSuffixOf` x
then (++"g++") . reverse . drop 3 . reverse $ path
else if "clang" `isSuffixOf` x
then path ++ "++"
else path
let cc = tool tc compilerCommand
cpp = toolFromString tc "cpp"
cppExists <- doesFileExist cpp
let cpp' = if cppExists then cpp else cc ++ " -E"
return $ [
("CPP", cpp')
, ("AR", tool tc archiverCommand)
, ("NM", toolFromString tc "nm")
, ("CC", tool tc compilerCommand)
-- FIXME: Configure toolchain with compiler command per language?
, ("CXX", c2cxx $ tool tc compilerCommand)
, ("LD", toolFromString tc "ld")
, ("RANLIB", toolFromString tc "ranlib")
, ("CFLAGS", unwords cflags)
, ("CPPFLAGS", unwords cflags)
, ("CXXFLAGS", unwords cxxflags)
, ("LDFLAGS", unwords ldflags)
]
| samplecount/shake-language-c | src/Development/Shake/Language/C/ToolChain.hs | apache-2.0 | 10,167 | 0 | 18 | 2,534 | 1,914 | 1,062 | 852 | 199 | 6 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QAbstractItemView_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:20
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QAbstractItemView_h (
QisIndexHidden_h(..)
) where
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 (QAbstractItemView ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractItemView_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QAbstractItemView_unSetUserMethod" qtc_QAbstractItemView_unSetUserMethod :: Ptr (TQAbstractItemView a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QAbstractItemViewSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractItemView_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QAbstractItemView ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractItemView_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QAbstractItemViewSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractItemView_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QAbstractItemView ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractItemView_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QAbstractItemViewSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractItemView_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QAbstractItemView ()) (QAbstractItemView x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QAbstractItemView setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QAbstractItemView_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QAbstractItemView_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQAbstractItemView 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_QAbstractItemView_setUserMethod" qtc_QAbstractItemView_setUserMethod :: Ptr (TQAbstractItemView a) -> CInt -> Ptr (Ptr (TQAbstractItemView x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QAbstractItemView :: (Ptr (TQAbstractItemView x0) -> IO ()) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QAbstractItemView_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QAbstractItemViewSc a) (QAbstractItemView x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QAbstractItemView setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QAbstractItemView_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QAbstractItemView_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQAbstractItemView 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 (QAbstractItemView ()) (QAbstractItemView x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QAbstractItemView setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QAbstractItemView_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QAbstractItemView_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQAbstractItemView 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_QAbstractItemView_setUserMethodVariant" qtc_QAbstractItemView_setUserMethodVariant :: Ptr (TQAbstractItemView a) -> CInt -> Ptr (Ptr (TQAbstractItemView x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QAbstractItemView :: (Ptr (TQAbstractItemView x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QAbstractItemView_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QAbstractItemViewSc a) (QAbstractItemView x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QAbstractItemView setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QAbstractItemView_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QAbstractItemView_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQAbstractItemView 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 (QAbstractItemView ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QAbstractItemView_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QAbstractItemView_unSetHandler" qtc_QAbstractItemView_unSetHandler :: Ptr (TQAbstractItemView a) -> CWString -> IO (CBool)
instance QunSetHandler (QAbstractItemViewSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QAbstractItemView_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QAbstractItemView ()) (QAbstractItemView x0 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> IO ()
setHandlerWrapper x0
= do x0obj <- qAbstractItemViewFromPtr 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_QAbstractItemView_setHandler1" qtc_QAbstractItemView_setHandler1 :: Ptr (TQAbstractItemView a) -> CWString -> Ptr (Ptr (TQAbstractItemView x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView1 :: (Ptr (TQAbstractItemView x0) -> IO ()) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemViewSc a) (QAbstractItemView x0 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> IO ()
setHandlerWrapper x0
= do x0obj <- qAbstractItemViewFromPtr 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 (QAbstractItemView ()) (()) where
doItemsLayout_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_doItemsLayout cobj_x0
foreign import ccall "qtc_QAbstractItemView_doItemsLayout" qtc_QAbstractItemView_doItemsLayout :: Ptr (TQAbstractItemView a) -> IO ()
instance QdoItemsLayout_h (QAbstractItemViewSc a) (()) where
doItemsLayout_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_doItemsLayout cobj_x0
instance QsetHandler (QAbstractItemView ()) (QAbstractItemView x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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_QAbstractItemView_setHandler2" qtc_QAbstractItemView_setHandler2 :: Ptr (TQAbstractItemView a) -> CWString -> Ptr (Ptr (TQAbstractItemView x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView2 :: (Ptr (TQAbstractItemView x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> Ptr (TQEvent t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemViewSc a) (QAbstractItemView x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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 QdragEnterEvent_h (QAbstractItemView ()) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_dragEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_dragEnterEvent" qtc_QAbstractItemView_dragEnterEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent_h (QAbstractItemViewSc a) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_dragEnterEvent cobj_x0 cobj_x1
instance QdragLeaveEvent_h (QAbstractItemView ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_dragLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_dragLeaveEvent" qtc_QAbstractItemView_dragLeaveEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent_h (QAbstractItemViewSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_dragLeaveEvent cobj_x0 cobj_x1
instance QdragMoveEvent_h (QAbstractItemView ()) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_dragMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_dragMoveEvent" qtc_QAbstractItemView_dragMoveEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent_h (QAbstractItemViewSc a) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_dragMoveEvent cobj_x0 cobj_x1
instance QdropEvent_h (QAbstractItemView ()) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_dropEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_dropEvent" qtc_QAbstractItemView_dropEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent_h (QAbstractItemViewSc a) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_dropEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractItemView ()) (QAbstractItemView x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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_QAbstractItemView_setHandler3" qtc_QAbstractItemView_setHandler3 :: Ptr (TQAbstractItemView a) -> CWString -> Ptr (Ptr (TQAbstractItemView x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView3 :: (Ptr (TQAbstractItemView x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemViewSc a) (QAbstractItemView x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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 (QAbstractItemView ()) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_event cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_event" qtc_QAbstractItemView_event :: Ptr (TQAbstractItemView a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent_h (QAbstractItemViewSc a) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_event cobj_x0 cobj_x1
instance QfocusInEvent_h (QAbstractItemView ()) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_focusInEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_focusInEvent" qtc_QAbstractItemView_focusInEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent_h (QAbstractItemViewSc a) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_focusInEvent cobj_x0 cobj_x1
instance QfocusOutEvent_h (QAbstractItemView ()) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_focusOutEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_focusOutEvent" qtc_QAbstractItemView_focusOutEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent_h (QAbstractItemViewSc a) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_focusOutEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractItemView ()) (QAbstractItemView x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qAbstractItemViewFromPtr 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_QAbstractItemView_setHandler4" qtc_QAbstractItemView_setHandler4 :: Ptr (TQAbstractItemView a) -> CWString -> Ptr (Ptr (TQAbstractItemView x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView4 :: (Ptr (TQAbstractItemView x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemViewSc a) (QAbstractItemView x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qAbstractItemViewFromPtr 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 (QAbstractItemView ()) (()) where
horizontalOffset_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_horizontalOffset cobj_x0
foreign import ccall "qtc_QAbstractItemView_horizontalOffset" qtc_QAbstractItemView_horizontalOffset :: Ptr (TQAbstractItemView a) -> IO CInt
instance QhorizontalOffset_h (QAbstractItemViewSc a) (()) where
horizontalOffset_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_horizontalOffset cobj_x0
instance QsetHandler (QAbstractItemView ()) (QAbstractItemView x0 -> QPoint t1 -> IO (QModelIndex t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex t0))
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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_QAbstractItemView_setHandler5" qtc_QAbstractItemView_setHandler5 :: Ptr (TQAbstractItemView a) -> CWString -> Ptr (Ptr (TQAbstractItemView x0) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView5 :: (Ptr (TQAbstractItemView x0) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex t0))) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex t0))))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemViewSc a) (QAbstractItemView x0 -> QPoint t1 -> IO (QModelIndex t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex t0))
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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 (QAbstractItemView ()) ((Point)) where
indexAt_h x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QAbstractItemView_indexAt_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QAbstractItemView_indexAt_qth" qtc_QAbstractItemView_indexAt_qth :: Ptr (TQAbstractItemView a) -> CInt -> CInt -> IO (Ptr (TQModelIndex ()))
instance QindexAt_h (QAbstractItemViewSc a) ((Point)) where
indexAt_h x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QAbstractItemView_indexAt_qth cobj_x0 cpoint_x1_x cpoint_x1_y
instance QqindexAt_h (QAbstractItemView ()) ((QPoint t1)) where
qindexAt_h x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_indexAt cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_indexAt" qtc_QAbstractItemView_indexAt :: Ptr (TQAbstractItemView a) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex ()))
instance QqindexAt_h (QAbstractItemViewSc a) ((QPoint t1)) where
qindexAt_h x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_indexAt cobj_x0 cobj_x1
instance QsetHandler (QAbstractItemView ()) (QAbstractItemView x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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_QAbstractItemView_setHandler6" qtc_QAbstractItemView_setHandler6 :: Ptr (TQAbstractItemView a) -> CWString -> Ptr (Ptr (TQAbstractItemView x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView6 :: (Ptr (TQAbstractItemView x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> CLong -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemViewSc a) (QAbstractItemView x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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 (QAbstractItemView ()) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QAbstractItemView_inputMethodQuery" qtc_QAbstractItemView_inputMethodQuery :: Ptr (TQAbstractItemView a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery_h (QAbstractItemViewSc a) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
instance QsetHandler (QAbstractItemView ()) (QAbstractItemView x0 -> QModelIndex t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQModelIndex t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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_QAbstractItemView_setHandler7" qtc_QAbstractItemView_setHandler7 :: Ptr (TQAbstractItemView a) -> CWString -> Ptr (Ptr (TQAbstractItemView x0) -> Ptr (TQModelIndex t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView7 :: (Ptr (TQAbstractItemView x0) -> Ptr (TQModelIndex t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> Ptr (TQModelIndex t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemViewSc a) (QAbstractItemView x0 -> QModelIndex t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQModelIndex t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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 ()
class QisIndexHidden_h x0 x1 where
isIndexHidden_h :: x0 -> x1 -> IO (Bool)
instance QisIndexHidden_h (QAbstractItemView ()) ((QModelIndex t1)) where
isIndexHidden_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_isIndexHidden cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_isIndexHidden" qtc_QAbstractItemView_isIndexHidden :: Ptr (TQAbstractItemView a) -> Ptr (TQModelIndex t1) -> IO CBool
instance QisIndexHidden_h (QAbstractItemViewSc a) ((QModelIndex t1)) where
isIndexHidden_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_isIndexHidden cobj_x0 cobj_x1
instance QkeyPressEvent_h (QAbstractItemView ()) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_keyPressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_keyPressEvent" qtc_QAbstractItemView_keyPressEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent_h (QAbstractItemViewSc a) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_keyPressEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractItemView ()) (QAbstractItemView x0 -> String -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQString ()) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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_QAbstractItemView_setHandler8" qtc_QAbstractItemView_setHandler8 :: Ptr (TQAbstractItemView a) -> CWString -> Ptr (Ptr (TQAbstractItemView x0) -> Ptr (TQString ()) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView8 :: (Ptr (TQAbstractItemView x0) -> Ptr (TQString ()) -> IO ()) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> Ptr (TQString ()) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemViewSc a) (QAbstractItemView x0 -> String -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQString ()) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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 (QAbstractItemView ()) ((String)) where
keyboardSearch_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QAbstractItemView_keyboardSearch cobj_x0 cstr_x1
foreign import ccall "qtc_QAbstractItemView_keyboardSearch" qtc_QAbstractItemView_keyboardSearch :: Ptr (TQAbstractItemView a) -> CWString -> IO ()
instance QkeyboardSearch_h (QAbstractItemViewSc a) ((String)) where
keyboardSearch_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QAbstractItemView_keyboardSearch cobj_x0 cstr_x1
instance QmouseDoubleClickEvent_h (QAbstractItemView ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_mouseDoubleClickEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_mouseDoubleClickEvent" qtc_QAbstractItemView_mouseDoubleClickEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent_h (QAbstractItemViewSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_mouseDoubleClickEvent cobj_x0 cobj_x1
instance QmouseMoveEvent_h (QAbstractItemView ()) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_mouseMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_mouseMoveEvent" qtc_QAbstractItemView_mouseMoveEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent_h (QAbstractItemViewSc a) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_mouseMoveEvent cobj_x0 cobj_x1
instance QmousePressEvent_h (QAbstractItemView ()) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_mousePressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_mousePressEvent" qtc_QAbstractItemView_mousePressEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent_h (QAbstractItemViewSc a) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_mousePressEvent cobj_x0 cobj_x1
instance QmouseReleaseEvent_h (QAbstractItemView ()) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_mouseReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_mouseReleaseEvent" qtc_QAbstractItemView_mouseReleaseEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent_h (QAbstractItemViewSc a) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_mouseReleaseEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractItemView ()) (QAbstractItemView x0 -> CursorAction -> KeyboardModifiers -> IO (QModelIndex t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> CLong -> CLong -> IO (Ptr (TQModelIndex t0))
setHandlerWrapper x0 x1 x2
= do x0obj <- qAbstractItemViewFromPtr 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_QAbstractItemView_setHandler9" qtc_QAbstractItemView_setHandler9 :: Ptr (TQAbstractItemView a) -> CWString -> Ptr (Ptr (TQAbstractItemView x0) -> CLong -> CLong -> IO (Ptr (TQModelIndex t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView9 :: (Ptr (TQAbstractItemView x0) -> CLong -> CLong -> IO (Ptr (TQModelIndex t0))) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> CLong -> CLong -> IO (Ptr (TQModelIndex t0))))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemViewSc a) (QAbstractItemView x0 -> CursorAction -> KeyboardModifiers -> IO (QModelIndex t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> CLong -> CLong -> IO (Ptr (TQModelIndex t0))
setHandlerWrapper x0 x1 x2
= do x0obj <- qAbstractItemViewFromPtr 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 (QAbstractItemView ()) ((CursorAction, KeyboardModifiers)) where
moveCursor_h x0 (x1, x2)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_moveCursor cobj_x0 (toCLong $ qEnum_toInt x1) (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QAbstractItemView_moveCursor" qtc_QAbstractItemView_moveCursor :: Ptr (TQAbstractItemView a) -> CLong -> CLong -> IO (Ptr (TQModelIndex ()))
instance QmoveCursor_h (QAbstractItemViewSc a) ((CursorAction, KeyboardModifiers)) where
moveCursor_h x0 (x1, x2)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_moveCursor cobj_x0 (toCLong $ qEnum_toInt x1) (toCLong $ qFlags_toInt x2)
instance Qreset_h (QAbstractItemView ()) (()) (IO ()) where
reset_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_reset cobj_x0
foreign import ccall "qtc_QAbstractItemView_reset" qtc_QAbstractItemView_reset :: Ptr (TQAbstractItemView a) -> IO ()
instance Qreset_h (QAbstractItemViewSc a) (()) (IO ()) where
reset_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_reset cobj_x0
instance QresizeEvent_h (QAbstractItemView ()) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_resizeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_resizeEvent" qtc_QAbstractItemView_resizeEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent_h (QAbstractItemViewSc a) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_resizeEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractItemView ()) (QAbstractItemView x0 -> QModelIndex t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQModelIndex t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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_QAbstractItemView_setHandler10" qtc_QAbstractItemView_setHandler10 :: Ptr (TQAbstractItemView a) -> CWString -> Ptr (Ptr (TQAbstractItemView x0) -> Ptr (TQModelIndex t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView10 :: (Ptr (TQAbstractItemView x0) -> Ptr (TQModelIndex t1) -> IO ()) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> Ptr (TQModelIndex t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemViewSc a) (QAbstractItemView x0 -> QModelIndex t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQModelIndex t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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 (QAbstractItemView ()) (QAbstractItemView x0 -> QModelIndex t1 -> ScrollHint -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQModelIndex t1) -> CLong -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qAbstractItemViewFromPtr 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_QAbstractItemView_setHandler11" qtc_QAbstractItemView_setHandler11 :: Ptr (TQAbstractItemView a) -> CWString -> Ptr (Ptr (TQAbstractItemView x0) -> Ptr (TQModelIndex t1) -> CLong -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView11 :: (Ptr (TQAbstractItemView x0) -> Ptr (TQModelIndex t1) -> CLong -> IO ()) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> Ptr (TQModelIndex t1) -> CLong -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView11_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemViewSc a) (QAbstractItemView x0 -> QModelIndex t1 -> ScrollHint -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQModelIndex t1) -> CLong -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qAbstractItemViewFromPtr 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 (QAbstractItemView ()) ((QModelIndex t1)) where
scrollTo_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_scrollTo cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_scrollTo" qtc_QAbstractItemView_scrollTo :: Ptr (TQAbstractItemView a) -> Ptr (TQModelIndex t1) -> IO ()
instance QscrollTo_h (QAbstractItemViewSc a) ((QModelIndex t1)) where
scrollTo_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_scrollTo cobj_x0 cobj_x1
instance QscrollTo_h (QAbstractItemView ()) ((QModelIndex t1, ScrollHint)) where
scrollTo_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_scrollTo1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QAbstractItemView_scrollTo1" qtc_QAbstractItemView_scrollTo1 :: Ptr (TQAbstractItemView a) -> Ptr (TQModelIndex t1) -> CLong -> IO ()
instance QscrollTo_h (QAbstractItemViewSc a) ((QModelIndex t1, ScrollHint)) where
scrollTo_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_scrollTo1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QselectAll_h (QAbstractItemView ()) (()) where
selectAll_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_selectAll cobj_x0
foreign import ccall "qtc_QAbstractItemView_selectAll" qtc_QAbstractItemView_selectAll :: Ptr (TQAbstractItemView a) -> IO ()
instance QselectAll_h (QAbstractItemViewSc a) (()) where
selectAll_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_selectAll cobj_x0
instance QsetHandler (QAbstractItemView ()) (QAbstractItemView x0 -> QObject t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQObject t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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_QAbstractItemView_setHandler12" qtc_QAbstractItemView_setHandler12 :: Ptr (TQAbstractItemView a) -> CWString -> Ptr (Ptr (TQAbstractItemView x0) -> Ptr (TQObject t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView12 :: (Ptr (TQAbstractItemView x0) -> Ptr (TQObject t1) -> IO ()) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> Ptr (TQObject t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView12_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemViewSc a) (QAbstractItemView x0 -> QObject t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQObject t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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 (QAbstractItemView ()) ((QAbstractItemModel t1)) where
setModel_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_setModel cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_setModel" qtc_QAbstractItemView_setModel :: Ptr (TQAbstractItemView a) -> Ptr (TQAbstractItemModel t1) -> IO ()
instance QsetModel_h (QAbstractItemViewSc a) ((QAbstractItemModel t1)) where
setModel_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_setModel cobj_x0 cobj_x1
instance QsetRootIndex_h (QAbstractItemView ()) ((QModelIndex t1)) where
setRootIndex_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_setRootIndex cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_setRootIndex" qtc_QAbstractItemView_setRootIndex :: Ptr (TQAbstractItemView a) -> Ptr (TQModelIndex t1) -> IO ()
instance QsetRootIndex_h (QAbstractItemViewSc a) ((QModelIndex t1)) where
setRootIndex_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_setRootIndex cobj_x0 cobj_x1
instance QsetHandler (QAbstractItemView ()) (QAbstractItemView x0 -> QRect t1 -> SelectionFlags -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQRect t1) -> CLong -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qAbstractItemViewFromPtr 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_QAbstractItemView_setHandler13" qtc_QAbstractItemView_setHandler13 :: Ptr (TQAbstractItemView a) -> CWString -> Ptr (Ptr (TQAbstractItemView x0) -> Ptr (TQRect t1) -> CLong -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView13 :: (Ptr (TQAbstractItemView x0) -> Ptr (TQRect t1) -> CLong -> IO ()) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> Ptr (TQRect t1) -> CLong -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView13_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemViewSc a) (QAbstractItemView x0 -> QRect t1 -> SelectionFlags -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQRect t1) -> CLong -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qAbstractItemViewFromPtr 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 (QAbstractItemView ()) ((QRect t1, SelectionFlags)) where
qsetSelection_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_setSelection cobj_x0 cobj_x1 (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QAbstractItemView_setSelection" qtc_QAbstractItemView_setSelection :: Ptr (TQAbstractItemView a) -> Ptr (TQRect t1) -> CLong -> IO ()
instance QqsetSelection_h (QAbstractItemViewSc a) ((QRect t1, SelectionFlags)) where
qsetSelection_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_setSelection cobj_x0 cobj_x1 (toCLong $ qFlags_toInt x2)
instance QsetSelection_h (QAbstractItemView ()) ((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_QAbstractItemView_setSelection_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QAbstractItemView_setSelection_qth" qtc_QAbstractItemView_setSelection_qth :: Ptr (TQAbstractItemView a) -> CInt -> CInt -> CInt -> CInt -> CLong -> IO ()
instance QsetSelection_h (QAbstractItemViewSc 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_QAbstractItemView_setSelection_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h (toCLong $ qFlags_toInt x2)
instance QsetSelectionModel_h (QAbstractItemView ()) ((QItemSelectionModel t1)) where
setSelectionModel_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_setSelectionModel cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_setSelectionModel" qtc_QAbstractItemView_setSelectionModel :: Ptr (TQAbstractItemView a) -> Ptr (TQItemSelectionModel t1) -> IO ()
instance QsetSelectionModel_h (QAbstractItemViewSc a) ((QItemSelectionModel t1)) where
setSelectionModel_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_setSelectionModel cobj_x0 cobj_x1
instance QsetHandler (QAbstractItemView ()) (QAbstractItemView x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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_QAbstractItemView_setHandler14" qtc_QAbstractItemView_setHandler14 :: Ptr (TQAbstractItemView a) -> CWString -> Ptr (Ptr (TQAbstractItemView x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView14 :: (Ptr (TQAbstractItemView x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> CInt -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView14_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemViewSc a) (QAbstractItemView x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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 QsizeHintForColumn_h (QAbstractItemView ()) ((Int)) where
sizeHintForColumn_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_sizeHintForColumn cobj_x0 (toCInt x1)
foreign import ccall "qtc_QAbstractItemView_sizeHintForColumn" qtc_QAbstractItemView_sizeHintForColumn :: Ptr (TQAbstractItemView a) -> CInt -> IO CInt
instance QsizeHintForColumn_h (QAbstractItemViewSc a) ((Int)) where
sizeHintForColumn_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_sizeHintForColumn cobj_x0 (toCInt x1)
instance QsizeHintForRow_h (QAbstractItemView ()) ((Int)) where
sizeHintForRow_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_sizeHintForRow cobj_x0 (toCInt x1)
foreign import ccall "qtc_QAbstractItemView_sizeHintForRow" qtc_QAbstractItemView_sizeHintForRow :: Ptr (TQAbstractItemView a) -> CInt -> IO CInt
instance QsizeHintForRow_h (QAbstractItemViewSc a) ((Int)) where
sizeHintForRow_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_sizeHintForRow cobj_x0 (toCInt x1)
instance QverticalOffset_h (QAbstractItemView ()) (()) where
verticalOffset_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_verticalOffset cobj_x0
foreign import ccall "qtc_QAbstractItemView_verticalOffset" qtc_QAbstractItemView_verticalOffset :: Ptr (TQAbstractItemView a) -> IO CInt
instance QverticalOffset_h (QAbstractItemViewSc a) (()) where
verticalOffset_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_verticalOffset cobj_x0
instance QviewportEvent_h (QAbstractItemView ()) ((QEvent t1)) where
viewportEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_viewportEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_viewportEvent" qtc_QAbstractItemView_viewportEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQEvent t1) -> IO CBool
instance QviewportEvent_h (QAbstractItemViewSc a) ((QEvent t1)) where
viewportEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_viewportEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractItemView ()) (QAbstractItemView x0 -> QModelIndex t1 -> IO (QRect t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect t0))
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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_QAbstractItemView_setHandler15" qtc_QAbstractItemView_setHandler15 :: Ptr (TQAbstractItemView a) -> CWString -> Ptr (Ptr (TQAbstractItemView x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView15 :: (Ptr (TQAbstractItemView x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect t0))) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect t0))))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView15_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemViewSc a) (QAbstractItemView x0 -> QModelIndex t1 -> IO (QRect t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect t0))
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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 (QAbstractItemView ()) ((QModelIndex t1)) where
qvisualRect_h x0 (x1)
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_visualRect cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_visualRect" qtc_QAbstractItemView_visualRect :: Ptr (TQAbstractItemView a) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect ()))
instance QqvisualRect_h (QAbstractItemViewSc a) ((QModelIndex t1)) where
qvisualRect_h x0 (x1)
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_visualRect cobj_x0 cobj_x1
instance QvisualRect_h (QAbstractItemView ()) ((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_QAbstractItemView_visualRect_qth cobj_x0 cobj_x1 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QAbstractItemView_visualRect_qth" qtc_QAbstractItemView_visualRect_qth :: Ptr (TQAbstractItemView a) -> Ptr (TQModelIndex t1) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
instance QvisualRect_h (QAbstractItemViewSc 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_QAbstractItemView_visualRect_qth cobj_x0 cobj_x1 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
instance QsetHandler (QAbstractItemView ()) (QAbstractItemView x0 -> QItemSelection t1 -> IO (QRegion t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQRegion t0))
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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_QAbstractItemView_setHandler16" qtc_QAbstractItemView_setHandler16 :: Ptr (TQAbstractItemView a) -> CWString -> Ptr (Ptr (TQAbstractItemView x0) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQRegion t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView16 :: (Ptr (TQAbstractItemView x0) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQRegion t0))) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQRegion t0))))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView16_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemViewSc a) (QAbstractItemView x0 -> QItemSelection t1 -> IO (QRegion t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQRegion t0))
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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 (QAbstractItemView ()) ((QItemSelection t1)) where
visualRegionForSelection_h x0 (x1)
= withQRegionResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_visualRegionForSelection cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_visualRegionForSelection" qtc_QAbstractItemView_visualRegionForSelection :: Ptr (TQAbstractItemView a) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQRegion ()))
instance QvisualRegionForSelection_h (QAbstractItemViewSc a) ((QItemSelection t1)) where
visualRegionForSelection_h x0 (x1)
= withQRegionResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_visualRegionForSelection cobj_x0 cobj_x1
instance QcontextMenuEvent_h (QAbstractItemView ()) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_contextMenuEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_contextMenuEvent" qtc_QAbstractItemView_contextMenuEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent_h (QAbstractItemViewSc a) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_contextMenuEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractItemView ()) (QAbstractItemView x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qAbstractItemViewFromPtr 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_QAbstractItemView_setHandler17" qtc_QAbstractItemView_setHandler17 :: Ptr (TQAbstractItemView a) -> CWString -> Ptr (Ptr (TQAbstractItemView x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView17 :: (Ptr (TQAbstractItemView x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> IO (Ptr (TQSize t0))))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView17_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemViewSc a) (QAbstractItemView x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qAbstractItemViewFromPtr 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 (QAbstractItemView ()) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_minimumSizeHint cobj_x0
foreign import ccall "qtc_QAbstractItemView_minimumSizeHint" qtc_QAbstractItemView_minimumSizeHint :: Ptr (TQAbstractItemView a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint_h (QAbstractItemViewSc a) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_minimumSizeHint cobj_x0
instance QminimumSizeHint_h (QAbstractItemView ()) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QAbstractItemView_minimumSizeHint_qth" qtc_QAbstractItemView_minimumSizeHint_qth :: Ptr (TQAbstractItemView a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint_h (QAbstractItemViewSc a) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QpaintEvent_h (QAbstractItemView ()) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_paintEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_paintEvent" qtc_QAbstractItemView_paintEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent_h (QAbstractItemViewSc a) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_paintEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractItemView ()) (QAbstractItemView x0 -> Int -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView18 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView18_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> CInt -> CInt -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qAbstractItemViewFromPtr 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_QAbstractItemView_setHandler18" qtc_QAbstractItemView_setHandler18 :: Ptr (TQAbstractItemView a) -> CWString -> Ptr (Ptr (TQAbstractItemView x0) -> CInt -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView18 :: (Ptr (TQAbstractItemView x0) -> CInt -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> CInt -> CInt -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView18_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemViewSc a) (QAbstractItemView x0 -> Int -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView18 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView18_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> CInt -> CInt -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qAbstractItemViewFromPtr 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 (QAbstractItemView ()) ((Int, Int)) where
scrollContentsBy_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_scrollContentsBy cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QAbstractItemView_scrollContentsBy" qtc_QAbstractItemView_scrollContentsBy :: Ptr (TQAbstractItemView a) -> CInt -> CInt -> IO ()
instance QscrollContentsBy_h (QAbstractItemViewSc a) ((Int, Int)) where
scrollContentsBy_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_scrollContentsBy cobj_x0 (toCInt x1) (toCInt x2)
instance QqsizeHint_h (QAbstractItemView ()) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_sizeHint cobj_x0
foreign import ccall "qtc_QAbstractItemView_sizeHint" qtc_QAbstractItemView_sizeHint :: Ptr (TQAbstractItemView a) -> IO (Ptr (TQSize ()))
instance QqsizeHint_h (QAbstractItemViewSc a) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_sizeHint cobj_x0
instance QsizeHint_h (QAbstractItemView ()) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QAbstractItemView_sizeHint_qth" qtc_QAbstractItemView_sizeHint_qth :: Ptr (TQAbstractItemView a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint_h (QAbstractItemViewSc a) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QwheelEvent_h (QAbstractItemView ()) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_wheelEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_wheelEvent" qtc_QAbstractItemView_wheelEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent_h (QAbstractItemViewSc a) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_wheelEvent cobj_x0 cobj_x1
instance QchangeEvent_h (QAbstractItemView ()) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_changeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_changeEvent" qtc_QAbstractItemView_changeEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent_h (QAbstractItemViewSc a) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_changeEvent cobj_x0 cobj_x1
instance QactionEvent_h (QAbstractItemView ()) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_actionEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_actionEvent" qtc_QAbstractItemView_actionEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent_h (QAbstractItemViewSc a) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_actionEvent cobj_x0 cobj_x1
instance QcloseEvent_h (QAbstractItemView ()) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_closeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_closeEvent" qtc_QAbstractItemView_closeEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent_h (QAbstractItemViewSc a) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_closeEvent cobj_x0 cobj_x1
instance QdevType_h (QAbstractItemView ()) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_devType cobj_x0
foreign import ccall "qtc_QAbstractItemView_devType" qtc_QAbstractItemView_devType :: Ptr (TQAbstractItemView a) -> IO CInt
instance QdevType_h (QAbstractItemViewSc a) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_devType cobj_x0
instance QenterEvent_h (QAbstractItemView ()) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_enterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_enterEvent" qtc_QAbstractItemView_enterEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent_h (QAbstractItemViewSc a) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_enterEvent cobj_x0 cobj_x1
instance QheightForWidth_h (QAbstractItemView ()) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_heightForWidth cobj_x0 (toCInt x1)
foreign import ccall "qtc_QAbstractItemView_heightForWidth" qtc_QAbstractItemView_heightForWidth :: Ptr (TQAbstractItemView a) -> CInt -> IO CInt
instance QheightForWidth_h (QAbstractItemViewSc a) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_heightForWidth cobj_x0 (toCInt x1)
instance QhideEvent_h (QAbstractItemView ()) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_hideEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_hideEvent" qtc_QAbstractItemView_hideEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent_h (QAbstractItemViewSc a) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_hideEvent cobj_x0 cobj_x1
instance QkeyReleaseEvent_h (QAbstractItemView ()) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_keyReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_keyReleaseEvent" qtc_QAbstractItemView_keyReleaseEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent_h (QAbstractItemViewSc a) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_keyReleaseEvent cobj_x0 cobj_x1
instance QleaveEvent_h (QAbstractItemView ()) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_leaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_leaveEvent" qtc_QAbstractItemView_leaveEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent_h (QAbstractItemViewSc a) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_leaveEvent cobj_x0 cobj_x1
instance QmoveEvent_h (QAbstractItemView ()) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_moveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_moveEvent" qtc_QAbstractItemView_moveEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent_h (QAbstractItemViewSc a) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_moveEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractItemView ()) (QAbstractItemView x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView19 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView19_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler19 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qAbstractItemViewFromPtr 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_QAbstractItemView_setHandler19" qtc_QAbstractItemView_setHandler19 :: Ptr (TQAbstractItemView a) -> CWString -> Ptr (Ptr (TQAbstractItemView x0) -> IO (Ptr (TQPaintEngine t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView19 :: (Ptr (TQAbstractItemView x0) -> IO (Ptr (TQPaintEngine t0))) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> IO (Ptr (TQPaintEngine t0))))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView19_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemViewSc a) (QAbstractItemView x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView19 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView19_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler19 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qAbstractItemViewFromPtr 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 (QAbstractItemView ()) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_paintEngine cobj_x0
foreign import ccall "qtc_QAbstractItemView_paintEngine" qtc_QAbstractItemView_paintEngine :: Ptr (TQAbstractItemView a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine_h (QAbstractItemViewSc a) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_paintEngine cobj_x0
instance QsetHandler (QAbstractItemView ()) (QAbstractItemView x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView20 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView20_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler20 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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_QAbstractItemView_setHandler20" qtc_QAbstractItemView_setHandler20 :: Ptr (TQAbstractItemView a) -> CWString -> Ptr (Ptr (TQAbstractItemView x0) -> CBool -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView20 :: (Ptr (TQAbstractItemView x0) -> CBool -> IO ()) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> CBool -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView20_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemViewSc a) (QAbstractItemView x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView20 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView20_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler20 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qAbstractItemViewFromPtr 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 (QAbstractItemView ()) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_setVisible cobj_x0 (toCBool x1)
foreign import ccall "qtc_QAbstractItemView_setVisible" qtc_QAbstractItemView_setVisible :: Ptr (TQAbstractItemView a) -> CBool -> IO ()
instance QsetVisible_h (QAbstractItemViewSc a) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractItemView_setVisible cobj_x0 (toCBool x1)
instance QshowEvent_h (QAbstractItemView ()) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_showEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_showEvent" qtc_QAbstractItemView_showEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent_h (QAbstractItemViewSc a) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_showEvent cobj_x0 cobj_x1
instance QtabletEvent_h (QAbstractItemView ()) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_tabletEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractItemView_tabletEvent" qtc_QAbstractItemView_tabletEvent :: Ptr (TQAbstractItemView a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent_h (QAbstractItemViewSc a) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractItemView_tabletEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractItemView ()) (QAbstractItemView x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView21 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView21_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler21 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qAbstractItemViewFromPtr 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_QAbstractItemView_setHandler21" qtc_QAbstractItemView_setHandler21 :: Ptr (TQAbstractItemView a) -> CWString -> Ptr (Ptr (TQAbstractItemView 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_QAbstractItemView21 :: (Ptr (TQAbstractItemView x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQAbstractItemView x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QAbstractItemView21_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractItemViewSc a) (QAbstractItemView x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractItemView21 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractItemView21_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractItemView_setHandler21 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractItemView x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qAbstractItemViewFromPtr 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 (QAbstractItemView ()) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QAbstractItemView_eventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QAbstractItemView_eventFilter" qtc_QAbstractItemView_eventFilter :: Ptr (TQAbstractItemView a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter_h (QAbstractItemViewSc 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_QAbstractItemView_eventFilter cobj_x0 cobj_x1 cobj_x2
| uduki/hsQt | Qtc/Gui/QAbstractItemView_h.hs | bsd-2-clause | 116,200 | 0 | 18 | 24,003 | 36,565 | 17,564 | 19,001 | -1 | -1 |
{-|
Module : Network.NSFW.Firewall.Rule
Description : Defines the basic packet filtering rules.
-}
module Network.NSFW.Firewall.Rule
( makeBlacklistFilter, protocolBlacklistFilter, sourceIpBlacklistFilter
) where
import Network.NSFW.Firewall.Common
( Action(DROP, PASS), FirewallState, LogLevel(LogInfo), PacketFilterRule
, getProtocolBlacklist, getSourceIpBlacklist)
import Network.NSFW.Firewall.Logging (logMsg)
import Network.NSFW.Firewall.Packet (Packet, getProtocol, getSourceIpAddress)
import Control.Monad.RWS (get)
-- | Function to generate blacklist packet filtering rules.
makeBlacklistFilter :: (Eq a, Show a) =>
String -> (Packet -> a) -> (FirewallState -> [a]) -> PacketFilterRule Action
makeBlacklistFilter name getField blacklist packet = do
fwState <- get
let field = getField packet
if field `elem` blacklist fwState
then do logMsg LogInfo ("Dropping packet because " ++ name ++ " " ++ show field
++ " is blacklisted.")
return DROP
else return PASS
-- | Filter a packet by the protocol blacklist in FirewallState.
protocolBlacklistFilter :: PacketFilterRule Action
protocolBlacklistFilter = makeBlacklistFilter "protocol" getProtocol getProtocolBlacklist
-- | Filter a packet by the source IP blacklist in FirewallState.
sourceIpBlacklistFilter :: PacketFilterRule Action
sourceIpBlacklistFilter = makeBlacklistFilter "source IP" getSourceIpAddress getSourceIpBlacklist
| m-renaud/NSFW | src/Network/NSFW/Firewall/Rule.hs | bsd-2-clause | 1,492 | 0 | 15 | 265 | 285 | 161 | 124 | 22 | 2 |
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module Development.Ecstatic.SimplifyDef (
simplify,
isSum, isMul, isAtom, isPrim
) where
import Development.Ecstatic.Types()
import qualified Simplify as S
import Language.C
import qualified Data.Map.Strict as M
-- Exported function
simplify :: CExpr -> CExpr
simplify = simplify'
simplify' :: CExpr -> CExpr
simplify' = rebuild . (S.simplify expr_def)
-- CExpr builder
rebuild :: S.Poly CExpr Int -> CExpr
rebuild poly =
case map toProd (M.toList poly) of
[] -> 0
ps -> foldl1 (+) ps
where
toProd :: ([(CExpr, Int)], Int) -> CExpr
toProd (ts, coef) =
let coef' = fromIntegral coef
in
case ts of
[] -> coef'
_ -> foldl1 (*) $
((if coef == (S.one expr_def) then [] else [coef']) ++
concatMap (\(n, exp) -> replicate exp n) ts)
-- module Simplify definitions
expr_def :: S.Expr CExpr CExpr Int
expr_def = S.Expr
{ S.isSum = isSum
, S.isMul = isMul
, S.isAtom = isAtom
, S.isPrim = isPrim
, S.zero = 0
, S.one = 1
}
isSum :: CExpr -> Maybe [CExpr]
isSum (CBinary CAddOp t1 t2 _) = Just [t1, t2]
isSum (CBinary CSubOp t1 t2 _) =
Just [t1, CUnary CMinOp t2 undefNode]
isSum _ = Nothing
isMul :: CExpr -> Maybe [CExpr]
isMul (CBinary CMulOp t1 t2 _) = Just [t1, t2]
isMul _ = Nothing
isAtom :: CExpr -> Maybe CExpr
isAtom (CBinary CMulOp _ _ _) = Nothing
isAtom (CBinary CAddOp _ _ _) = Nothing
isAtom (CConst (CIntConst (CInteger _ _ _) _)) = Nothing
isAtom t = Just t
isPrim' :: CExpr -> Maybe Int
isPrim' (CConst (CIntConst (CInteger number _ _) _)) = Just (fromIntegral number)
isPrim' _ = Nothing
isPrim :: CExpr -> Maybe Int
isPrim x | Just n <- isPrim' x = Just n
isPrim (CUnary CMinOp x _) | Just n <- isPrim' x = Just (-n)
isPrim _ = Nothing
deriving instance Ord CExpr
deriving instance Eq CExpr
deriving instance Ord (CBuiltinThing NodeInfo)
deriving instance Eq (CBuiltinThing NodeInfo)
deriving instance Ord (CPartDesignator NodeInfo)
deriving instance Eq (CPartDesignator NodeInfo)
deriving instance Ord (CConstant NodeInfo)
deriving instance Eq (CConstant NodeInfo)
deriving instance Ord (CDeclaration NodeInfo)
deriving instance Eq (CDeclaration NodeInfo)
deriving instance Ord (CDeclarationSpecifier NodeInfo)
deriving instance Eq (CDeclarationSpecifier NodeInfo)
deriving instance Ord (CTypeQualifier NodeInfo)
deriving instance Eq (CTypeQualifier NodeInfo)
deriving instance Ord (CDeclarator NodeInfo)
deriving instance Eq (CDeclarator NodeInfo)
deriving instance Ord (CStatement NodeInfo)
deriving instance Eq (CStatement NodeInfo)
deriving instance Ord (CAssemblyStatement NodeInfo)
deriving instance Eq (CAssemblyStatement NodeInfo)
deriving instance Ord (CDerivedDeclarator NodeInfo)
deriving instance Eq (CDerivedDeclarator NodeInfo)
deriving instance (Ord (CInitializer NodeInfo))
deriving instance (Eq (CInitializer NodeInfo))
deriving instance (Ord (CTypeSpecifier NodeInfo))
deriving instance (Eq (CTypeSpecifier NodeInfo))
deriving instance (Ord (CCompoundBlockItem NodeInfo))
deriving instance (Eq (CCompoundBlockItem NodeInfo))
deriving instance (Ord (CAssemblyOperand NodeInfo))
deriving instance (Eq (CAssemblyOperand NodeInfo))
deriving instance (Ord (CArraySize NodeInfo))
deriving instance (Eq (CArraySize NodeInfo))
deriving instance (Ord (CAttribute NodeInfo))
deriving instance (Eq (CAttribute NodeInfo))
deriving instance (Ord (CEnumeration NodeInfo))
deriving instance (Eq (CEnumeration NodeInfo))
deriving instance (Ord (CFunctionDef NodeInfo))
deriving instance (Eq (CFunctionDef NodeInfo))
deriving instance (Ord (CStringLiteral NodeInfo))
deriving instance (Eq (CStringLiteral NodeInfo))
deriving instance (Ord (CStructureUnion NodeInfo))
deriving instance (Eq (CStructureUnion NodeInfo))
deriving instance (Ord (CStructTag))
| kovach/ecstatic | Development/Ecstatic/SimplifyDef.hs | bsd-2-clause | 3,860 | 1 | 21 | 615 | 1,436 | 750 | 686 | 98 | 4 |
import Data.Array
import qualified Data.Array.Unboxed as U
import qualified Data.Foldable as Fld
import Data.List
import qualified Data.Map as Map
import Data.Maybe
import qualified Data.Sequence as Seq
buildArr la a b f = res
where
res = la (a, b) (map (f (res !)) [a .. b])
merge [] xs = xs
merge xs [] = xs
merge xs@(x : xs') ys@(y : ys') = if x <= y then x : merge xs' ys else y : merge xs ys'
arrlst xs = map (xs !) (U.indices xs)
main = do
pstr <- getLine
let (n : q : _) = map read (words pstr)
es <- mapM (const readEdge) [1 .. pred n]
let mchildren = Map.fromListWith (Seq.><) (map (\(a, b) -> (b, Seq.singleton a)) es)
let children = buildArr listArray 1 n (\_ x -> Fld.toList $ if x `Map.member` mchildren then fromJust $ x `Map.lookup` mchildren else Seq.empty)
let ranks = buildArr U.listArray 1 n (\mem x -> Fld.foldl' (+) 0 ((\x -> succ $ mem x) `map` (children ! x)))
sstr <- getLine
let sals = U.listArray (1 :: Int, n) (map (read :: String -> Int) (words sstr))
tst q 0 children sals
--f x children sals = merge (sort $ (\x -> (sals ! x, x)) `map` (children ! x)) $ foldl' merge [] ((\x -> f x children sals) `map` (children ! x))
f x children sals = concat $ (sort $ (\x -> (sals ! x, x)) `map` (children ! x)) : (foldr (:) [] ((\x -> f x children sals) `map` (children ! x)))
qs k xs = if ll == k then pivot else if ll > k then qs k ls else qs (k - ll - 1) (tail rs)
where
pivot = head xs
(ls, rs) = partition (< pivot) xs
ll = length ls
g v k cs ss = qs k xs
where
xs = f v cs ss
tst 0 _ _ _ = return ()
tst q d children sals = do
qstr <- getLine
let (v : k : _) = map read (words qstr)
--let d' = snd $ (f (v + d) children sals) !! (pred k)
let d' = snd $ g (v + d) (pred k) children sals
putStrLn $ show d'
tst (pred q) d' children sals
readEdge :: IO (Int, Int)
readEdge = do
estr <- getLine
let (a : b : _) = map read (words estr)
return (a, b)
| pbl64k/HackerRank-Contests | 2014-06-20-FP/BoleynSalary/bs.qs.hs | bsd-2-clause | 2,006 | 0 | 19 | 550 | 985 | 521 | 464 | 42 | 3 |
module Mashroom (Mashroom(White, Red), number) where
data Mashroom = White | Red deriving Show
number :: Integer
number = 7
| YoshikuniJujo/funpaala | samples/45_summary/Mashroom.hs | bsd-3-clause | 126 | 0 | 5 | 22 | 41 | 27 | 14 | 6 | 1 |
module Graphics.Pastel.GD.Test ( testGD ) where
import Graphics.Pastel
import Graphics.Pastel.GD.Draw
import Graphics.GD
import qualified Data.ByteString as BS
testGD :: (Int, Int) -> Drawing -> IO ()
testGD (w,h) d = do image <- drawGD (w,h) d
bs <- savePngByteString image
BS.putStrLn bs
| willdonnelly/pastel | Graphics/Pastel/GD/Test.hs | bsd-3-clause | 333 | 0 | 9 | 85 | 114 | 64 | 50 | 9 | 1 |
module Control.Concurrent.Suspend
( suspend
, Delay
, usDelay
, msDelay
, sDelay
, mDelay
, hDelay
, (.+.)
) where
------------------------------------------------------------------------------
import Control.Concurrent (threadDelay)
import Control.Monad (when)
------------------------------------------------------------------------------
import Control.Concurrent.Delay
------------------------------------------------------------------------------
-- | Analogy of `Control.Concurrent.threadDelay` that allows for longer delays.
--
-- Suspends the current thread for the given delay (GHC only).
--
-- There is no guarantee that the thread will be rescheduled promptly when the
-- delay has expired, but the thread will never continue to run earlier than specified.
suspend :: Delay -> IO ()
suspend (Delay us) = when (us > 0) $ do
let wait = min us $ fromIntegral (maxBound :: Int)
threadDelay (fromIntegral wait)
suspend $! Delay (us - wait)
{-# INLINEABLE suspend #-} | Palmik/suspend | src/Control/Concurrent/Suspend.hs | bsd-3-clause | 1,022 | 0 | 13 | 171 | 167 | 96 | 71 | 17 | 1 |
import Data.Bits
halfAdder :: Bits a => a -> a -> (a, a)
halfAdder x y = (x `xor` y, x .&. y)
fullAdder :: Bits a => a -> a -> a -> (a, a)
fullAdder x y c_in = (s, c_out)
where s = (x `xor` y) `xor` c_in;
c_out = ((x .&. y) .|. (x .&. c_in)) .|. (y .&. c_in)
fullAdder2 :: Bits a => a -> a -> a -> (a, a)
fullAdder2 x y c_in = (s, c_out)
where (s0, c0) = halfAdder x y;
(s, c1) = halfAdder s0 c_in;
c_out = c0 `xor` c1
| cameronbwhite/ComputerHardware | adder.hs | bsd-3-clause | 461 | 0 | 11 | 144 | 263 | 148 | 115 | 12 | 1 |
module Kraken.Web.ConfigSpec where
import Control.Applicative
import Control.DeepSeq
import Control.Exception
import Data.Aeson
import Data.String.Conversions
import Network.URI
import Network.Wai.Handler.Warp
import Safe
import System.Directory
import System.Environment
import System.IO.Temp
import Test.Hspec
import Kraken.Web.Config
main :: IO ()
main = hspec spec
mkConfig :: Port -> String -> Config
mkConfig port uri = Config {
port = port,
krakenUri = fromJustNote "mkConfig: unparseable test URI" $ parseURI uri
}
spec :: Spec
spec = do
describe "loadConfig" $ do
it "loads from kraken-web.conf by default" $ do
withSystemTempDirectory "kraken-test" $ \ dir -> do
withCurrentDirectory dir $ do
let config = mkConfig 9832 "http://foo.com/bar"
writeFile "kraken-web.conf" $ cs $ encode config
withArgs [] loadConfig `shouldReturn` config
it "loads from a file given by --config" $ do
withSystemTempDirectory "kraken-test" $ \ dir -> do
withCurrentDirectory dir $ do
let config = mkConfig 8439 "http://bar.com/boo"
writeFile "something.file" $ cs $ encode config
withArgs (words "--config something.file") loadConfig
`shouldReturn` config
describe "kraken-web.conf.example" $ do
it "can be parsed as a configuration file" $ do
config <- withArgs (words "--config kraken-web.conf.example")
loadConfig
deepseq (encode config) (return ())
withCurrentDirectory :: FilePath -> IO a -> IO a
withCurrentDirectory dir action = bracket
(getCurrentDirectory <* setCurrentDirectory dir)
setCurrentDirectory
(const action)
| zalora/kraken | test/Kraken/Web/ConfigSpec.hs | bsd-3-clause | 1,805 | 0 | 23 | 487 | 440 | 217 | 223 | 46 | 1 |
module GameWindow (
windowResolution
, windowPosition
, backgroundColor
, fps
, window
) where
import Graphics.Gloss
windowResolution :: (Int, Int)
windowResolution = (1280, 720)
windowPosition :: (Int, Int)
windowPosition = (10,10)
backgroundColor :: Color
backgroundColor = black
fps :: Int
fps = 60
window :: Display
window = InWindow "Droid That You Are Looking For" windowResolution windowPosition | stefanjanjic90/DroidThatYouAreLookingFor | GameWindow.hs | bsd-3-clause | 432 | 0 | 5 | 86 | 107 | 66 | 41 | 17 | 1 |
module Foundation where
import Prelude
import Yesod
import Yesod.Static
import Yesod.Auth
import Yesod.Auth.BrowserId
import Yesod.Auth.GoogleEmail
import Yesod.Default.Config
import Yesod.Default.Util (addStaticContentExternal)
import Network.HTTP.Conduit (Manager)
import qualified Settings
import Settings.Development (development)
import qualified Database.Persist.Store
import Settings.StaticFiles
import Database.Persist.GenericSql
import Settings (widgetFile, Extra (..))
import Model
import Text.Jasmine (minifym)
import Web.ClientSession (getKey)
import Text.Hamlet (hamletFile)
import System.Log.FastLogger (Logger)
-- | The site argument for your application. This can be a good place to
-- keep settings and values requiring initialization before your application
-- starts running, such as database connections. Every handler will have
-- access to the data present here.
data App = App
{ settings :: AppConfig DefaultEnv Extra
, getStatic :: Static -- ^ Settings for static file serving.
, connPool :: Database.Persist.Store.PersistConfigPool Settings.PersistConfig -- ^ Database connection pool.
, httpManager :: Manager
, persistConfig :: Settings.PersistConfig
, appLogger :: Logger
}
-- Set up i18n messages. See the message folder.
-- mkMessage "App" "messages" "en"
-- This is where we define all of the routes in our application. For a full
-- explanation of the syntax, please see:
-- http://www.yesodweb.com/book/handler
--
-- This function does three things:
--
-- * Creates the route datatype AppRoute. Every valid URL in your
-- application can be represented as a value of this type.
-- * Creates the associated type:
-- type instance Route App = AppRoute
-- * Creates the value resourcesApp which contains information on the
-- resources declared below. This is used in Handler.hs by the call to
-- mkYesodDispatch
--
-- What this function does *not* do is create a YesodSite instance for
-- App. Creating that instance requires all of the handler functions
-- for our application to be in scope. However, the handler functions
-- usually require access to the AppRoute datatype. Therefore, we
-- split these actions into two functions and place them in separate files.
mkYesodData "App" $(parseRoutesFile "config/routes")
type Form x = Html -> MForm App App (FormResult x, Widget)
-- Please see the documentation for the Yesod typeclass. There are a number
-- of settings which can be configured by overriding methods here.
instance Yesod App where
approot = ApprootMaster $ appRoot . settings
-- Store session data on the client in encrypted cookies,
-- default session idle timeout is 120 minutes
makeSessionBackend _ = do
key <- getKey "config/client_session_key.aes"
let timeout = 120 * 60 -- 120 minutes
(getCachedDate, _closeDateCache) <- clientSessionDateCacher timeout
return . Just $ clientSessionBackend2 key getCachedDate
defaultLayout widget = do
master <- getYesod
mmsg <- getMessage
-- We break up the default layout into two components:
-- default-layout is the contents of the body tag, and
-- default-layout-wrapper is the entire page. Since the final
-- value passed to hamletToRepHtml cannot be a widget, this allows
-- you to use normal widget features in default-layout.
pc <- widgetToPageContent $ do
$(widgetFile "normalize")
addStylesheet $ StaticR css_bootstrap_css
$(widgetFile "default-layout")
hamletToRepHtml $(hamletFile "templates/default-layout-wrapper.hamlet")
-- This is done to provide an optimization for serving static files from
-- a separate domain. Please see the staticRoot setting in Settings.hs
urlRenderOverride y (StaticR s) =
Just $ uncurry (joinPath y (Settings.staticRoot $ settings y)) $ renderRoute s
urlRenderOverride _ _ = Nothing
-- The page to be redirected to when authentication is required.
authRoute _ = Just $ AuthR LoginR
-- This function creates static content files in the static folder
-- and names them based on a hash of their content. This allows
-- expiration dates to be set far in the future without worry of
-- users receiving stale content.
addStaticContent =
addStaticContentExternal minifym genFileName Settings.staticDir (StaticR . flip StaticRoute [])
where
-- Generate a unique filename based on the content itself
genFileName lbs
| development = "autogen-" ++ base64md5 lbs
| otherwise = base64md5 lbs
-- Place Javascript at bottom of the body tag so the rest of the page loads first
jsLoader _ = BottomOfBody
-- What messages should be logged. The following includes all messages when
-- in development, and warnings and errors in production.
shouldLog _ _source level =
development || level == LevelWarn || level == LevelError
getLogger = return . appLogger
-- How to run database actions.
instance YesodPersist App where
type YesodPersistBackend App = SqlPersist
runDB f = do
master <- getYesod
Database.Persist.Store.runPool
(persistConfig master)
f
(connPool master)
instance YesodAuth App where
type AuthId App = UserId
-- Where to send a user after successful login
loginDest _ = HomeR
-- Where to send a user after logout
logoutDest _ = HomeR
getAuthId creds = runDB $ do
x <- getBy $ UniqueUser $ credsIdent creds
case x of
Just (Entity uid _) -> return $ Just uid
Nothing -> do
fmap Just $ insert $ User (credsIdent creds) Nothing
-- You can add other plugins like BrowserID, email or OAuth here
authPlugins _ = [authBrowserId, authGoogleEmail]
authHttpManager = httpManager
-- This instance is required to use forms. You can modify renderMessage to
-- achieve customized and internationalized form validation messages.
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
-- | Get the 'Extra' value, used to hold data from the settings.yml file.
getExtra :: Handler Extra
getExtra = fmap (appExtra . settings) getYesod
-- Note: previous versions of the scaffolding included a deliver function to
-- send emails. Unfortunately, there are too many different options for us to
-- give a reasonable default. Instead, the information is available on the
-- wiki:
--
-- https://github.com/yesodweb/yesod/wiki/Sending-email
| mkrauskopf/ouch-web | Foundation.hs | bsd-3-clause | 6,586 | 0 | 17 | 1,426 | 907 | 499 | 408 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TupleSections #-}
module Snap.Snaplet.CustomAuth.OAuth2.Internal
( oauth2Init
, saveAction
, redirectToProvider
) where
import Control.Error.Util hiding (err)
import Control.Lens
import Control.Monad.Except
import Control.Monad.Trans.Except
import Control.Monad.Trans.Maybe
import Control.Monad.State
import Data.Aeson
import qualified Data.Binary
import Data.Binary (Binary)
import Data.Binary.Instances ()
import qualified Data.ByteString.Base64
import Data.ByteString.Lazy (ByteString, toStrict, fromStrict)
import Data.Char (chr)
import qualified Data.Configurator as C
import Data.HashMap.Lazy (HashMap)
import qualified Data.HashMap.Lazy as M
import Data.Maybe (isJust, isNothing, catMaybes)
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (decodeLatin1, decodeUtf8', encodeUtf8)
import Data.Time.Clock (UTCTime, getCurrentTime, diffUTCTime)
import Network.HTTP.Client (Manager)
import Network.OAuth.OAuth2
import Prelude hiding (lookup)
import Snap hiding (path)
import Snap.Snaplet.Session
import System.Random
import URI.ByteString
import Snap.Snaplet.CustomAuth.AuthManager
import Snap.Snaplet.CustomAuth.Types hiding (name)
import Snap.Snaplet.CustomAuth.User (setUser, currentUser, recoverSession)
import Snap.Snaplet.CustomAuth.Util (getStateName, getParamText, setFailure)
oauth2Init
:: IAuthBackend u i e b
=> OAuth2Settings u i e b
-> Initializer b (AuthManager u e b) (HashMap Text Provider)
oauth2Init s = do
cfg <- getSnapletUserConfig
root <- getSnapletRootURL
hostname <- liftIO $ C.require cfg "hostname"
scheme <- liftIO $ C.lookupDefault "https" cfg "protocol"
names <- liftIO $ C.lookupDefault [] cfg "oauth2.providers"
-- TODO: use discovery
let makeProvider name = let
name' = "oauth2." <> name
lk = MaybeT . C.lookup cfg . (name' <>)
lku n = lk n >>=
MaybeT . return . hush . parseURI strictURIParserOptions . encodeUtf8
callback = URI (Scheme scheme)
(Just $ Authority Nothing (Host hostname) Nothing)
("/" <> root <> "/oauth2callback/" <> (encodeUtf8 name))
mempty Nothing
in Provider
<$> (MaybeT $ return $ pure $ T.toLower $ name)
<*> (MaybeT $ return $ pure $ Nothing)
<*> lk ".scope"
<*> lku ".endpoint.identity"
<*> lk ".identityField"
<*> (OAuth2
<$> lk ".clientId"
<*> (lift $ runMaybeT $ lk ".clientSecret")
<*> lku ".endpoint.auth"
<*> lku ".endpoint.access"
<*> (pure $ Just callback))
addRoutes $ mapped._2 %~ (bracket s) $
[ ("oauth2createaccount", oauth2CreateAccount s)
, ("oauth2callback/:provider", oauth2Callback s)
, ("oauth2login/:provider", redirectLogin)
]
liftIO $ M.fromList . map (\x -> (providerName x, x)) . catMaybes <$>
(mapM (runMaybeT . makeProvider) names)
redirectLogin
:: Handler b (AuthManager u e b) ()
redirectLogin = do
provs <- gets providers
provider <- (flip M.lookup provs =<<) <$> getParamText "provider"
maybe pass toProvider provider
where
toProvider p = do
success <- redirectToProvider $ providerName p
if success then return () else pass
getRedirUrl
:: Provider
-> Text
-> URI
getRedirUrl p token =
appendQueryParams [("state", encodeUtf8 token)
,("scope", encodeUtf8 $ scope p)] $ authorizationUrl $ oauth p
redirectToProvider
:: Text
-> Handler b (AuthManager u e b) Bool
redirectToProvider pName = do
maybe (return False) redirectToProvider' =<< M.lookup pName <$> gets providers
redirectToProvider'
:: Provider
-> Handler b (AuthManager u e b) Bool
redirectToProvider' provider = do
-- Generate a state token and store it in SessionManager
store <- gets stateStore'
stamp <- liftIO $ (T.pack . show) <$> getCurrentTime
name <- getStateName
let randomChar i
| i < 10 = chr (i+48)
| i < 36 = chr (i+55)
| otherwise = chr (i+61)
randomText n = T.pack <$> replicateM n (randomChar <$> randomRIO (0,61))
token <- liftIO $ randomText 20
withTop' store $ do
setInSession name token
setInSession (name <> "_stamp") stamp
commitSession
let redirUrl = serializeURIRef' $ getRedirUrl provider token
redirect' redirUrl 303
getUserInfo
:: MonadIO m
=> Manager
-> Provider
-> AccessToken
-> ExceptT (Maybe ByteString) m Text
getUserInfo mgr provider token = do
let endpoint = identityEndpoint provider
(withExceptT Just $ ExceptT $ liftIO $ authGetJSON mgr token endpoint) >>=
(maybe (throwE Nothing) pure . lookupProviderInfo)
where
lookup' a b = maybeText =<< M.lookup a b
maybeText (String x) = Just x
maybeText _ = Nothing
lookupProviderInfo = lookup' (identityField provider)
oauth2Callback
:: IAuthBackend u i e b
=> OAuth2Settings u i e b
-> Handler b (AuthManager u e b) ()
oauth2Callback s = do
provs <- gets providers
maybe pass (oauth2Callback' s) =<<
((flip M.lookup provs =<<) <$> getParamText "provider")
oauth2Callback'
:: IAuthBackend u i e b
=> OAuth2Settings u i e b
-> Provider
-> Handler b (AuthManager u e b) ()
oauth2Callback' s provider = do
name <- getStateName
let ss = stateStore s
mgr = httpManager s
res <- runExceptT $ do
let param = oauth provider
expiredStamp <- lift $ withTop' ss $
maybe (return True) (liftIO . isExpiredStamp) =<<
fmap (read . T.unpack) <$> getFromSession (name <> "_stamp")
when expiredStamp $ throwE ExpiredState
hostState <- maybe (throwE StateNotStored) return =<<
(lift $ withTop' ss $ getFromSession name)
providerState <- maybe (throwE StateNotReceived) return =<<
(lift $ getParamText "state")
when (hostState /= providerState) $ throwE BadState
_ <- runMaybeT $ do
err <- MaybeT $ lift $ getParam "error"
lift $ throwE $ ProviderError $ hush $ decodeUtf8' err
-- Get the user id from provider
(maybe (throwE (IdExtractionFailed Nothing)) pure =<<
(fmap ExchangeToken) <$> (lift $ getParamText "code")) >>=
-- TODO: catch?
(liftIO . fetchAccessToken mgr param >=>
either (const $ throwE AccessTokenFetchError) pure >=>
-- TODO: get user id (sub) from idToken in token, if
-- available. Requires JWT handling.
withExceptT (IdExtractionFailed . ((hush . decodeUtf8' . toStrict) =<<)) .
getUserInfo (httpManager s) provider . accessToken)
either (setFailure ((oauth2Failure s) SCallback) (Just $ providerName provider) .
Right . Create . OAuth2Failure)
(oauth2Success s provider) res
-- User has successfully completed OAuth2 login. Get the stored
-- intended action and perform it.
oauth2Success
:: IAuthBackend u i e b
=> OAuth2Settings u i e b
-> Provider
-> Text
-> Handler b (AuthManager u e b) ()
oauth2Success s provider token = do
key <- getActionKey $ providerName provider
store <- gets stateStore'
name <- getStateName
act <- withTop' store $ runMaybeT $ do
act <- MaybeT $ getFromSession key
lift $ deleteFromSession key >> commitSession
return act
withTop' store $ do
setInSession (name <> "_provider") (providerName provider)
setInSession (name <> "_token") token
commitSession
-- When there's no user defined action stored, treat this as a
-- regular login
maybe (doOauth2Login s provider token) (doResume s provider token) act
doOauth2Login
:: IAuthBackend u i e b
=> OAuth2Settings u i e b
-> Provider
-> Text
-> Handler b (AuthManager u e b) ()
doOauth2Login s provider token = do
-- Sanity check: See if the user is already logged in.
recoverSession
currentUser >>=
maybe proceed (const $ setFailure ((oauth2Failure s) SLogin)
(Just $ providerName provider) $
Right $ Create $ OAuth2Failure AlreadyLoggedIn)
where
proceed = do
res <- runExceptT $ do
usr <- ExceptT $ (oauth2Login s) (providerName provider) token
maybe (return ()) (lift . setUser) usr
return usr
either (setFailure ((oauth2Failure s) SLogin)
(Just $ providerName provider) . Left)
(const $ oauth2LoginDone s) res
isExpiredStamp
:: UTCTime
-> IO Bool
isExpiredStamp stamp = do
current <- getCurrentTime
let diff = diffUTCTime current stamp
return $ diff < 0 || diff > 300
prepareOAuth2Create'
:: IAuthBackend u i e b
=> OAuth2Settings u i e b
-> Provider
-> Text
-> Handler b (AuthManager u e b) (Either (Either e CreateFailure) i)
prepareOAuth2Create' s provider token =
(prepareOAuth2Create s) (providerName provider) token >>=
either checkDuplicate (return . Right)
where
checkDuplicate e = do
isE <- isDuplicateError e
return $ Left $ if isE then Right $ OAuth2Failure IdentityInUse else Left e
-- Check that stored action is not too old and that user matches
doResume
:: IAuthBackend u i e b
=> OAuth2Settings u i e b
-> Provider
-> Text
-> Text
-> Handler b (AuthManager u e b) ()
doResume s provider token d = do
recoverSession
user <- currentUser
userId <- runMaybeT $ lift . getUserId =<< (MaybeT $ return user)
res <- runExceptT $ do
d' <- ExceptT . return $ maybe (Left $ Right ActionDecodeError) Right $
((fmap $ \(_, _, x) -> x) . hush . Data.Binary.decodeOrFail . fromStrict) =<<
(hush $ Data.ByteString.Base64.decode $ encodeUtf8 d)
when (requireUser d' && isNothing user) $ throwE (Right AttachNotLoggedIn)
u <- ExceptT $ return . either (Left . Left) Right =<<
(oauth2Check s) (providerName provider) token
-- Compare current user with action's stored user
when (userId /= actionUser d') $
throwE (Right ActionUserMismatch)
case requireUser d' of
-- Compare current user with identity owner
True -> when (maybe True ((/= userId) . Just) u) $
throwE (Right ActionUserMismatch)
-- Ensure that the identity is not yet used
False -> when (isJust u) $ throwE (Right AlreadyAttached)
expired <- liftIO $ isExpiredStamp (actionStamp d')
when expired $ throwE (Right ActionTimeout)
return $ savedAction d'
either (setFailure ((oauth2Failure s) SAction)
(Just $ providerName provider) . fmap Action)
((resumeAction s) (providerName provider) token) res
-- User has successfully signed in via oauth2 and the provider/token
-- did not match with an existing user. This is the endpoint for
-- requesting account creation afterwards.
oauth2CreateAccount
:: IAuthBackend u i e b
=> OAuth2Settings u i e b
-> Handler b (AuthManager u e b) ()
oauth2CreateAccount s = do
store <- gets stateStore'
provs <- gets providers
usrName <- ((hush . decodeUtf8') =<<) <$>
(getParam =<< ("_new" <>) <$> gets userField)
name <- getStateName
provider <- (flip M.lookup provs =<<) <$>
(withTop' store $ getFromSession (name <> "_provider"))
user <- runExceptT $ do
-- Sanity check: See if the user is already logged in.
u <- lift $ recoverSession >> currentUser
when (isJust u) $ throwE (Right $ OAuth2Failure AlreadyUser)
-- Get userName
userName <- hoistEither $ note (Right MissingName) usrName
-- Get the token and provider from session store
res <- maybe (throwE $ Right $ OAuth2Failure NoStoredToken) return =<<
(lift $ withTop' store $ runMaybeT $ do
provider' <- MaybeT $ return provider
token <- MaybeT $ getFromSession (name <> "_token")
return (provider', token))
ExceptT $ fmap (,userName) <$> prepareOAuth2Create' s (fst res) (snd res)
res <- runExceptT $ do
(i, userName) <- hoistEither user
usr <- ExceptT $ create userName i
lift $ setUser usr
return usr
case (user, res) of
(Right (i,_), Left _) -> cancelPrepare i
_ -> return ()
either (setFailure ((oauth2Failure s) SCreate) (providerName <$> provider) . fmap Create)
(oauth2AccountCreated s) res
getActionKey
:: Text
-> Handler b (AuthManager u e b) Text
getActionKey p = do
path <- maybe "auth" id . hush . decodeUtf8' <$> getSnapletRootURL
name <- maybe "auth" id <$> getSnapletName
return $ "__" <> name <> "_" <> path <> "_action_" <> p
saveAction
:: (IAuthBackend u i e b, Binary a)
=> Bool
-> Text
-> a
-> Handler b (AuthManager u e b) ()
saveAction require provider a = do
provs <- gets providers
guard $ provider `elem` (M.keys provs)
let d = Data.Binary.encode a
key <- getActionKey provider
store <- gets $ stateStore'
stamp <- liftIO $ getCurrentTime
i <- runMaybeT $ lift . getUserId =<< MaybeT currentUser
let payload = SavedAction {
actionProvider = provider
, actionStamp = stamp
, actionUser = i
, requireUser = require
, savedAction = toStrict d
}
let d' = decodeLatin1 $ Data.ByteString.Base64.encode $
toStrict . Data.Binary.encode $ payload
withTop' store $ do
setInSession key d'
commitSession
| kaol/snaplet-customauth | Snap/Snaplet/CustomAuth/OAuth2/Internal.hs | bsd-3-clause | 13,223 | 0 | 22 | 3,084 | 4,343 | 2,154 | 2,189 | -1 | -1 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTSyntax #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE RecordWildCards #-}
module TwentyFortyEight
( Player
, getBoard
, moveDirection
, twentyFortyEight
) where
import Control.Applicative
import Control.Lens
import Control.Monad.Trans.Free
import Control.Monad.Trans (MonadIO, liftIO)
import Game
data PlayerF :: * -> * where
GetGame :: (Game -> next) -> PlayerF next
MoveDirection :: Direction -> (Bool -> next) -> PlayerF next
deriving Functor
type Player m = FreeT PlayerF m
getGame :: Monad m => Player m Game
getGame = liftF $ GetGame id
-- Get the game board.
getBoard :: Monad m => Player m Board
getBoard = view gameBoard <$> getGame
-- Move in the given direction. Returns True if the board changed, False otherwise.
moveDirection :: Monad m => Direction -> Player m Bool
moveDirection dir = liftF (MoveDirection dir id)
twentyFortyEight :: MonadIO m => Game -> Player m () -> m ()
twentyFortyEight game player = runFreeT player >>= \case
Pure _ -> return ()
Free (GetGame next) -> twentyFortyEight game (next game)
Free (MoveDirection dir next) ->
if | isWon game' -> liftIO $ putStrLn $ "You win! Score: " ++ show (game^.gameScore)
| isLost game' -> liftIO $ putStrLn $ "You lose. Score: " ++ show (game^.gameScore)
| oldBoard == newBoard -> twentyFortyEight game' (next False)
| otherwise -> liftIO (addNewNumber game') >>= \game'' -> twentyFortyEight game'' (next True)
where
game' :: Game
game' = makeMove dir game
oldBoard, newBoard :: Board
oldBoard = game^.gameBoard
newBoard = game'^.gameBoard
| mitchellwrosen/hs2048-free | TwentyFortyEight.hs | bsd-3-clause | 1,855 | 1 | 15 | 494 | 507 | 261 | 246 | -1 | -1 |
module View (view) where
import System.Hclip (setClipboard)
import Util
import VaultData
tagPred :: String -> String -> Bool
tagPred tag =
if tag == ""
then const True
else (== tag)
filterTag :: [VaultEntry] -> String -> [VaultEntry]
filterTag entries tag =
let anyPred = tagPred tag
in filter (any anyPred . tags) entries
view :: [String] -> IO ()
view [fileName] = view [fileName, ""]
view [fileName,tag] = do
jsonStr <- readFile fileName
let v = parseVault jsonStr
es = filterTag (entries v) tag
e <- selectEntry es
password <- getMasterPassword
if verifyMasterPass password v
then do
putStrLn $ showEntry password e
setClipboard $ getEntryPassword password e
putStrLn "\nEntry password copied to clipboard."
else putStrLn "Incorrect password!"
| oahziur/yige-pass | src/View.hs | bsd-3-clause | 862 | 0 | 12 | 232 | 278 | 140 | 138 | 27 | 2 |
{-# LANGUAGE PatternGuards #-}
-- | Main executive for LambNyaa.
module Network.LambNyaa.Scheduler (schedule) where
import Control.Concurrent
import Control.Monad
import Data.Hashable
import Data.List
import qualified Database.SQLite.Simple as DB
import Network.LambNyaa.Config
import Network.LambNyaa.Item
import Network.LambNyaa.Monad
import Network.LambNyaa.Sink
import Network.LambNyaa.Database
import Network.LambNyaa.Log
import System.Posix.Signals
import System.Exit
info' = info "Scheduler"
note' = note "Scheduler"
-- | Pause thread for a number of seconds.
delaySecs :: Int -> IO ()
delaySecs n = do
forM_ [1..ksecs] . const $ threadDelay (1000 * 1000000)
threadDelay (secs * 1000000)
where
(ksecs, secs) = n `divMod` 1000
-- | Perform a clean exit on SIGTERM or SIGINT.
die :: ThreadId -> IO ()
die mainthread = do
info' $ "Interrupted; performing cleanup and exiting..."
delaySecs 2
clearLogHandlers
throwTo mainthread ExitSuccess
-- | Execute a pipeline according to schedule.
schedule :: Config -> Nyaa () -> IO ()
schedule cfg ny = do
setLogHandlers $ cfgLogHandlers cfg
setLogLevel $ cfgLogLevel cfg
tid <- myThreadId
when (cfgCatchSignals cfg) $ do
installHandler keyboardSignal (Catch $ die tid) (Just fullSignalSet)
installHandler softwareTermination (Catch $ die tid) (Just fullSignalSet)
return ()
case cfgSchedule cfg of
Once -> do
info' "Starting oneshot run..."
tot <- execute cfg ny
info' $ "Run completed! " ++ show tot ++ " items accepted."
(Every n Seconds) -> every n (show n ++ " seconds") $ execute cfg ny
(Every n Minutes) -> every (n*60) (show n ++ " minutes") $ execute cfg ny
(Every n Hours) -> every (n*60*60) (show n ++ " hours") $ execute cfg ny
(Every n Days) -> every (n*24*60*60) (show n ++ " days") $ execute cfg ny
-- | Perform an action every n seconds.
every :: Int -> String -> IO Int -> IO ()
every secs sched act = do
note' $ "Starting scheduling; runs are scheduled for every " ++ sched
go
where
go = do
info' "Starting new run..."
tot <- act
info' $ "Run completed! " ++ show tot ++ " items accepted."
delaySecs secs >> go
-- | Execute a pipeline from Source to Sink, and return the total number of
-- elements processed as well as the total number accepted.
execute :: Config -> Nyaa () -> IO Int
execute cfg nyaa = withSQLite cfg $ \conn -> runNyaa (NyaaEnv conn cfg) nyaa
| valderman/lambnyaa | Network/LambNyaa/Scheduler.hs | bsd-3-clause | 2,471 | 0 | 15 | 526 | 770 | 382 | 388 | 57 | 5 |
{-# LANGUAGE CPP #-}
{- some output from log of "cabal test", three old modules fail, three new modules pass:
Test SampleVar
0: forkIO read thread 1
0: stop thread 1
1: read interrupted
0: write sv #1
0: write sv #2 with timeout
0: timeout triggered, write sv #2 blocked, FAIL
Test QSem
0: forkIO wait thread 1
0: stop thread 1
1: wait interrupted
0: signal q #1
0: forkIO wait thread 2
0: forkIO wait thread 3
0: signal q #2
2: wait done
0: stop thread 2
0: stop thread 3
3: wait interrupted (QUANTITY LOST) FAIL
False
Test QSemN
0: forkIO wait thread 1
0: stop thread 1
1: wait interrupted
0: signal q #1
0: forkIO wait thread 2
0: forkIO wait thread 3
0: signal q #2
2: wait done
0: stop thread 2
0: stop thread 3
3: wait interrupted (QUANTITY LOST) FAIL
False
Expected 3 Failures for above code
Test MSampleVar
0: forkIO read thread 1
0: stop thread 1
1: read interrupted
0: write sv #1
0: write sv #2 with timeout
0: write sv #2 returned, PASS
Test MSem
0: forkIO wait thread 1
0: stop thread 1
1: wait interrupted
0: signal q #1
0: forkIO wait thread 2
2: wait done
0: forkIO wait thread 3
0: signal q #2
3: wait done (QUANTITY CONSERVED) PASS
0: stop thread 2
0: stop thread 3
True
Test MSemN
0: forkIO wait thread 1
0: stop thread 1
1: wait interrupted
0: signal q #1
0: forkIO wait thread 2
2: wait done
0: forkIO wait thread 3
0: signal q #2
3: wait done (QUANTITY CONSERVED) PASS
0: stop thread 2
0: stop thread 3
True
Test suite TestSafeSemaphore: PASS
Test suite logged to: dist/test/SafeSemaphore-0.8.0-TestSafeSemaphore.log
-}
module Main where
import Prelude hiding (read)
import Control.Concurrent
import Control.Exception
import Control.Concurrent.QSem
import Control.Concurrent.QSemN
import qualified Control.Concurrent.MSem as MSem
import qualified Control.Concurrent.MSemN as MSemN
import qualified Control.Concurrent.MSemN2 as MSemN2
import qualified Control.Concurrent.SSem as SSem
import Control.Concurrent.MVar
import Test.HUnit
import System.Exit
#if !MIN_VERSION_base(4,7,0)
import Control.Concurrent.SampleVar
#endif
import Control.Concurrent.MSampleVar as MSV
import System.Timeout
delay = threadDelay (1000*100)
--delay = yield -- now causes tests to fail in ghc 7.4
fork x = do m <- newEmptyMVar
t <- forkIO (finally x (putMVar m ()))
delay
return (t,m)
stop (t,m) = do killThread t
delay
takeMVar m
-- True if test passed, False if test failed
-- This expects FIFO semantics for the waiters
testSem :: Integral n
=> String
-> (n -> IO a)
-> (a->IO ())
-> (a -> IO ())
-> IO Bool
testSem name new wait signal = do
putStrLn ("\n\nTest "++ name)
q <- new 0
putStrLn "0: forkIO wait thread 1"
(t1,m1) <- fork $ do
wait q `onException` (putStrLn "1: wait interrupted")
putStrLn "1: wait done UNEXPECTED"
putStrLn "0: stop thread 1"
stop (t1,m1)
putStrLn "0: signal q #1"
signal q
delay
putStrLn "0: forkIO wait thread 2"
(t2,m2) <- fork $ do
wait q `onException` (putStrLn "2: wait interrupted UNEXPECTED")
putStrLn "2: wait done"
delay
result <- newEmptyMVar
putStrLn "0: forkIO wait thread 3"
(t3,m3) <- fork $ do
wait q `onException` (putStrLn "3: wait interrupted (QUANTITY LOST) FAIL" >> putMVar result False)
putStrLn "3: wait done (QUANTITY CONSERVED) PASS"
putMVar result True
putStrLn "0: signal q #2"
signal q
delay
putStrLn "0: stop thread 2"
stop (t2,m2)
putStrLn "0: stop thread 3"
stop (t3,m3)
r <- takeMVar result
print r
return r
testSV name newEmpty read write = do
putStrLn ("\n\nTest "++ name)
sv <- newEmpty
putStrLn "0: forkIO read thread 1"
(t1,m1) <- fork $ do
read sv `onException` (putStrLn "1: read interrupted")
putStrLn "1: read done UNEXPECTED"
putStrLn "0: stop thread 1"
stop (t1,m1)
putStrLn "0: write sv #1"
write sv 1
putStrLn "0: write sv #2 with timeout"
m <- timeout (1000*100) (write sv 2)
case m of
Nothing -> do
putStrLn "0: timeout triggered, write sv #2 blocked, FAIL"
return False
Just () -> do
putStrLn "0: write sv #2 returned, PASS"
return True
-- True if test passed, False if test failed
-- This does not expect FIFO semantics for the waiters, uses getValue instead
testSSem :: Integral n
=> String
-> (n -> IO a)
-> (a->IO ())
-> (a -> IO ())
-> (a -> IO Int)
-> IO Bool
testSSem name new wait signal getValue = do
putStrLn ("\n\nTest "++ name)
q <- new 0
putStrLn "0: forkIO wait thread 1"
(t1,m1) <- fork $ do
wait q `onException` (putStrLn "1: wait interrupted")
putStrLn "1: wait done UNEXPECTED"
putStrLn "0: stop thread 1"
stop (t1,m1)
putStrLn "0: signal q #1"
signal q
delay
putStrLn "0: forkIO wait thread 2"
(t2,m2) <- fork $ do
wait q `onException` (putStrLn "2: wait interrupted")
putStrLn "2: wait done"
delay
putStrLn "0: forkIO wait thread 3"
(t3,m3) <- fork $ do
wait q `onException` (putStrLn "3: wait interrupted")
putStrLn "3: wait done"
delay
putStrLn "0: signal q #2"
signal q
delay
putStrLn "0: stop thread 2"
stop (t2,m2)
putStrLn "0: stop thread 3"
stop (t3,m3)
r <- getValue q
putStrLn $ "Final Value "++show r
return (r==0)
#if !MIN_VERSION_base(4,7,0)
testOldSV = test $ testSV "SampleVar" newEmptySampleVar readSampleVar writeSampleVar
#else
testOldSV = test $ putStrLn "Cannot test SampleVar on GHC 7.8 because it was removed" >> return False
#endif
testNewSV = test $ testSV "MSampleVar" newEmptySV readSV writeSV
testsQ = TestList . (testOldSV:) . map test $
[ testSem "QSem" newQSem waitQSem signalQSem
, testSem "QSemN" newQSemN (flip waitQSemN 1) (flip signalQSemN 1)
]
testsM = TestList . (testNewSV:) . map test $
[ testSem "MSem" MSem.new MSem.wait MSem.signal
, testSem "MSemN" MSemN.new (flip MSemN.wait 1) (flip MSemN.signal 1)
, testSem "MSemN2" MSemN2.new (flip MSemN2.wait 1) (flip MSemN2.signal 1)
, testSSem "SSem" SSem.new SSem.wait SSem.signal SSem.getValue
]
-- This is run by "cabal test"
main = do
runTestTT testsQ
putStrLn "Expected 3 Failures for above code\n"
c <- runTestTT testsM
if failures c == 0 then exitSuccess else exitFailure
| ChrisKuklewicz/SafeSemaphore | tests/TestKillSem.hs | bsd-3-clause | 6,291 | 0 | 14 | 1,424 | 1,454 | 701 | 753 | 138 | 2 |
-- | Some types at top of expression type.
module Toy.Exp.Ext where
import qualified Data.Map as M
import Toy.Base (Var)
import Toy.Exp.Data (ExpRes)
type LocalVars = M.Map Var ExpRes
| Martoon-00/toy-compiler | src/Toy/Exp/Ext.hs | bsd-3-clause | 219 | 0 | 6 | 64 | 50 | 32 | 18 | 5 | 0 |
{-# LANGUAGE ForeignFunctionInterface, CPP #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.NV.PrimitiveRestart
-- Copyright : (c) Sven Panne 2013
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- All raw functions and tokens from the NV_primitive_restart extension not
-- already in the OpenGL 3.1 core, see
-- <http://www.opengl.org/registry/specs/NV/primitive_restart.txt>.
-- NOTE: The OpenGL 3.1 core has some functions and tokens with the same names,
-- but with different semantics and values, so we use a suffix in those cases.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.NV.PrimitiveRestart (
-- * Functions
glPrimitiveRestart,
glPrimitiveRestartIndexNV,
-- * Tokens
gl_PRIMITIVE_RESTART_NV,
gl_PRIMITIVE_RESTART_INDEX_NV
) where
import Foreign.C.Types
import Graphics.Rendering.OpenGL.Raw.Core31.Types
import Graphics.Rendering.OpenGL.Raw.Extensions
#include "HsOpenGLRaw.h"
extensionNameString :: String
extensionNameString = "GL_NV_primitive_restart"
EXTENSION_ENTRY(dyn_glPrimitiveRestart,ptr_glPrimitiveRestart,"glPrimitiveRestart",glPrimitiveRestart, IO ())
EXTENSION_ENTRY(dyn_glPrimitiveRestartIndexNV,ptr_glPrimitiveRestartIndexNV,"glPrimitiveRestartIndexNV",glPrimitiveRestartIndexNV,GLuint -> IO ())
gl_PRIMITIVE_RESTART_NV :: GLenum
gl_PRIMITIVE_RESTART_NV = 0x8558
gl_PRIMITIVE_RESTART_INDEX_NV :: GLenum
gl_PRIMITIVE_RESTART_INDEX_NV = 0x8559
| mfpi/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/NV/PrimitiveRestart.hs | bsd-3-clause | 1,645 | 0 | 10 | 185 | 156 | 103 | 53 | -1 | -1 |
bindM :: Maybe a -> (a -> Maybe b) -> Maybe b
Just x `bindM` f = f x
Nothing `bindM` _ = Nothing
retM :: a -> Maybe a
retM = Just
appM :: Maybe (a -> b) -> Maybe a -> Maybe b
Just f `appM` Just x = Just $ f x
_ `appM` _ = Nothing
pureM :: a -> Maybe a
pureM = Just
fappM :: Maybe a -> Maybe (a -> b) -> Maybe b
fappM = flip appM
safeDivM :: Integer -> Integer -> Maybe Integer
safeDivM _ 0 = Nothing
safeDivM x y = Just $ x `div` y
calcM :: Integer -> Integer -> Integer -> Integer -> Maybe Integer
calcM a b c d =
a `safeDivM` b `bindM` \x ->
c `safeDivM` d `bindM` \y ->
retM $ x + y
data TryM a = ErrorM String | SuccessM a deriving Show
retT :: a -> TryM a
retT = SuccessM
bindT :: TryM a -> (a -> TryM b) -> TryM b
SuccessM x `bindT` f = f x
ErrorM em `bindT` _ = ErrorM em
safeDivTM :: Integer -> Integer -> TryM Integer
safeDivTM x 0 = ErrorM $ show x ++ " is divided by zero\n"
safeDivTM x y = SuccessM $ x `div` y
mappT :: TryM (a -> b) -> TryM a -> TryM b
tf `mappT` tx = tf `bindT` \f -> tx `bindT` \x -> retT $ f x
calcTM :: Integer -> Integer -> Integer -> Integer -> TryM Integer
calcTM a b c d = retT (+) `mappT` (a `safeDivTM` b) `mappT` (c `safeDivTM` d)
data TryA a = ErrorA String | SuccessA a deriving Show
pureT :: a -> TryA a
pureT = SuccessA
appT :: TryA (a -> b) -> TryA a -> TryA b
SuccessA f `appT` SuccessA x = SuccessA $ f x
SuccessA _ `appT` ErrorA em' = ErrorA em'
ErrorA em `appT` SuccessA _ = ErrorA em
ErrorA em `appT` ErrorA em' = ErrorA $ em ++ em'
safeDivTA :: Integer -> Integer -> TryA Integer
safeDivTA x 0 = ErrorA $ show x ++ " is divided by zero\n"
safeDivTA x y = SuccessA $ x `div` y
calcTA :: Integer -> Integer -> Integer -> Integer -> TryA Integer
calcTA a b c d = pureT (+) `appT` (a `safeDivTA` b) `appT` (c `safeDivTA` d)
calc2 :: Integer -> Integer -> Integer -> TryM Integer
calc2 a b c =
a `safeDivTM` b `bindT` \x ->
x `safeDivTM` c
| YoshikuniJujo/funpaala | samples/34_applicative/applicative.hs | bsd-3-clause | 1,910 | 10 | 10 | 450 | 986 | 515 | 471 | 50 | 1 |
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Main where
import qualified Alerta.Golden as Golden
import qualified Alerta.Hedgehog as Hedgehog
import Test.Tasty (TestTree, defaultMain, testGroup)
import Test.Tasty.Hedgehog (testProperty)
main :: IO ()
main = do
defaultMain $ testGroup "tests"
[ testGroup "Golden tests" Golden.tests
, testGroup "Hedgehog" Hedgehog.tests
]
| mjhopkins/alerta-client | test/Spec.hs | bsd-3-clause | 436 | 0 | 11 | 102 | 95 | 56 | 39 | 11 | 1 |
{-# OPTIONS_GHC -Wall #-}
module Messages.Strings where
import Messages.Types
showFiles :: [FilePath] -> String
showFiles = unlines . map (" " ++)
showPromptMessage :: PromptMessage -> String
showPromptMessage (FilesWillBeOverwritten filePaths) =
unlines
[ "This will overwrite the following files to use Elm's preferred style:"
, ""
, showFiles filePaths
, "This cannot be undone! Make sure to back up these files before proceeding."
, ""
, "Are you sure you want to overwrite these files with formatted versions? (y/n)"
]
showErrorMessage :: ErrorMessage -> String
showErrorMessage ErrorsHeading = "ERRORS"
showErrorMessage (BadInputFiles filePaths) =
unlines
[ "There was a problem reading one or more of the specified input files:"
, ""
, unlines $ map ((++) " " . showInputMessage) filePaths
, "Please check the given paths."
]
showErrorMessage SingleOutputWithMultipleInputs =
unlines
[ "Can't write to the OUTPUT path, because multiple .elm files have been specified."
, ""
, "Please remove the --output argument. The .elm files in INPUT will be formatted in place."
]
showErrorMessage TooManyInputs =
"Too many input sources! Please only provide one of either INPUT or --stdin"
showErrorMessage OutputAndValidate =
"Cannot use --output and --validate together"
showErrorMessage (MustSpecifyVersionWithUpgrade elmVersion) =
"I can only upgrade code to the latest Elm version. To make sure I'm doing what you expect, you must also specify --elm-version=" ++ show elmVersion ++ " when you use --upgrade."
showInputMessage :: InputFileMessage -> String
showInputMessage (FileDoesNotExist path) =
path ++ ": File does not exist"
showInputMessage (NoElmFiles path) =
path ++ ": Directory does not contain any *.elm files"
| nukisman/elm-format-short | src/Messages/Strings.hs | bsd-3-clause | 1,869 | 0 | 11 | 400 | 260 | 140 | 120 | 38 | 1 |
module Main where
import Haskus.System.Input
import Haskus.System.Event
import Haskus.System.Sys
import Haskus.System.Terminal
import Haskus.System.Process
import Haskus.System.Linux.Handle
import Haskus.System.Linux.FileSystem
import Haskus.Utils.Flow
import qualified Haskus.Format.Binary.BitSet as BitSet
import System.Environment
main :: IO ()
main = runSys' <| do
term <- defaultTerminal
args <- liftIO getArgs
case args of
(devpath:_) -> do
let flgs = BitSet.fromList [HandleReadWrite,HandleNonBlocking]
hdl <- open Nothing devpath flgs BitSet.empty
|> evalCatchFlowT (\err -> error ( "Unable to open device: " ++ show err))
eventChannel <- newEventReader hdl
onEvent eventChannel <| \ev -> do
let ev' = makeInputEvent ev
case inputEventType ev' of
InputKeyEvent action key
| action /= KeyRepeat -> writeStrLn term (show key ++ ": " ++ show action)
_ -> return ()
threadDelaySec 20
_ -> writeStrLn term ("Usage: sudo haskus-keys /dev/input/event0")
| hsyl20/ViperVM | haskus-system-tools/src/keys/Main.hs | bsd-3-clause | 1,148 | 2 | 25 | 318 | 312 | 160 | 152 | 29 | 3 |
{-# LANGUAGE FlexibleContexts, RankNTypes, CPP #-}
module AWS.RDS.DBSnapshot
( describeDBSnapshots
, createDBSnapshot
, deleteDBSnapshot
, copyDBSnapshot
) where
import Data.Text (Text)
#if MIN_VERSION_conduit(1,1,0)
import Control.Monad.Trans.Resource (MonadThrow, MonadResource, MonadBaseControl)
#endif
import Data.Conduit
import Control.Applicative
import Data.XML.Types (Event(..))
import AWS.Util
import AWS.Lib.Query
import AWS.Lib.Parser
import AWS.RDS.Types hiding (Event)
import AWS.RDS.Internal
describeDBSnapshots
:: (MonadBaseControl IO m, MonadResource m)
=> Maybe Text -- ^ DBInstanceIdentifier
-> Maybe Text -- ^ DBSnapshotIdentifier
-> Maybe Text -- ^ Marker
-> Maybe Int -- ^ MaxRecords
-> Maybe Text -- ^ SnapshotType
-> RDS m [DBSnapshot]
describeDBSnapshots dbiid dbsid marker maxRecords sType =
rdsQuery "DescribeDBSnapshots" params sinkDBSnapshots
where
params =
[ "DBInstanceIdentifier" |=? dbiid
, "DBSnapshotIdentifier" |=? dbsid
, "Marker" |=? marker
, "MaxRecords" |=? toText <$> maxRecords
, "SnapshotType" |=? sType
]
sinkDBSnapshots
:: MonadThrow m
=> Consumer Event m [DBSnapshot]
sinkDBSnapshots = elements "DBSnapshot" sinkDBSnapshot
sinkDBSnapshot
:: MonadThrow m
=> Consumer Event m DBSnapshot
sinkDBSnapshot = DBSnapshot
<$> getT "Port"
<*> getT "Iops"
<*> getT "Engine"
<*> getT "Status"
<*> getT "SnapshotType"
<*> getT "LicenseModel"
<*> getT "DBInstanceIdentifier"
<*> getT "EngineVersion"
<*> getT "DBSnapshotIdentifier"
<*> getT "SnapshotCreateTime"
<*> getT "VpcId"
<*> getT "AvailabilityZone"
<*> getT "InstanceCreateTime"
<*> getT "AllocatedStorage"
<*> getT "MasterUsername"
createDBSnapshot
:: (MonadBaseControl IO m, MonadResource m)
=> Text -- ^ DBInstanceIdentifier
-> Text -- ^ DBSnapshotIdentifier
-> RDS m DBSnapshot
createDBSnapshot dbiid dbsid =
rdsQuery "CreateDBSnapshot" params $
element "DBSnapshot" sinkDBSnapshot
where
params =
[ "DBInstanceIdentifier" |= dbiid
, "DBSnapshotIdentifier" |= dbsid
]
deleteDBSnapshot
:: (MonadBaseControl IO m, MonadResource m)
=> Text -- ^ DBSnapshotIdentifier
-> RDS m DBSnapshot
deleteDBSnapshot dbsid =
rdsQuery "DeleteDBSnapshot" params $
element "DBSnapshot" sinkDBSnapshot
where
params = ["DBSnapshotIdentifier" |= dbsid]
copyDBSnapshot
:: (MonadBaseControl IO m, MonadResource m)
=> Text -- ^ SourceDBSnapshotIdentifier
-> Text -- ^ TargetDBSnapshotIdentifier
-> RDS m DBSnapshot
copyDBSnapshot source target =
rdsQuery "CopyDBSnapshot" params $
element "DBSnapshot" sinkDBSnapshot
where
params =
[ "SourceDBSnapshotIdentifier" |= source
, "TargetDBSnapshotIdentifier" |= target
]
| IanConnolly/aws-sdk-fork | AWS/RDS/DBSnapshot.hs | bsd-3-clause | 2,920 | 0 | 20 | 655 | 644 | 341 | 303 | 84 | 1 |
-- | Definition of a 'Reporter IO' which uses log-warper to gather logs and
-- uses the HTTP backend to send them to some server(s).
module Pos.Reporting.Production
( ProductionReporterParams (..)
, productionReporter
) where
import Universum
import Control.Exception.Safe (catchIO)
import Pos.Crypto (ProtocolMagic)
import Pos.Infra.Diffusion.Types (Diffusion)
import Pos.Infra.Reporting (Reporter (..))
import Pos.Infra.Reporting.Http (reportNode)
import Pos.Infra.Reporting.NodeInfo (extendWithNodeInfo)
import Pos.Infra.Reporting.Wlog (LoggerConfig, withWlogTempFile)
import Pos.Util.CompileInfo (CompileTimeInfo)
import Pos.Util.Trace (Severity, Trace)
data ProductionReporterParams = ProductionReporterParams
{ prpServers :: ![Text]
, prpLoggerConfig :: !LoggerConfig
, prpProtocolMagic :: !ProtocolMagic
, prpCompileTimeInfo :: !CompileTimeInfo
, prpTrace :: !(Trace IO (Severity, Text))
}
productionReporter
:: ProductionReporterParams
-> Diffusion IO -- ^ Used to get status info, not to do any network stuff.
-> Reporter IO
productionReporter params diffusion = Reporter $ \rt -> withWlogTempFile logConfig $ \mfp -> do
rt' <- extendWithNodeInfo diffusion rt
reportNode logTrace protocolMagic compileTimeInfo servers mfp rt'
`catchIO`
reportExnHandler rt'
where
servers = prpServers params
logConfig = prpLoggerConfig params
protocolMagic = prpProtocolMagic params
compileTimeInfo = prpCompileTimeInfo params
logTrace = prpTrace params
--
reportExnHandler _rt _e =
pure ()
| input-output-hk/pos-haskell-prototype | lib/src/Pos/Reporting/Production.hs | mit | 1,722 | 0 | 12 | 412 | 343 | 197 | 146 | 45 | 1 |
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
-- | Methods of reporting different unhealthy behaviour to server.
module Pos.Core.Reporting.Methods
( Reporter (..)
, noReporter
, MonadReporting (..)
-- * Report single event.
, reportError
, reportInfo
) where
import Universum
-- The cardano-report-server has been switched off and removing code that
-- depends on it makes building other projects like cardano-byron-proxy
-- easier. We leave the API here, but turn all operations into a NO-OP.
-- | Encapsulates the sending of a report, with potential for side-effects.
newtype Reporter m = Reporter
{ runReporter :: forall a . a -> m ()
}
noReporter :: Applicative m => Reporter m
noReporter = Reporter (const (pure ()))
-- | Typeclass analgoue of 'Reporter', for those who are allergic to using
-- function arguments.
class Applicative m => MonadReporting m where
report :: a -> m ()
-- | Report some general information.
reportInfo :: MonadReporting m => Text -> m ()
reportInfo = const $ pure ()
-- | Report «error», i. e. a situation when something is wrong with our
-- node, e. g. an assertion failed.
reportError :: MonadReporting m => Text -> m ()
reportError = const $ pure ()
| input-output-hk/pos-haskell-prototype | core/src/Pos/Core/Reporting/Methods.hs | mit | 1,377 | 0 | 10 | 310 | 216 | 123 | 93 | 21 | 1 |
module Case1 where
main :: Int
main =
case [2,2] of
(1:y:ys) -> y + 3
(x:xs) -> 32
| roberth/uu-helium | test/correct/Case1.hs | gpl-3.0 | 108 | 0 | 10 | 44 | 58 | 33 | 25 | 6 | 2 |
module GameServerSpec where
import Control.Exception (bracket)
import Data.String (fromString)
import GameServer
import GameServer.Types
import Network.HTTP.Simple
import Network.HTTP.Types
import Test.Hspec
import GameServer.Log
withServer :: (Server -> IO c) -> IO c
withServer =
bracket (startServer fakeLogger (ServerConfiguration 0 [])) stopServer
spec :: Spec
spec = around withServer $ describe "GameServer Server" $ do
it "serves index.html page" $ \ Server{serverPort} -> do
response <- httpBS (fromString $ "http://localhost:" <> show serverPort <> "/index.html")
getResponseStatus response `shouldBe` ok200
| abailly/hsgames | game-server/test/GameServerSpec.hs | apache-2.0 | 726 | 0 | 17 | 184 | 189 | 100 | 89 | -1 | -1 |
{-# LANGUAGE Rank2Types, FunctionalDependencies, TemplateHaskell, GeneralizedNewtypeDeriving #-}
module SecondTransfer.TLS.Types (
FinishRequest (..)
-- , ProtocolSelector
, TLSContext (..)
, ConnectionId (..)
, ConnectionEvent (..)
, ConnectionCallbacks (..)
, ConnectionTransformCallback
, LogCallback
, ServiceIsClosingCallback
, logEvents_CoCa
, blanketPlainTextIO_CoCa
, serviceIsClosing_CoCa
, defaultConnectionCallbacks
, TLSSessionStorage (..)
) where
import Control.Lens
import qualified Data.ByteString as B
import Data.Int (Int64)
import qualified Network.Socket as NS(SockAddr)
import SecondTransfer.MainLoop.Protocol
import SecondTransfer.IOCallbacks.Types (
TLSServerIO,
IOChannels,
IOCallbacks,
ConnectionData,
ConnectionId (..)
)
import SecondTransfer.IOCallbacks.WrapSocket
import SecondTransfer.TLS.SessionStorage
-- | Singleton type. Used in conjunction with an `MVar`. If the MVar is full,
-- the fuction `tlsServeWithALPNAndFinishOnRequest` knows that it should finish
-- at its earliest convenience and call the `CloseAction` for any open sessions.
data FinishRequest = FinishRequest
-- type ProtocolSelector = [B.ByteString] -> IO (Maybe Int)
-- | Class to have different kinds of TLS backends. Included here and enabled through 'enable-botan'
-- is support for using Botan as a backend. HTTP/2 requires TLS 1.2 and ALPN, so older versions
-- of many TLS libraries are not suitable.
--
--
class IOChannels session => TLSContext ctx session | ctx -> session, session -> ctx where
newTLSContextFromMemory :: B.ByteString -> B.ByteString -> HttpProtocolVersion -> IO ctx
-- ^ /newTLSContextFromMemory cert_data key_data protocol_selector/ creates a new context, provided
-- certificate data. The certificate data must be in X509 format. The private key should be in PKCS8 format
-- /without/ password.
newTLSContextFromCertFileNames :: B.ByteString -> B.ByteString -> HttpProtocolVersion -> IO ctx -- ^ newTLSContextFromMemory cert_filename key_filename protocol_selector
-- ^ Same as before, but using filename instead of certificates loaded into memory.
unencryptTLSServerIO :: forall cipherio . TLSServerIO cipherio => ctx -> cipherio -> IO session
-- ^ Returns the protocoll finally selected for a session.
getSelectedProtocol :: session -> IO HttpProtocolVersion
-- ^ Some TLS implementations can use session resumption. This returns true if the
-- enabling is successfull
enableSessionResumption :: forall a . TLSSessionStorage a => ctx -> a -> IO Bool
enableSessionResumption _ _ = return False
-- ^ Says if a session was resumed. For backends without support for session resumption,
-- this always returns False. Notice that this call may block if the information
-- about the session's resumption status is not yet in memory.
sessionWasResumed :: session -> IO Bool
sessionWasResumed _ = return False
-- | Connection events
data ConnectionEvent =
Established_CoEv NS.SockAddr ConnectionId Int64 -- ^ New connection. The second member says how many live connections are now
| ALPNFailed_CoEv ConnectionId -- ^ An ALPN negotiation failed
| Ended_CoEv ConnectionId -- ^ A connection ended.
| TooManyInHandshake_CoEv NS.SockAddr -- ^ Somebody was opening too many TCP connections without
-- finishing the TLS handshake, and therefore we are
-- dropping connections from that client.
| TLSHandshakeTimeOut_CoEv NS.SockAddr -- ^ When I can't finish the handshake
| AcceptError_CoEv AcceptErrorCondition -- ^. A condition
-- | See the docs below
type LogCallback = ConnectionEvent -> IO ()
-- | See below
type ConnectionTransformCallback = ConnectionData -> IOCallbacks -> IO IOCallbacks
-- | The service is closing, stop accepting connections
type ServiceIsClosingCallback = IO Bool
-- | Callbacks used by client applications to get notified about interesting
-- events happening at a connection level, or to get asked about things
-- (e.g, about if it is proper to accept a connection). These are used from CoreServer
data ConnectionCallbacks = ConnectionCallbacks {
-- | Invoked after the connection is accepted, and after it is finished.
_logEvents_CoCa :: Maybe LogCallback
-- | Function to transform the plain-text IOCallbacks when a connection is
-- accepted. Handy for implementing metrics, or for slowing things down.
, _blanketPlainTextIO_CoCa :: Maybe ConnectionTransformCallback
-- | Invoked before accepting a new connection. If False, the connection
-- is accepted. If True, the connection is rejected, the socket is
-- closed and the thread finished
, _serviceIsClosing_CoCa :: Maybe ServiceIsClosingCallback
}
makeLenses ''ConnectionCallbacks
-- | Default connections callback. Empty
defaultConnectionCallbacks :: ConnectionCallbacks
defaultConnectionCallbacks = ConnectionCallbacks {
_logEvents_CoCa = Nothing
, _blanketPlainTextIO_CoCa = Nothing
, _serviceIsClosing_CoCa = Nothing
}
| shimmercat/second-transfer | hs-src/SecondTransfer/TLS/Types.hs | bsd-3-clause | 6,414 | 0 | 11 | 2,251 | 544 | 332 | 212 | -1 | -1 |
module Language.Haskell.Stylish.Tests.Util
( testStep
) where
--------------------------------------------------------------------------------
import Language.Haskell.Stylish.Parse
import Language.Haskell.Stylish.Step
--------------------------------------------------------------------------------
testStep :: Step -> String -> String
testStep step str = case parseModule [] Nothing str of
Left err -> error err
Right module' -> unlines $ stepFilter step ls module'
where
ls = lines str
| silkapp/stylish-haskell | tests/Language/Haskell/Stylish/Tests/Util.hs | bsd-3-clause | 539 | 0 | 9 | 99 | 108 | 59 | 49 | 9 | 2 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE RankNTypes #-}
module Optical.Each where
import Control.Lens -- hiding (coerce)
-- import Control.Lens.Internal
-- import Data.Profunctor.Unsafe
-- import Data.Monoid
import qualified Data.Sequence as S
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import Data.Text.Lens
import Data.Word
import qualified Data.ByteString as BS
import Data.ByteString.Lens
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Lazy.Lens as LBS
import qualified Data.Map.Strict as M
import qualified Data.IntMap.Strict as IM
import qualified Data.Vector as B
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Storable as S
import qualified Data.Vector.Primitive as P
import qualified Data.HashMap.Strict as HM
import Data.Vector.Generic.Lens
import Data.Int
import Data.Hashable
import Data.Tree
-- import Control.Applicative.Backwards
-- These aren't proper "Traversals" in the they don't satisfy the
-- traversal laws. But I see the 'Each' class as a convient class for
-- overloading the 'each' name.
-- instance Each IntSet.IntSet IntSet.IntSet Int Int where
-- each f = IntSet.fromList . traverse f . IntSet.toList
-- instance (Ord a, Ord b) => Each Set.Set Set.Set a b where
-- each f = IntSet.fromList . traverse f . IntSet.toList
-- instance (Hashable a, Eq a, Hashable b, Eq b) => Each HashSet.HashSet HashSet.HashSet a b where
-- each f = IntSet.fromList . traverse f . IntSet.toList
-- | Like 'traverse_' but for 'Each'.
each_ :: (Applicative f, Each s s b b) => (b -> f r) -> s -> f ()
each_ = traverseOf_ each
class Each s t a b => EachWithIndex s t a b where
ieach :: IndexedTraversal (Index s) s t a b
instance EachWithIndex (B.Vector a) (B.Vector b) a b where
ieach = vectorTraverse
{-# INLINE ieach #-}
instance (U.Unbox a, U.Unbox b) => EachWithIndex (U.Vector a) (U.Vector b) a b where
ieach = vectorTraverse
{-# INLINE ieach #-}
instance (S.Storable a, S.Storable b) => EachWithIndex (S.Vector a) (S.Vector b) a b where
ieach = vectorTraverse
{-# INLINE ieach #-}
instance (P.Prim a, P.Prim b) => EachWithIndex (P.Vector a) (P.Vector b) a b where
ieach = vectorTraverse
{-# INLINE ieach #-}
instance EachWithIndex (S.Seq a) (S.Seq b) a b where
ieach = traversed
{-# INLINE ieach #-}
instance EachWithIndex [a] [b] a b where
ieach = traversed
{-# INLINE ieach #-}
instance (a ~ Word8, b ~ Word8) => EachWithIndex BS.ByteString BS.ByteString a b where
ieach = bytes
{-# INLINE ieach #-}
instance (a ~ Word8, b ~ Word8) => EachWithIndex LBS.ByteString LBS.ByteString a b where
ieach = LBS.bytes
{-# INLINE ieach #-}
instance (a ~ Char, b ~ Char) => EachWithIndex T.Text T.Text a b where
ieach = text
{-# INLINE ieach #-}
instance (a ~ Char, b ~ Char) => EachWithIndex LT.Text LT.Text a b where
ieach = reindexed (fromIntegral :: Int -> Int64) text
{-# INLINE ieach #-}
instance EachWithIndex (M.Map k a) (M.Map k b) a b where
ieach = itraversed
{-# INLINE ieach #-}
instance EachWithIndex (IM.IntMap a) (IM.IntMap b) a b where
ieach = itraversed
{-# INLINE ieach #-}
instance (Eq k, Hashable k) => EachWithIndex (HM.HashMap k a) (HM.HashMap k b) a b where
ieach = itraversed
{-# INLINE ieach #-}
instance EachWithIndex (Tree a) (Tree b) a b where
ieach = itraversed
{-# INLINE ieach #-}
-- | Like 'itraverse_' but for 'EachWithIndex'.
ieach_ :: (Applicative f, EachWithIndex s s b b) => (Index s -> b -> f r) -> s -> f ()
ieach_ = itraverseOf_ ieach
{-# INLINE ieach_ #-}
| cchalmers/optical | src/Optical/Each.hs | bsd-3-clause | 3,883 | 0 | 10 | 689 | 978 | 560 | 418 | 82 | 1 |
{-# LANGUAGE ViewPatterns #-}
-- | Main entry point.
module Main where
import Ircbrowse.Config
import Ircbrowse.Model.Migrations
import Ircbrowse.Server
import Ircbrowse.Types
import Ircbrowse.Model.Data
import Ircbrowse.Import
import Snap.App
import Snap.App.Cache
import Snap.App.Migrate
import System.Environment
-- | Main entry point.
main :: IO ()
main = do
cpath:action <- getArgs
config <- getConfig cpath
pool <- newPool (configPostgres config)
let db = runDB () config pool
case foldr const "" action of
"complete-import" ->
importRecent False config pool
"fast-import" ->
importRecent True config pool
"generate-data" -> do
db $ migrate False versions
db $ generateData
clearCache config
_ -> do
db $ migrate False versions
runServer config pool
| plow-technologies/ircbrowse | src/Main.hs | bsd-3-clause | 828 | 0 | 13 | 177 | 228 | 114 | 114 | 30 | 4 |
module Main where
import Control.Monad
import Language.Haskell.HLint (hlint)
import System.Directory
import System.Exit (exitFailure, exitSuccess)
import System.FilePath
import System.FilePath.Find
main :: IO ()
main = do
pwd <- getCurrentDirectory
let runHlint f = hlint $ f:
[ "--ignore=Redundant do"
, "--ignore=Use camelCase"
, "--ignore=Redundant $"
, "--ignore=Use &&"
, "--ignore=Use &&&"
, "--ignore=Use const"
, "--ignore=Use >=>"
, "--ignore=Use ."
, "--ignore=Use unless"
, "--ignore=Reduce duplication"
, "--cpp-define=USE_TEMPLATE_HASKELL"
, "--cpp-define=DEBUG"
, "--ignore=Use tuple-section"
]
recurseInto = and <$> sequence
[ fileType ==? Directory
, fileName /=? ".git"
]
matchFile = and <$> sequence
[ extension ==? ".hs"
]
files <- find recurseInto matchFile (pwd </> "src") --TODO: Someday fix all hints in tests, etc.
ideas <- fmap concat $ forM files $ \f -> do
putStr $ "linting file " ++ drop (length pwd + 1) f ++ "... "
runHlint f
if null ideas then exitSuccess else exitFailure
| reflex-frp/reflex | test/hlint.hs | bsd-3-clause | 1,189 | 0 | 17 | 332 | 273 | 147 | 126 | 34 | 2 |
module Tinc.GhcPkgSpec (spec) where
import Control.Monad
import System.Environment
import Helper
import Tinc.Facts
import Tinc.GhcPkg
import Tinc.Package
globalPackages :: [String]
globalPackages = [
"array"
, "base"
, "binary"
, "bytestring"
, "Cabal"
, "containers"
, "deepseq"
, "directory"
, "filepath"
, "ghc"
, "ghc-boot"
, "ghc-boot-th"
, "ghci"
, "ghc-prim"
, "haskeline"
, "hpc"
, "integer-gmp"
, "pretty"
, "process"
, "rts"
, "template-haskell"
, "terminfo"
, "time"
, "transformers"
, "unix"
, "xhtml"
, "ghc-compact"
, "mtl"
, "parsec"
, "stm"
, "text"
]
spec :: Spec
spec = do
describe "listGlobalPackages" $ before_ (getExecutablePath >>= useNix >>= (`when` pending)) $ do
it "lists packages from global package database" $ do
packages <- listGlobalPackages
map simplePackageName packages `shouldMatchList` globalPackages
| sol/tinc | test/Tinc/GhcPkgSpec.hs | mit | 985 | 0 | 14 | 267 | 220 | 132 | 88 | 46 | 1 |
module {{moduleName}}.Swallow (swallow) where
swallow :: String -> String -> String
swallow prefix suffix = prefix ++ suffix
| mankyKitty/holy-haskell-project-starter | scaffold/src/ModuleName/Swallow.hs | mit | 126 | 1 | 6 | 19 | 41 | 24 | 17 | -1 | -1 |
#if __GLASGOW_HASKELL__ >= 701
{-# LANGUAGE Trustworthy #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Graphics.Win32.GDI.Graphics2D
-- Copyright : (c) Alastair Reid, 1997-2003
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : Esa Ilari Vuokko <[email protected]>
-- Stability : provisional
-- Portability : portable
--
-- 2D graphics operations
--
-----------------------------------------------------------------------------
module Graphics.Win32.GDI.Graphics2D
where
import System.Win32.Types
import Graphics.Win32.GDI.Types
import Foreign
#include "windows_cconv.h"
----------------------------------------------------------------
-- Lines and Curves
----------------------------------------------------------------
moveToEx :: HDC -> Int32 -> Int32 -> IO POINT
moveToEx dc x y =
allocaPOINT $ \ p_point -> do
failIfFalse_ "MoveToEx" $ c_MoveToEx dc x y p_point
peekPOINT p_point
foreign import WINDOWS_CCONV unsafe "windows.h MoveToEx"
c_MoveToEx :: HDC -> Int32 -> Int32 -> Ptr POINT -> IO Bool
lineTo :: HDC -> Int32 -> Int32 -> IO ()
lineTo dc x y =
failIfFalse_ "LineTo" $ c_LineTo dc x y
foreign import WINDOWS_CCONV unsafe "windows.h LineTo"
c_LineTo :: HDC -> Int32 -> Int32 -> IO Bool
polyline :: HDC -> [POINT] -> IO ()
polyline dc points =
withPOINTArray points $ \ pount_array npoints ->
failIfFalse_ "Polyline" $ c_Polyline dc pount_array npoints
foreign import WINDOWS_CCONV unsafe "windows.h Polyline"
c_Polyline :: HDC -> Ptr POINT -> Int -> IO Bool
polylineTo :: HDC -> [POINT] -> IO ()
polylineTo dc points =
withPOINTArray points $ \ pount_array npoints ->
failIfFalse_ "PolylineTo" $ c_PolylineTo dc pount_array npoints
foreign import WINDOWS_CCONV unsafe "windows.h PolylineTo"
c_PolylineTo :: HDC -> Ptr POINT -> Int -> IO Bool
polygon :: HDC -> [POINT] -> IO ()
polygon dc points =
withPOINTArray points $ \ pount_array npoints ->
failIfFalse_ "Polygon" $ c_Polygon dc pount_array npoints
foreign import WINDOWS_CCONV unsafe "windows.h Polygon"
c_Polygon :: HDC -> Ptr POINT -> Int -> IO Bool
polyBezier :: HDC -> [POINT] -> IO ()
polyBezier dc points =
withPOINTArray points $ \ pount_array npoints ->
failIfFalse_ "PolyBezier" $ c_PolyBezier dc pount_array npoints
foreign import WINDOWS_CCONV unsafe "windows.h PolyBezier"
c_PolyBezier :: HDC -> Ptr POINT -> Int -> IO Bool
polyBezierTo :: HDC -> [POINT] -> IO ()
polyBezierTo dc points =
withPOINTArray points $ \ pount_array npoints ->
failIfFalse_ "PolyBezierTo" $ c_PolyBezierTo dc pount_array npoints
foreign import WINDOWS_CCONV unsafe "windows.h PolyBezierTo"
c_PolyBezierTo :: HDC -> Ptr POINT -> Int -> IO Bool
arc :: HDC -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> IO ()
arc dc left top right bottom x1 y1 x2 y2 =
failIfFalse_ "Arc" $ c_Arc dc left top right bottom x1 y1 x2 y2
foreign import WINDOWS_CCONV unsafe "windows.h Arc"
c_Arc :: HDC -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> IO Bool
arcTo :: HDC -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> IO ()
arcTo dc left top right bottom x1 y1 x2 y2 =
failIfFalse_ "ArcTo" $ c_ArcTo dc left top right bottom x1 y1 x2 y2
foreign import WINDOWS_CCONV unsafe "windows.h ArcTo"
c_ArcTo :: HDC -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> IO Bool
angleArc :: HDC -> Int32 -> Int32 -> WORD -> Float -> Float -> IO ()
angleArc dc x y r start sweep =
failIfFalse_ "AngleArc" $ c_AngleArc dc x y r start sweep
foreign import WINDOWS_CCONV unsafe "windows.h AngleArc"
c_AngleArc :: HDC -> Int32 -> Int32 -> WORD -> Float -> Float -> IO Bool
----------------------------------------------------------------
-- Filled Shapes
----------------------------------------------------------------
-- ToDo: We ought to be able to specify a colour instead of the
-- Brush by adding 1 to colour number.
fillRect :: HDC -> RECT -> HBRUSH -> IO ()
fillRect dc rect brush =
withRECT rect $ \ c_rect ->
failIfFalse_ "FillRect" $ c_FillRect dc c_rect brush
foreign import WINDOWS_CCONV unsafe "windows.h FillRect"
c_FillRect :: HDC -> Ptr RECT -> HBRUSH -> IO Bool
frameRect :: HDC -> RECT -> HBRUSH -> IO ()
frameRect dc rect brush =
withRECT rect $ \ c_rect ->
failIfFalse_ "FrameRect" $ c_FrameRect dc c_rect brush
foreign import WINDOWS_CCONV unsafe "windows.h FrameRect"
c_FrameRect :: HDC -> Ptr RECT -> HBRUSH -> IO Bool
invertRect :: HDC -> RECT -> IO ()
invertRect dc rect =
withRECT rect $ \ c_rect ->
failIfFalse_ "InvertRect" $ c_InvertRect dc c_rect
foreign import WINDOWS_CCONV unsafe "windows.h InvertRect"
c_InvertRect :: HDC -> Ptr RECT -> IO Bool
rectangle :: HDC -> Int32 -> Int32 -> Int32 -> Int32 -> IO ()
rectangle dc left top right bottom =
failIfFalse_ "Rectangle" $ c_Rectangle dc left top right bottom
foreign import WINDOWS_CCONV unsafe "windows.h Rectangle"
c_Rectangle :: HDC -> Int32 -> Int32 -> Int32 -> Int32 -> IO Bool
roundRect :: HDC -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> IO ()
roundRect dc left top right bottom w h =
failIfFalse_ "RoundRect" $ c_RoundRect dc left top right bottom w h
foreign import WINDOWS_CCONV unsafe "windows.h RoundRect"
c_RoundRect :: HDC -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> IO Bool
ellipse :: HDC -> Int32 -> Int32 -> Int32 -> Int32 -> IO ()
ellipse dc left top right bottom =
failIfFalse_ "Ellipse" $ c_Ellipse dc left top right bottom
foreign import WINDOWS_CCONV unsafe "windows.h Ellipse"
c_Ellipse :: HDC -> Int32 -> Int32 -> Int32 -> Int32 -> IO Bool
chord :: HDC -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> IO ()
chord dc left top right bottom x1 y1 x2 y2 =
failIfFalse_ "Chord" $ c_Chord dc left top right bottom x1 y1 x2 y2
foreign import WINDOWS_CCONV unsafe "windows.h Chord"
c_Chord :: HDC -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> IO Bool
pie :: HDC -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> IO ()
pie dc left top right bottom x1 y1 x2 y2 =
failIfFalse_ "Pie" $ c_Pie dc left top right bottom x1 y1 x2 y2
foreign import WINDOWS_CCONV unsafe "windows.h Pie"
c_Pie :: HDC -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> Int32 -> IO Bool
----------------------------------------------------------------
-- Bitmaps
----------------------------------------------------------------
bitBlt :: HDC -> INT -> INT -> INT -> INT -> HDC -> INT -> INT -> RasterOp3 -> IO ()
bitBlt dcDest xDest yDest w h dcSrc xSrc ySrc rop =
failIfFalse_ "BitBlt" $ c_BitBlt dcDest xDest yDest w h dcSrc xSrc ySrc rop
foreign import WINDOWS_CCONV unsafe "windows.h BitBlt"
c_BitBlt :: HDC -> INT -> INT -> INT -> INT -> HDC -> INT -> INT -> RasterOp3 -> IO Bool
maskBlt :: HDC -> INT -> INT -> INT -> INT -> HDC -> INT -> INT -> HBITMAP -> INT -> INT -> RasterOp4 -> IO ()
maskBlt dcDest xDest yDest w h dcSrc xSrc ySrc bm xMask yMask rop =
failIfFalse_ "MaskBlt" $
c_MaskBlt dcDest xDest yDest w h dcSrc xSrc ySrc bm xMask yMask rop
foreign import WINDOWS_CCONV unsafe "windows.h MaskBlt"
c_MaskBlt :: HDC -> INT -> INT -> INT -> INT -> HDC -> INT -> INT -> HBITMAP -> INT -> INT -> RasterOp4 -> IO Bool
stretchBlt :: HDC -> INT -> INT -> INT -> INT -> HDC -> INT -> INT -> INT -> INT -> RasterOp3 -> IO ()
stretchBlt dcDest xDest yDest wDest hDest hdcSrc xSrc ySrc wSrc hSrc rop =
failIfFalse_ "StretchBlt" $
c_StretchBlt dcDest xDest yDest wDest hDest hdcSrc xSrc ySrc wSrc hSrc rop
foreign import WINDOWS_CCONV unsafe "windows.h StretchBlt"
c_StretchBlt :: HDC -> INT -> INT -> INT -> INT -> HDC -> INT -> INT -> INT -> INT -> RasterOp3 -> IO Bool
-- We deviate slightly from the Win32 interface
-- %C typedef POINT ThreePts[3];
-- Old 2nd line:
-- %start POINT vertices[3];
plgBlt :: HDC -> POINT -> POINT -> POINT -> HDC -> INT -> INT -> INT -> INT -> MbHBITMAP -> INT -> INT -> IO ()
plgBlt hdDest p1 p2 p3 hdSrc x y w h mb_bm xMask yMask =
withPOINTArray [p1,p2,p3] $ \ vertices _ ->
failIfFalse_ "PlgBlt" $
c_PlgBlt hdDest vertices hdSrc x y w h (maybePtr mb_bm) xMask yMask
foreign import WINDOWS_CCONV unsafe "windows.h PlgBlt"
c_PlgBlt :: HDC -> Ptr POINT -> HDC -> INT -> INT -> INT -> INT -> HBITMAP -> INT -> INT -> IO Bool
----------------------------------------------------------------
-- Fonts and Text
----------------------------------------------------------------
textOut :: HDC -> INT -> INT -> String -> IO ()
textOut dc x y str =
withTStringLen str $ \ (c_str, len) ->
failIfFalse_ "TextOut" $ c_TextOut dc x y c_str len
foreign import WINDOWS_CCONV unsafe "windows.h TextOutW"
c_TextOut :: HDC -> INT -> INT -> LPCTSTR -> Int -> IO Bool
-- missing TabbedTextOut from WinFonts.ss; GSL ???
getTextExtentPoint32 :: HDC -> String -> IO SIZE
getTextExtentPoint32 dc str =
withTStringLen str $ \ (c_str, len) ->
allocaSIZE $ \ p_size -> do
failIfFalse_ "GetTextExtentPoint32" $
c_GetTextExtentPoint32 dc c_str len p_size
peekSIZE p_size
foreign import WINDOWS_CCONV unsafe "windows.h GetTextExtentPoint32W"
c_GetTextExtentPoint32 :: HDC -> LPCTSTR -> Int -> Ptr SIZE -> IO Bool
-- missing getTabbedTextExtent from WinFonts.ss; GSL ???
-- missing SetTextJustification from WinFonts.ss; GSL ???
-- missing a whole family of techandfamily functionality; GSL ???
-- missing DrawText and DrawTextFormat in WinFonts.ss; GSL ???
----------------------------------------------------------------
-- End
----------------------------------------------------------------
| jwiegley/ghc-release | libraries/Win32/Graphics/Win32/GDI/Graphics2D.hs | gpl-3.0 | 9,705 | 419 | 10 | 1,776 | 2,889 | 1,483 | 1,406 | -1 | -1 |
module Data.Tree.Extra where
import Prelude (Ordering, (.), map)
import Data.List (sortBy)
import Data.Tree (Forest, Tree(..))
sortTreeBy :: (Tree a -> Tree a -> Ordering) -> Tree a -> Tree a
sortTreeBy f (Node x xs) = Node x (sortForestBy f xs)
sortForestBy :: (Tree a -> Tree a -> Ordering) -> Forest a -> Forest a
sortForestBy f = sortBy f . map (sortTreeBy f)
singleton :: a -> Tree a
singleton x = Node x []
| chreekat/snowdrift | Data/Tree/Extra.hs | agpl-3.0 | 418 | 0 | 9 | 82 | 204 | 106 | 98 | 10 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE AutoDeriveTypeable #-}
{-# LANGUAGE DeriveTraversable #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Functor.Identity
-- Copyright : (c) Andy Gill 2001,
-- (c) Oregon Graduate Institute of Science and Technology 2001
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- The identity functor and monad.
--
-- This trivial type constructor serves two purposes:
--
-- * It can be used with functions parameterized by functor or monad classes.
--
-- * It can be used as a base monad to which a series of monad
-- transformers may be applied to construct a composite monad.
-- Most monad transformer modules include the special case of
-- applying the transformer to 'Identity'. For example, @State s@
-- is an abbreviation for @StateT s 'Identity'@.
--
-- @since 4.8.0.0
-----------------------------------------------------------------------------
module Data.Functor.Identity (
Identity(..),
) where
import Control.Monad.Fix
import Data.Coerce
import Data.Foldable
-- | Identity functor and monad. (a non-strict monad)
--
-- @since 4.8.0.0
newtype Identity a = Identity { runIdentity :: a }
deriving (Eq, Ord, Traversable)
-- | This instance would be equivalent to the derived instances of the
-- 'Identity' newtype if the 'runIdentity' field were removed
instance (Read a) => Read (Identity a) where
readsPrec d = readParen (d > 10) $ \ r ->
[(Identity x,t) | ("Identity",s) <- lex r, (x,t) <- readsPrec 11 s]
-- | This instance would be equivalent to the derived instances of the
-- 'Identity' newtype if the 'runIdentity' field were removed
instance (Show a) => Show (Identity a) where
showsPrec d (Identity x) = showParen (d > 10) $
showString "Identity " . showsPrec 11 x
-- ---------------------------------------------------------------------------
-- Identity instances for Functor and Monad
instance Foldable Identity where
foldMap = coerce
elem = (. runIdentity) #. (==)
foldl = coerce
foldl' = coerce
foldl1 _ = runIdentity
foldr f z (Identity x) = f x z
foldr' = foldr
foldr1 _ = runIdentity
length _ = 1
maximum = runIdentity
minimum = runIdentity
null _ = False
product = runIdentity
sum = runIdentity
toList (Identity x) = [x]
instance Functor Identity where
fmap = coerce
instance Applicative Identity where
pure = Identity
(<*>) = coerce
instance Monad Identity where
return = Identity
m >>= k = k (runIdentity m)
instance MonadFix Identity where
mfix f = Identity (fix (runIdentity . f))
-- | Internal (non-exported) 'Coercible' helper for 'elem'
--
-- See Note [Function coercion] in "Data.Foldable" for more details.
(#.) :: Coercible b c => (b -> c) -> (a -> b) -> a -> c
(#.) _f = coerce
| green-haskell/ghc | libraries/base/Data/Functor/Identity.hs | bsd-3-clause | 3,199 | 0 | 11 | 843 | 550 | 318 | 232 | 44 | 1 |
{-# LANGUAGE DeriveGeneric, StandaloneDeriving, BangPatterns #-}
module Main where
import qualified Data.ByteString.Lazy as L
import Distribution.PackageDescription
import Criterion.Main
import qualified Data.Binary as Binary
import Data.Binary.Get (Get)
import qualified Data.Binary.Get as Binary
import GenericsBenchCache
main :: IO ()
main = benchmark =<< readPackageDescriptionCache 100
benchmark :: [PackageDescription] -> IO ()
benchmark pds = do
let lbs = encode pds
!_ = L.length lbs
str = show pds
!_ = length str
defaultMain [
bench "encode" (nf encode pds)
, bench "decode" (nf decode lbs)
, bench "decode null" (nf decodeNull lbs)
, bgroup "embarrassment" [
bench "read" (nf readPackageDescription str)
, bench "show" (nf show pds)
]
]
encode :: [PackageDescription] -> L.ByteString
encode = Binary.encode
decode :: L.ByteString -> Int
decode = length . (Binary.decode :: L.ByteString -> [PackageDescription])
decodeNull :: L.ByteString -> ()
decodeNull =
Binary.runGet $ do
n <- Binary.get :: Get Int
go n
where
go 0 = return ()
go i = do
x <- Binary.get :: Get PackageDescription
x `seq` go (i-1)
readPackageDescription :: String -> Int
readPackageDescription = length . (read :: String -> [PackageDescription])
| x456/binary | benchmarks/GenericsBench.hs | bsd-3-clause | 1,439 | 0 | 13 | 394 | 429 | 228 | 201 | 39 | 2 |
module Stackage.Build
( build
, defaultBuildSettings
, BuildSettings (..)
) where
import Control.Monad (unless)
import Prelude hiding (pi)
import Stackage.CheckCabalVersion (checkCabalVersion)
import Stackage.Config
import Stackage.InstallInfo
import Stackage.ModuleNameConflict
import Stackage.Types
import Stackage.Util
import System.Exit (ExitCode (ExitSuccess), exitWith)
import System.IO (BufferMode (NoBuffering),
IOMode (WriteMode), hPutStrLn,
hSetBuffering, withBinaryFile)
import qualified System.IO.UTF8
import System.Process (rawSystem, runProcess,
waitForProcess)
import qualified Data.ByteString.Lazy.Char8 as L8
defaultBuildSettings :: Maybe Int -- ^ argument to -j
-> GhcMajorVersion
-> BuildSettings
defaultBuildSettings cores version = BuildSettings
{ sandboxRoot = "sandbox"
, extraArgs = \bs -> "-fnetwork23" : "-fhttps" :
case bs of
BSTest -> []
_ ->
case cores of
Nothing -> ["-j"]
Just 1 -> []
Just j -> ["-j" ++ show j]
, testWorkerThreads = 4
, buildDocs = True
, tarballDir = "patching/tarballs"
, cabalFileDir = Nothing
, underlayPackageDirs = []
}
build :: BuildSettings -> BuildPlan -> IO ()
build settings' bp = do
libVersion <- checkCabalVersion
putStrLn "Wiping out old sandbox folder"
rm_r $ sandboxRoot settings'
rm_r "logs"
settings <- fixBuildSettings settings'
putStrLn "Creating new package database"
ec1 <- rawSystem "ghc-pkg" ["init", packageDir settings]
unless (ec1 == ExitSuccess) $ do
putStrLn "Unable to create package database via ghc-pkg init"
exitWith ec1
menv <- fmap Just $ getModifiedEnv settings
let runCabal args handle = runProcess "cabal" args Nothing menv Nothing (Just handle) (Just handle)
-- First install build tools so they can be used below.
let installBuildTool tool = do
let toolsDir = packageDir settings ++ "-tools"
rm_r toolsDir
ecInit <- rawSystem "ghc-pkg" ["init", toolsDir]
unless (ecInit == ExitSuccess) $ do
putStrLn "Unable to create package database via ghc-pkg init"
exitWith ecInit
putStrLn $ "Installing build tool: " ++ tool
ec <- withBinaryFile "build-tools.log" WriteMode $ \handle -> do
hSetBuffering handle NoBuffering
let args = addCabalArgs settings BSTools
$ "install"
: ("--cabal-lib-version=" ++ libVersion)
: "--build-log=logs-tools/$pkg.log"
: [tool]
hPutStrLn handle ("cabal " ++ unwords (map (\s -> "'" ++ s ++ "'") args))
ph <- runCabal args handle
waitForProcess ph
unless (ec == ExitSuccess) $ do
putStrLn $ concat
[ "Building of "
, tool
, " failed, please see build-tools.log"
]
exitWith ec
putStrLn $ tool ++ " built"
rm_r toolsDir
mapM_ installBuildTool $ bpTools bp
putStrLn "Beginning Stackage build"
ph <- withBinaryFile "build.log" WriteMode $ \handle -> do
packageList <- mapM (replaceTarball $ tarballDir settings) $ bpPackageList bp
let args = addCabalArgs settings BSBuild
$ "install"
: ("--cabal-lib-version=" ++ libVersion)
: "--build-log=logs/$pkg.log"
: "--max-backjumps=-1"
: "--reorder-goals"
: packageList
hPutStrLn handle ("cabal " ++ unwords (map (\s -> "'" ++ s ++ "'") args))
runCabal args handle
ec <- waitForProcess ph
unless (ec == ExitSuccess) $ do
putStrLn "Build failed, please see build.log"
L8.readFile "build.log" >>= L8.putStr
exitWith ec
putStrLn "Build completed successfully, checking for module name conflicts"
conflicts <- getModuleNameConflicts $ packageDir settings
System.IO.UTF8.writeFile "module-name-conflicts.txt"
$ renderModuleNameConflicts conflicts
| Tarrasch/stackage | Stackage/Build.hs | mit | 4,615 | 0 | 26 | 1,688 | 1,016 | 503 | 513 | 100 | 4 |
module Main where
import Files
main = do
cFiles <- allCFiles
putStrLn $ "C files:" ++ show cFiles
| juhp/stack | test/integration/tests/mutable-deps/files/app/Main.hs | bsd-3-clause | 104 | 0 | 8 | 24 | 33 | 17 | 16 | 5 | 1 |
{-# LANGUAGE StandaloneKindSignatures #-}
{-# LANGUAGE GADTs, PolyKinds, ExplicitForAll #-}
module SAKS_005 where
import Data.Kind (Type, Constraint)
type TypeRep :: forall k. k -> Type
data TypeRep a where
TyInt :: TypeRep Int
TyMaybe :: TypeRep Maybe
TyApp :: TypeRep a -> TypeRep b -> TypeRep (a b)
| sdiehl/ghc | testsuite/tests/saks/should_compile/saks005.hs | bsd-3-clause | 315 | 0 | 10 | 61 | 83 | 47 | 36 | -1 | -1 |
-- BANNERSTART
-- - Copyright 2006-2008, Galois, Inc.
-- - This software is distributed under a standard, three-clause BSD license.
-- - Please see the file LICENSE, distributed with this software, for specific
-- - terms and conditions.
-- Author: Adam Wick <[email protected]>
-- BANNEREND
--
import Control.Concurrent
import Control.Monad
import Hypervisor.Console
import Hypervisor.Debug
import System.Exit
main :: IO ()
main = do
forkIO tickThread
exitThread
tickThread :: IO ()
tickThread = do
writeDebugConsole "Tick!\n"
threadDelay 1000000
exitThread :: IO ()
exitThread = do
con <- initXenConsole
writeDebugConsole "Entering exitThread\n"
threadDelay 1000000
writeDebugConsole "Writing console message\n"
writeConsole con "Shutting down now!\n"
threadDelay 1000
writeDebugConsole "Calling shutdown\n"
exitSuccess
| thumphries/HaLVM | examples/Core/ExitTest/ExitTest.hs | bsd-3-clause | 848 | 0 | 7 | 134 | 148 | 71 | 77 | 23 | 1 |
{-
Copyright (C) 2014 Jesse Rosenthal <[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 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 : Text.Pandoc.Readers.Docx.Lists
Copyright : Copyright (C) 2014 Jesse Rosenthal
License : GNU GPL, version 2 or above
Maintainer : Jesse Rosenthal <[email protected]>
Stability : alpha
Portability : portable
Functions for converting flat docx paragraphs into nested lists.
-}
module Text.Pandoc.Readers.Docx.Lists ( blocksToBullets
, blocksToDefinitions
, listParagraphDivs
) where
import Text.Pandoc.JSON
import Text.Pandoc.Generic (bottomUp)
import Text.Pandoc.Shared (trim)
import Control.Monad
import Data.List
import Data.Maybe
isListItem :: Block -> Bool
isListItem (Div (_, classes, _) _) | "list-item" `elem` classes = True
isListItem _ = False
getLevel :: Block -> Maybe Integer
getLevel (Div (_, _, kvs) _) = liftM read $ lookup "level" kvs
getLevel _ = Nothing
getLevelN :: Block -> Integer
getLevelN b = case getLevel b of
Just n -> n
Nothing -> -1
getNumId :: Block -> Maybe Integer
getNumId (Div (_, _, kvs) _) = liftM read $ lookup "num-id" kvs
getNumId _ = Nothing
getNumIdN :: Block -> Integer
getNumIdN b = case getNumId b of
Just n -> n
Nothing -> -1
getText :: Block -> Maybe String
getText (Div (_, _, kvs) _) = lookup "text" kvs
getText _ = Nothing
data ListType = Itemized | Enumerated ListAttributes
listStyleMap :: [(String, ListNumberStyle)]
listStyleMap = [("upperLetter", UpperAlpha),
("lowerLetter", LowerAlpha),
("upperRoman", UpperRoman),
("lowerRoman", LowerRoman),
("decimal", Decimal)]
listDelimMap :: [(String, ListNumberDelim)]
listDelimMap = [("%1)", OneParen),
("(%1)", TwoParens),
("%1.", Period)]
getListType :: Block -> Maybe ListType
getListType b@(Div (_, _, kvs) _) | isListItem b =
let
start = lookup "start" kvs
frmt = lookup "format" kvs
txt = lookup "text" kvs
in
case frmt of
Just "bullet" -> Just Itemized
Just f ->
case txt of
Just t -> Just $ Enumerated (
read (fromMaybe "1" start) :: Int,
fromMaybe DefaultStyle (lookup f listStyleMap),
fromMaybe DefaultDelim (lookup t listDelimMap))
Nothing -> Nothing
_ -> Nothing
getListType _ = Nothing
listParagraphDivs :: [String]
listParagraphDivs = ["ListParagraph"]
-- This is a first stab at going through and attaching meaning to list
-- paragraphs, without an item marker, following a list item. We
-- assume that these are paragraphs in the same item.
handleListParagraphs :: [Block] -> [Block]
handleListParagraphs [] = []
handleListParagraphs (
(Div attr1@(_, classes1, _) blks1) :
(Div (ident2, classes2, kvs2) blks2) :
blks
) | "list-item" `elem` classes1 &&
not ("list-item" `elem` classes2) &&
(not . null) (listParagraphDivs `intersect` classes2) =
-- We don't want to keep this indent.
let newDiv2 =
(Div (ident2, classes2, filter (\kv -> fst kv /= "indent") kvs2) blks2)
in
handleListParagraphs ((Div attr1 (blks1 ++ [newDiv2])) : blks)
handleListParagraphs (blk:blks) = blk : (handleListParagraphs blks)
separateBlocks' :: Block -> [[Block]] -> [[Block]]
separateBlocks' blk ([] : []) = [[blk]]
separateBlocks' b@(BulletList _) acc = (init acc) ++ [(last acc) ++ [b]]
separateBlocks' b@(OrderedList _ _) acc = (init acc) ++ [(last acc) ++ [b]]
-- The following is for the invisible bullet lists. This is how
-- pandoc-generated ooxml does multiparagraph item lists.
separateBlocks' b acc | liftM trim (getText b) == Just "" =
(init acc) ++ [(last acc) ++ [b]]
separateBlocks' b acc = acc ++ [[b]]
separateBlocks :: [Block] -> [[Block]]
separateBlocks blks = foldr separateBlocks' [[]] (reverse blks)
flatToBullets' :: Integer -> [Block] -> [Block]
flatToBullets' _ [] = []
flatToBullets' num xs@(b : elems)
| getLevelN b == num = b : (flatToBullets' num elems)
| otherwise =
let bNumId = getNumIdN b
bLevel = getLevelN b
(children, remaining) =
span
(\b' ->
((getLevelN b') > bLevel ||
((getLevelN b') == bLevel && (getNumIdN b') == bNumId)))
xs
in
case getListType b of
Just (Enumerated attr) ->
(OrderedList attr (separateBlocks $ flatToBullets' bLevel children)) :
(flatToBullets' num remaining)
_ ->
(BulletList (separateBlocks $ flatToBullets' bLevel children)) :
(flatToBullets' num remaining)
flatToBullets :: [Block] -> [Block]
flatToBullets elems = flatToBullets' (-1) elems
singleItemHeaderToHeader :: Block -> Block
singleItemHeaderToHeader (OrderedList _ [[h@(Header _ _ _)]]) = h
singleItemHeaderToHeader blk = blk
blocksToBullets :: [Block] -> [Block]
blocksToBullets blks =
map singleItemHeaderToHeader $
bottomUp removeListDivs $
flatToBullets $ (handleListParagraphs blks)
plainParaInlines :: Block -> [Inline]
plainParaInlines (Plain ils) = ils
plainParaInlines (Para ils) = ils
plainParaInlines _ = []
blocksToDefinitions' :: [([Inline], [[Block]])] -> [Block] -> [Block] -> [Block]
blocksToDefinitions' [] acc [] = reverse acc
blocksToDefinitions' defAcc acc [] =
reverse $ (DefinitionList (reverse defAcc)) : acc
blocksToDefinitions' defAcc acc
((Div (_, classes1, _) blks1) : (Div (ident2, classes2, kvs2) blks2) : blks)
| "DefinitionTerm" `elem` classes1 && "Definition" `elem` classes2 =
let remainingAttr2 = (ident2, delete "Definition" classes2, kvs2)
pair = case remainingAttr2 == ("", [], []) of
True -> (concatMap plainParaInlines blks1, [blks2])
False -> (concatMap plainParaInlines blks1, [[Div remainingAttr2 blks2]])
in
blocksToDefinitions' (pair : defAcc) acc blks
blocksToDefinitions' defAcc acc
((Div (ident2, classes2, kvs2) blks2) : blks)
| (not . null) defAcc && "Definition" `elem` classes2 =
let remainingAttr2 = (ident2, delete "Definition" classes2, kvs2)
defItems2 = case remainingAttr2 == ("", [], []) of
True -> blks2
False -> [Div remainingAttr2 blks2]
((defTerm, defItems):defs) = defAcc
defAcc' = case null defItems of
True -> (defTerm, [defItems2]) : defs
False -> (defTerm, init defItems ++ [last defItems ++ defItems2]) : defs
in
blocksToDefinitions' defAcc' acc blks
blocksToDefinitions' [] acc (b:blks) =
blocksToDefinitions' [] (b:acc) blks
blocksToDefinitions' defAcc acc (b:blks) =
blocksToDefinitions' [] (b : (DefinitionList (reverse defAcc)) : acc) blks
removeListDivs' :: Block -> [Block]
removeListDivs' (Div (ident, classes, kvs) blks)
| "list-item" `elem` classes =
case delete "list-item" classes of
[] -> blks
classes' -> [Div (ident, classes', kvs) $ blks]
removeListDivs' (Div (ident, classes, kvs) blks)
| not $ null $ listParagraphDivs `intersect` classes =
case classes \\ listParagraphDivs of
[] -> blks
classes' -> [Div (ident, classes', kvs) blks]
removeListDivs' blk = [blk]
removeListDivs :: [Block] -> [Block]
removeListDivs = concatMap removeListDivs'
blocksToDefinitions :: [Block] -> [Block]
blocksToDefinitions = blocksToDefinitions' [] []
| gbataille/pandoc | src/Text/Pandoc/Readers/Docx/Lists.hs | gpl-2.0 | 8,062 | 0 | 20 | 1,867 | 2,499 | 1,341 | 1,158 | 159 | 4 |
-- from Jon Hill
module ShouldFail where
buglet = [ x | (x,y) <- buglet ]
| olsner/ghc | testsuite/tests/typecheck/should_fail/tcfail033.hs | bsd-3-clause | 75 | 0 | 8 | 17 | 27 | 17 | 10 | 2 | 1 |
-- !!! printing Floats; was a bug in hbc (reported by andy)
--
main = print ((fromIntegral (42 :: Int)) :: Float)
| wxwxwwxxx/ghc | testsuite/tests/numeric/should_run/arith006.hs | bsd-3-clause | 115 | 0 | 9 | 23 | 29 | 17 | 12 | 1 | 1 |
module TestPopulation where
import Data.AEq
import Control.Monad.Bayes.Class
import Control.Monad.Bayes.Enumerator
import Control.Monad.Bayes.Sampler
import Control.Monad.Bayes.Population as Population
import Sprinkler
weightedSampleSize :: MonadSample m => Population m a -> m Int
weightedSampleSize = fmap length . runPopulation
popSize :: IO Int
popSize = sampleIOfixed $ weightedSampleSize $ spawn 5 >> sprinkler
manySize :: IO Int
manySize = sampleIOfixed $ weightedSampleSize $ spawn 5 >> sprinkler >> spawn 3
sprinkler :: MonadInfer m => m Bool
sprinkler = Sprinkler.soft
sprinklerExact :: [(Bool, Double)]
sprinklerExact = enumerate Sprinkler.soft
--all_check = (mass (Population.all id (spawn 2 >> sprinkler)) True) ~== 0.09
transCheck1 :: Bool
transCheck1 = enumerate (collapse sprinkler) ~==
sprinklerExact
transCheck2 :: Bool
transCheck2 = enumerate (collapse (spawn 2 >> sprinkler)) ~==
sprinklerExact
resampleCheck :: Int -> Bool
resampleCheck n =
(enumerate . collapse . resampleMultinomial) (spawn n >> sprinkler) ~==
sprinklerExact
popAvgCheck :: Bool
popAvgCheck = expectation f Sprinkler.soft ~== expectation id (popAvg f $ pushEvidence Sprinkler.soft) where
f True = 10
f False = 4
| adscib/monad-bayes | test/TestPopulation.hs | mit | 1,251 | 0 | 11 | 211 | 348 | 185 | 163 | 31 | 2 |
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-}
module Syntax where
import Control.Monad
import NarrowingSearch
-- -----------------------
data Blk = BIEnv [GlobHyp]
| BICtx Context
| BIForm HNFormula
| BIUnifyForm [Int] HNFormula Env
| BIUnifyType Type
| BICheckForm Type
| BIComputed
| BISimpArgs Bool -- shoud be cons (otherwise nil)
| BIFormHead FormHead
data FormHead = FHLamLam | FHLamApp | FHAppLam | FHC Cons | FHApp | FHChoice
instance Show Blk where
show (BIEnv{}) = "BIEnv"
show (BICtx{}) = "BICtx"
show (BIForm{}) = "BIForm"
show (BIUnifyForm{}) = "BIUnifyForm"
show (BIUnifyType{}) = "BIUnifyType"
show (BICheckForm{}) = "BICheckForm"
show (BIComputed{}) = "BIComputed"
data GenCost = GCStop
| GCSubProb Int GenCost
| GCFork GenCost GenCost
| GCLocalHyp
deriving Show
-- -----------------------
type MMetavar a = Metavar a Blk
type MMM a = MM a Blk
type MMB a = MB a Blk
type MPB = PB Blk
-- -----------------------
data Problem = Problem {prName :: String, prIndSets :: Int, prGlobVars :: [GlobVar], prGlobHyps :: [GlobHyp], prConjectures :: [(String, MFormula)]}
type MUId = Maybe Int
nu = Nothing
data Elr = Var Int
| Glob GlobVar
data Type = Ind Int
| Bool
| Map MType MType
type MType = MMM Type
type MetaType = MMetavar Type
data Cons = Top | Bot | And | Or | Implies | Not | Forall | Exists | Eq
deriving (Eq, Show)
-- (Lam [T _, Bind _])
-- Top []
-- Bot []
-- And [F _, F _]
-- Or [F _, F _]
-- Implies [F _, F _]
-- Not [F _]
-- Forall [T _, F _]
-- Exists [T _, F _]
-- Eq [T _, F _, F _]
-- (Choice [T _, F _])
data Formula = C MUId Cons [FormulaArg MFormula]
| App MUId Elr MArgs
| Choice MUId MType MFormula MArgs
| Lam MUId MType MFormula
type MetaFormula = MMetavar Formula
type MFormula = MMM Formula
data FormulaArg a = F a
| T MType
data Args = ArgNil
| ArgCons MFormula MArgs
type MArgs = MMM Args
data GlobVar = GlobVar {gvName :: String, gvType :: MType, gvId :: Int}
-- -----------------------
data Proof = Intro MetaIntro
| Elim MetaHyp MetaProofElim
| RAA MetaProof
type MetaProof = MMetavar Proof
data Intro = OrIl MetaProof
| OrIr MetaProof
| AndI MetaProof MetaProof
| ExistsI MetaFormula MetaProof
| ImpliesI MetaProof
| NotI MetaProof
| ForallI MetaProof
| TopI
| EqI MetaProofEq
type MetaIntro = MMetavar Intro
data ProofElim = Use MetaProofEqSimp
| ElimStep MetaElimStep
type MetaProofElim = MMetavar ProofElim
data ElimStep = BotE
| NotE MetaProof
| OrE MetaProof MetaProof
| NTElimStep (NTElimStep MetaProofElim)
type MetaElimStep = MMetavar ElimStep
data ProofEqElim = UseEq
| UseEqSym
| EqElimStep MetaEqElimStep
type MetaProofEqElim = MMetavar ProofEqElim
data EqElimStep = NTEqElimStep (NTElimStep MetaProofEqElim)
type MetaEqElimStep = MMetavar EqElimStep
data NTElimStep a = AndEl a
| AndEr a
| ExistsE a
| ImpliesE MetaProof a
| ForallE MetaFormula a
| InvBoolExtl MetaProof a
| InvBoolExtr MetaProof a
| InvFunExt MetaFormula a
data ProofEq = Simp MetaProofEqSimp
| Step MetaHyp MetaProofEqElim MetaProofEqSimp MetaProofEq
| BoolExt MetaProof MetaProof
| FunExt MetaProofEq
type MetaProofEq = MMetavar ProofEq
data ProofEqs = PrEqNil
| PrEqCons MetaProofEq MetaProofEqs
type MetaProofEqs = MMetavar ProofEqs
data ProofEqSimp = SimpCons Cons [MetaProofEq]
| SimpApp MetaProofEqs
| SimpChoice MetaProofEq MetaProofEqs
| SimpLam EtaMode MetaProofEq
type MetaProofEqSimp = MMetavar ProofEqSimp
data EtaMode = EMNone | EMLeft | EMRight
data HElr = HVar Int
| HGlob GlobHyp
| AC MetaType MetaFormula MetaProof
data Hyp = Hyp HElr CFormula
type MetaHyp = MMetavar Hyp
data GlobHyp = GlobHyp {ghName :: String, ghForm :: MFormula, ghId :: Int, ghGenCost :: GenCost}
-- -----------------------
type Context = [CtxExt]
data CtxExt = VarExt MType
| HypExt CFormula
data CFormula = Cl Env MFormula
| CApp CFormula CFormula -- AC: MFormula MFormula, ExistsI: CFormula MFormula, ForallI: CFormula MFormula, ExistsE: CFormula CFormula, ForallE: CFormula MFormula
| CNot CFormula
| CHN HNFormula
data CArgs = ClA Env MArgs
type Env = [EnvElt]
data EnvElt = Skip
| Sub CFormula
| Lift Int
data HNFormula = HNC MUId Cons [FormulaArg CFormula]
| HNApp MUId Elr [CArgs]
| HNChoice MUId MType CFormula [CArgs]
| HNLam MUId MType CFormula
data HNArgs = HNNil
| HNCons CFormula [CArgs]
typeBool = NotM Bool
cl :: MFormula -> CFormula
cl f = Cl [] f
formBot = NotM (C nu Bot [])
-- -----------------------
lift :: Int -> CFormula -> CFormula
lift 0 f = f
lift n (Cl env f) = Cl (Lift n : env) f
lift n (CApp c1 c2) = CApp (lift n c1) (lift n c2)
lift n (CNot c) = CNot (lift n c)
lift n (CHN f) =
case f of
HNApp muid elr args -> CHN $ HNApp muid lelr (map (\(ClA env x) -> ClA (Lift n : env) x) args)
where
lelr = case elr of
Var i -> Var (i + n)
Glob g -> Glob g
HNChoice muid typ qf args -> CHN $ HNChoice muid typ (lift n qf) (map (\(ClA env x) -> ClA (Lift n : env) x) args)
sub :: CFormula -> CFormula -> CFormula
sub sf (Cl (Skip : env) f) = Cl (Sub sf : env) f
doclos :: Env -> Int -> Either Int CFormula
doclos = f 0
where
f ns [] i = Left (ns + i)
f ns (Lift n : xs) i = f (ns + n) xs i
f ns (Sub s : _) 0 = Right (lift ns s)
f ns (Skip : _) 0 = Left ns
f ns (Skip : xs) i = f (ns + 1) xs (i - 1)
f ns (Sub _ : xs) i = f ns xs (i - 1)
univar :: Env -> Int -> Maybe Int
univar cl v = f cl v 0
where
f [] v v' = Just (v' + v)
f (Lift n : _) v v' | v < n = Nothing
f (Lift n : xs) v v' = f xs (v - n) v'
f (Sub _ : xs) v v' = f xs v (v' + 1)
f (Skip : _) 0 v' = Just v'
f (Skip : xs) v v' = f xs (v - 1) (v' + 1)
subsvars :: Env -> [Int]
subsvars = f 0
where
f n [] = []
f n (Lift _ : xs) = f n xs
f n (Sub _ : xs) = n : f (n + 1) xs
f n (Skip : xs) = f (n + 1) xs
lookupVarType :: Context -> Int -> Maybe MType
lookupVarType [] _ = Nothing
lookupVarType (VarExt t : _) 0 = Just t
lookupVarType (_ : ctx) n = lookupVarType ctx (n - 1)
-- ----------------------------
probsize :: Problem -> Int
probsize pr = sum (map sgv (prGlobVars pr)) + sum (map sgh (prGlobHyps pr)) + sum (map (sf . snd) (prConjectures pr))
where
sgv gv = st $ gvType gv
sgh gh = sf $ ghForm gh
sf (NotM f) = case f of
C _ _ args -> 1 + sum (map sa args)
App _ _ args -> 1 + sa2 args
Lam _ t f -> st t + sf f
sa (F f) = sf f
sa (T t) = st t
sa2 (NotM ArgNil) = 0
sa2 (NotM (ArgCons f as)) = sf f + sa2 as
st t = 0
-- ------------------------------
instance ExpandMetas MType where
expandmetas t =
expandmm t $ \t -> case t of
Map t1 t2 -> do
t1 <- expandmetas t1
t2 <- expandmetas t2
return $ NotM $ Map t1 t2
_ ->
return $ NotM t
instance ExpandMetas MFormula where
expandmetas f =
expandmm f $ \f -> case f of
C uid c as -> do
as <- mapM (\a -> case a of
F f -> liftM F $ expandmetas f
T t -> liftM T $ expandmetas t)
as
return $ NotM $ C uid c as
App uid elr as -> do
as <- expandmetas as
return $ NotM $ App uid elr as
Choice uid t f as -> do
t <- expandmetas t
f <- expandmetas f
as <- expandmetas as
return $ NotM $ Choice uid t f as
Lam uid t f -> do
t <- expandmetas t
f <- expandmetas f
return $ NotM $ Lam uid t f
instance ExpandMetas MArgs where
expandmetas f =
expandmm f $ \f -> case f of
ArgNil ->
return $ NotM ArgNil
ArgCons f fs -> do
f <- expandmetas f
fs <- expandmetas fs
return $ NotM $ ArgCons f fs
instance ExpandMetas CFormula where
expandmetas cf =
case cf of
Cl env f -> do
env <- expandmetas env
f <- expandmetas f
return $ Cl env f
CApp f1 f2 -> do
f1 <- expandmetas f1
f2 <- expandmetas f2
return $ CApp f1 f2
CNot f -> do
f <- expandmetas f
return $ CNot f
CHN f -> do
f <- expandmetas f
return $ CHN f
instance ExpandMetas Env where
expandmetas = mapM g
where
g (Sub f) = do
f <- expandmetas f
return $ Sub f
g x =
return x
instance ExpandMetas HNFormula where
expandmetas f =
case f of
HNC uid c as -> do
as <- mapM (\a -> case a of
F f -> liftM F $ expandmetas f
T t -> liftM T $ expandmetas t)
as
return $ HNC uid c as
HNApp uid elr as -> do
as <- mapM g as
return $ HNApp uid elr as
HNChoice uid t f as -> do
t <- expandmetas t
f <- expandmetas f
as <- mapM g as
return $ HNChoice uid t f as
HNLam uid t f -> do
t <- expandmetas t
f <- expandmetas f
return $ HNLam uid t f
where
g (ClA env as) = do
env <- expandmetas env
as <- expandmetas as
return $ ClA env as
instance ExpandMetas MetaType where
expandmetas t = do
NotM t <- expandmetas (Meta t)
crmeta t
instance ExpandMetas MetaFormula where
expandmetas f = do
NotM f <- expandmetas (Meta f)
crmeta f
instance ExpandMetas MetaProof where
expandmetas p =
expandmeta p $ \p -> case p of
Intro p -> do
p <- expandmetas p
crmeta $ Intro p
Elim h p -> do
h <- expandmetas h
p <- expandmetas p
crmeta $ Elim h p
RAA p -> do
p <- expandmetas p
crmeta $ RAA p
instance ExpandMetas MetaIntro where
expandmetas p =
expandmeta p $ \p -> case p of
OrIl p -> do
p <- expandmetas p
crmeta $ OrIl p
OrIr p -> do
p <- expandmetas p
crmeta $ OrIr p
AndI p1 p2 -> do
p1 <- expandmetas p1
p2 <- expandmetas p2
crmeta $ AndI p1 p2
ExistsI f p -> do
f <- expandmetas f
p <- expandmetas p
crmeta $ ExistsI f p
ImpliesI p -> do
p <- expandmetas p
crmeta $ ImpliesI p
NotI p -> do
p <- expandmetas p
crmeta $ NotI p
ForallI p -> do
p <- expandmetas p
crmeta $ ForallI p
TopI ->
crmeta TopI
EqI p -> do
p <- expandmetas p
crmeta $ EqI p
instance ExpandMetas MetaProofElim where
expandmetas p =
expandmeta p $ \p -> case p of
Use p -> do
p <- expandmetas p
crmeta $ Use p
ElimStep p -> do
p <- expandmetas p
crmeta $ ElimStep p
instance ExpandMetas MetaElimStep where
expandmetas p =
expandmeta p $ \p -> case p of
BotE ->
crmeta BotE
NotE p -> do
p <- expandmetas p
crmeta $ NotE p
OrE p1 p2 -> do
p1 <- expandmetas p1
p2 <- expandmetas p2
crmeta $ OrE p1 p2
NTElimStep p -> do
p <- expandmetas p
crmeta $ NTElimStep p
instance ExpandMetas MetaProofEqElim where
expandmetas p =
expandmeta p $ \p -> case p of
UseEq ->
crmeta UseEq
UseEqSym ->
crmeta UseEqSym
EqElimStep p -> do
p <- expandmetas p
crmeta $ EqElimStep p
instance ExpandMetas MetaEqElimStep where
expandmetas p =
expandmeta p $ \p -> case p of
NTEqElimStep p -> do
p <- expandmetas p
crmeta $ NTEqElimStep p
instance ExpandMetas a => ExpandMetas (NTElimStep a) where
expandmetas p =
case p of
AndEl p -> do
p <- expandmetas p
return $ AndEl p
AndEr p -> do
p <- expandmetas p
return $ AndEr p
ExistsE p -> do
p <- expandmetas p
return $ ExistsE p
ImpliesE p1 p2 -> do
p1 <- expandmetas p1
p2 <- expandmetas p2
return $ ImpliesE p1 p2
ForallE f p -> do
f <- expandmetas f
p <- expandmetas p
return $ ForallE f p
InvBoolExtl p1 p2 -> do
p1 <- expandmetas p1
p2 <- expandmetas p2
return $ InvBoolExtl p1 p2
InvBoolExtr p1 p2 -> do
p1 <- expandmetas p1
p2 <- expandmetas p2
return $ InvBoolExtr p1 p2
InvFunExt f p -> do
f <- expandmetas f
p <- expandmetas p
return $ InvFunExt f p
instance ExpandMetas MetaProofEq where
expandmetas p =
expandmeta p $ \p -> case p of
Simp p -> do
p <- expandmetas p
crmeta $ Simp p
Step h p1 p2 p3 -> do
h <- expandmetas h
p1 <- expandmetas p1
p2 <- expandmetas p2
p3 <- expandmetas p3
crmeta $ Step h p1 p2 p3
BoolExt p1 p2 -> do
p1 <- expandmetas p1
p2 <- expandmetas p2
crmeta $ BoolExt p1 p2
FunExt p -> do
p <- expandmetas p
crmeta $ FunExt p
instance ExpandMetas MetaProofEqs where
expandmetas p =
expandmeta p $ \p -> case p of
PrEqNil ->
crmeta PrEqNil
PrEqCons p ps -> do
p <- expandmetas p
ps <- expandmetas ps
crmeta $ PrEqCons p ps
instance ExpandMetas MetaProofEqSimp where
expandmetas p =
expandmeta p $ \p -> case p of
SimpCons c ps -> do
ps <- mapM expandmetas ps
crmeta $ SimpCons c ps
SimpApp ps -> do
ps <- expandmetas ps
crmeta $ SimpApp ps
SimpChoice p ps -> do
p <- expandmetas p
ps <- expandmetas ps
crmeta $ SimpChoice p ps
SimpLam em p -> do
p <- expandmetas p
crmeta $ SimpLam em p
instance ExpandMetas MetaHyp where
expandmetas p =
expandmeta p $ \p -> case p of
Hyp elr cf -> do
elr <- case elr of
AC typ qf p -> do
typ <- expandmetas typ
qf <- expandmetas qf
p <- expandmetas p
return $ AC typ qf p
_ -> return elr
cf <- expandmetas cf
crmeta $ Hyp elr cf
| frelindb/agsyHOL | Syntax.hs | mit | 13,860 | 0 | 21 | 4,427 | 5,396 | 2,620 | 2,776 | 455 | 6 |
module TetrisAttack.Board.Combos (
handleCombos, gatherCombos
) where
--------------------------------------------------------------------------------
import Data.List (nub)
import TetrisAttack.Board.Types
import TetrisAttack.Constants
import TetrisAttack.Grid
import TetrisAttack.Tile
--------------------------------------------------------------------------------
type Combo = (GridLocation2D, TileColor)
-- For the given list of tuples of (row, color, numCombo), generate
-- a bunch of RLE combos for the given column
mkRowCombo :: [(Int, TileColor, Int)] -> Int -> [(Combo, Int)]
mkRowCombo l col = map (\(row, t, n) -> (((row, col), t), n)) l
mkColCombo :: [(Int, TileColor, Int)] -> Int -> [(Combo, Int)]
mkColCombo l row = map (\(col, t, n) -> (((row, col), t), n)) l
-- Take a RLE condensed combo and expand it into a list of Combos
expandRows :: (Combo, Int) -> [Combo]
expandRows (((x, y), color), num) = [((col, y), color) | col <- [(x-num+1)..x]]
expandCols :: (Combo, Int) -> [Combo]
expandCols (((x, y), c), num) = [((x, row), c) | row <- [(y-num+1)..y]]
gatherCombos :: Int -> BoardState -> [Combo]
gatherCombos comboLimit st = nub $ gatheredCols ++ gatheredRows
where
gatheredRows :: [Combo]
gatheredRows =
(concat $ zipWith mkRowCombo (walkRows st countWalker) [1..rowsPerBoard]) >>= expandRows
gatheredCols :: [Combo]
gatheredCols =
(concat $ zipWith mkColCombo (walkColumns st countWalker) [1..blocksPerRow]) >>= expandCols
-- This grid walker walks along rows or columns and keeps track of stationary
-- runs of a matching color and returns a list of all such runs.
countWalker :: GridWalker Tile [(Int, TileColor, Int)]
countWalker = countHelper 0 1 Blank []
where
countHelper :: Int -> Int -> Tile -> [(Int, TileColor, Int)] ->
GridWalker Tile [(Int, TileColor, Int)]
countHelper pos cnt tile combos = Walker walkerFn
where
dump :: Tile -> TileColor -> GridWalker Tile [(Int, TileColor, Int)]
dump t c = countHelper (pos + 1) 1 t ((pos, c, cnt) : combos)
reset :: Tile -> GridWalker Tile [(Int, TileColor, Int)]
reset t = countHelper (pos + 1) 1 t combos
walkerFn :: Maybe Tile -> GridWalker Tile [(Int, TileColor, Int)]
walkerFn Nothing
| cnt >= comboLimit = case tile of
(Stationary old) -> Result $ (pos, old, cnt) : combos
_ -> error "handleCombos -- The impossible happened"
| otherwise = Result $ combos
walkerFn (Just (Stationary new)) =
case tile of
(Stationary old)
| old == new -> countHelper (pos + 1) (cnt + 1) (Stationary new) combos
| cnt >= comboLimit -> dump (Stationary new) old
| otherwise -> reset (Stationary new)
_ -> reset (Stationary new)
walkerFn (Just t)
| cnt >= comboLimit =
case tile of
(Stationary old) -> dump t old
_ -> reset t
| otherwise = reset t
handleCombos :: TileMap -> (BoardState, Board a) -> (BoardState, Board a)
handleCombos m (st, b) = (bulkUpdate2D Vanishing (map fst gatheredTiles) st,
foldr updateLogic b gatheredTiles)
where
gatheredTiles = gatherCombos 3 st
updateLogic :: Combo -> Board a -> Board a
updateLogic (loc, color) = update2D (vanishing m color) loc
| Mokosha/HsTetrisAttack | TetrisAttack/Board/Combos.hs | mit | 3,529 | 0 | 17 | 969 | 1,187 | 654 | 533 | 58 | 6 |
module Atomo.Env where
import Atomo.Error
import Atomo.Internals
import Atomo.Primitive (primFuncs)
import Control.Monad.Error
import Data.IORef
import Data.Maybe (fromJust)
import Debug.Trace
type Scope = IORef [(Index, IORef AtomoVal)]
type Env = [Scope]
nullScope :: IO Scope
nullScope = newIORef []
nullEnv :: IO Env
nullEnv = do prims <- mapM (\(n, (a, _)) -> do val <- newIORef (lambdify (map PName a) (ABlock [APrimCall n (map AVariable a)]))
return (Define n, val)) primFuncs
global <- newIORef prims
return [global]
mutateVal :: Env -> Index -> AtomoVal -> IOThrowsError AtomoVal
mutateVal e n v = do ref <- getRef e n
liftIO $ writeIORef ref v
return v
defineVal :: Env -> Index -> AtomoVal -> IOThrowsError AtomoVal
defineVal e n v = do val <- liftIO $ newIORef v
env <- liftIO $ readIORef (head e)
liftIO $ writeIORef (head e) ((n, val) : env)
return v
getVal :: Env -> String -> IOThrowsError AtomoVal
getVal e n = do m <- maybeRef e (Define n)
case m of
Just v -> (liftIO . readIORef) v
Nothing -> do c <- maybeRef e (Class (Name n))
case c of
Just v -> (liftIO . readIORef) v
Nothing -> error $ "Could not find definition `" ++ n ++ "'"
getDef :: Env -> Index -> IOThrowsError AtomoVal
getDef e i = getRef e i >>= liftIO . readIORef
getRef :: Env -> Index -> IOThrowsError (IORef AtomoVal)
getRef e i = do m <- maybeRef e i
case m of
Nothing -> case i of
(Define n) -> error $ "Could not find definition `" ++ n ++ "'"
(Class t) -> error $ "Could not find class `" ++ prettyType t ++ "'"
(Process t) -> error $ "Could not find process `" ++ show t ++ "'"
(Typeclass n) -> error $ "Could not find typeclass `" ++ n ++ "'"
(Instance n t) -> error $ "Typeclass `" ++ n ++ "' does not have instance for `" ++ t ++ "'"
Just v -> return v
maybeRef :: Env -> Index -> IOThrowsError (Maybe (IORef AtomoVal))
maybeRef [] _ = return Nothing
maybeRef (s:ss) n = do env <- liftIO $ readIORef s
case lookup n env of
Just v -> return $ Just v
Nothing -> maybeRef ss n
getClasses :: Env -> Type -> IOThrowsError [(Index, IORef AtomoVal)]
getClasses [] _ = return []
getClasses (s:ss) t = do env <- liftIO $ readIORef s
rest <- getClasses ss t
return (findClasses env t [] ++ rest)
where
findClasses [] _ acc = acc
findClasses ((Class f, v):es) t acc | match t f = findClasses es t ((Class f, v) : acc)
| otherwise = findClasses es t acc
findClasses (_:es) t acc = findClasses es t acc
pMatch :: Env -> PatternMatch -> AtomoVal -> IOThrowsError Bool
pMatch e PAny _ = return True
pMatch e (PMatch a) b = return (a == b)
pMatch e (PName n) v = defineVal e (Define n) v >> return True
pMatch e (PNamed n p) v = do m <- pMatch e p v
if m
then defineVal e (Define n) v >> return True
else return False
pMatch e (PCons a as) (AValue b bs _) | a == b = matchAll e as bs
| otherwise = return False
pMatch e (PHeadTail h t) (AList (x:xs)) = do head <- pMatch e h x
if head
then pMatch e t (AList xs)
else return False
pMatch e (PList as) (AList bs) = matchAll e as bs
pMatch e (PTuple as) (ATuple bs) = matchAll e as bs
pMatch e _ _ = return False
pMatches :: PatternMatch -> AtomoVal -> Bool
pMatches PAny _ = True
pMatches (PMatch a) b = a == b
pMatches (PName _) _ = True
pMatches (PNamed _ p) v = pMatches p v
pMatches (PCons a as) (AValue b bs _) = a == b && matchesAll as bs
pMatches (PHeadTail _ _) (AList (_:_)) = True
pMatches (PList as) (AList bs) = matchesAll as bs
pMatches (PTuple as) (ATuple bs) = matchesAll as bs
pMatches _ _ = False
matchesAll :: [PatternMatch] -> [AtomoVal] -> Bool
matchesAll [] [] = True
matchesAll [] _ = False
matchesAll _ [] = False
matchesAll (a:as) (b:bs) | pMatches a b = matchesAll as bs
| otherwise = False
matchAll :: Env -> [PatternMatch] -> [AtomoVal] -> IOThrowsError Bool
matchAll e [] [] = return True
matchAll e [] _ = return False
matchAll e _ [] = return False
matchAll e (a:as) (b:bs) = do match <- pMatch e a b
if match
then matchAll e as bs
else return False
matchExec :: Env -> [AtomoVal] -> AtomoVal -> IOThrowsError AtomoVal
matchExec e [] _ = error "Non-exhaustive pattern match."
matchExec e ((APattern p c):ps) v = do m <- pMatch e p v
if m
then return c
else matchExec e ps v
| vito/atomo-old | Atomo/Env.hs | mit | 5,524 | 0 | 22 | 2,218 | 2,072 | 1,013 | 1,059 | 108 | 6 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE LambdaCase #-}
module Main (main) where
import ClassyPrelude
import Data.Either (isRight, isLeft)
import Test.Hspec
import Test.QuickCheck (property, Arbitrary(..), oneof)
import qualified Data.Text as T
import Data.SemVer
-- | Arbitrary semver
instance Arbitrary SemVer where
arbitrary = semver' <$> arb <*> arb <*> arb <*> arbitrary where
arb = abs <$> arbitrary
instance Arbitrary SemVerRange where
arbitrary = oneof [Eq <$> arbitrary,
Lt <$> arbitrary,
Gt <$> arbitrary,
Leq <$> arbitrary,
Geq <$> arbitrary
]
-- | Unsafe instance!
instance IsString SemVer where
fromString s = case parseSemVer (T.pack s) of
Right sv -> sv
Left err -> error $ show err
-- | Unsafe instance!
instance IsString SemVerRange where
fromString s = case parseSemVerRange (T.pack s) of
Right svr -> svr
Left err -> error $ show err
instance Arbitrary Text where
arbitrary = pack <$> arbitrary
instance Arbitrary PrereleaseTag where
arbitrary = oneof [IntTag . abs <$> arbitrary]
instance Arbitrary PrereleaseTags where
arbitrary = PrereleaseTags <$> arbitrary
-- | Asserts that the first argument is a `Right` value equal to the second
-- argument.
shouldBeR :: (Show a, Show b, Eq b) => Either a b -> b -> IO ()
shouldBeR x y = do
shouldSatisfy x isRight
let Right x' = x
x' `shouldBe` y
infixl 1 `shouldBeR`
shouldBeL :: (Show a, Show b, Eq a) => Either a b -> IO ()
shouldBeL x = shouldSatisfy x isLeft
main :: IO ()
main = hspec $ do
describe "semver parsing" $ do
it "should parse basic semvers" $ property $
-- Pre-apply absolute value so we know they're positive integers
\((abs -> maj, abs -> min, abs -> patch) :: (Int, Int, Int)) -> do
let s = intercalate "." $ map tshow ([maj, min, patch] :: [Int])
parseSemVer s `shouldBeR` semver maj min patch
it "should parse a semver with only major version" $ property $
\(abs -> maj :: Int) -> do
parseSemVer (tshow maj) `shouldBeR` semver maj 0 0
it "should parse a semver with only major and minor versions" $ property $
\((abs -> maj, abs -> min) :: (Int, Int)) -> do
let s = intercalate "." $ map tshow ([maj, min] :: [Int])
parseSemVer s `shouldBeR` semver maj min 0
it "pretty-printing is an injection" $ property $ \sv -> do
parseSemVer (tshow sv) `shouldBeR` sv
it "should parse a semver with metadata" $ do
parseSemVer "1.2.3-pre+asdf" `shouldBeR` semver'' 1 2 3 ["pre"] ["asdf"]
describe "with release tags" $ do
it "should parse a semver with release tags" $ do
parseSemVer "1.2.3-alpha" `shouldBeR` semver' 1 2 3 ["alpha"]
parseSemVer "1.2.3alpha" `shouldBeR` semver' 1 2 3 ["alpha"]
it "should parse a semver with multiple release tags" $ do
parseSemVer "1.2.3-alpha.3" `shouldBeR` semver' 1 2 3 ["alpha", IntTag 3]
parseSemVer "1.2.3alpha.3" `shouldBeR` semver' 1 2 3 ["alpha", IntTag 3]
describe "prerelease tag comparison" $ do
it "should treat empty lists as greater" $ property $
\(tags::PrereleaseTags) -> case tags of
PrereleaseTags [] -> return ()
tags -> [] > tags `shouldBe` True
describe "semver range parsing" $ do
it "should parse a semver into an exact range" $ property $ \sv -> do
-- This says that if we pretty-print a semver V and parse it as a
-- semver range, we get the range "= V" back.
parseSemVerRange (tshow sv) `shouldBeR` Eq sv
it "pretty printing should be an injection" $ property $ \svr -> do
-- This says that if we pretty-print a semver V and parse it as a
-- semver range, we get the range "= V" back.
parseSemVerRange (tshow svr) `shouldBeR` svr
it "should parse a semver with partial version into a range" $ property $
\(abs -> maj :: Int, abs -> min :: Int) -> do
let expected = Geq (semver maj min 0) `And` Lt (semver maj (min + 1) 0)
parseIt = parseSemVerRange . T.intercalate "."
-- E.g. 1.2 =====> (>=1.2.0 <1.3)
parseIt [tshow maj, tshow min] `shouldBeR` expected
parseIt [tshow maj, tshow min, "X"] `shouldBeR` expected
parseIt [tshow maj, tshow min, "x"] `shouldBeR` expected
parseIt [tshow maj, tshow min, "*"] `shouldBeR` expected
it "should parse a multi range" $ do
parseSemVerRange "1.2.3-pre+asdf - 2.4.3-pre+asdf"
`shouldBeR` Geq (semver'' 1 2 3 ["pre"] ["asdf"])
`And` Lt (semver'' 2 4 3 ["pre"] ["asdf"])
it "should parse semvers with && instead of spaces" $ do
let expected = Geq (semver 2 0 0) `And` Leq (semver 2 15 0)
parseSemVerRange ">= 2 && <= 2.14" `shouldBeR` expected
it "should fail when it's wrong" $ do
shouldBeL (parseSemVerRange "xyz")
rangeTests
cleanTests
-- | These test cases were adapted from
-- https://github.com/npm/node-semver/blob/master/test/clean.js
cleanTests :: Spec
cleanTests = describe "unclean version strings" $ do
let examples :: [(Text, Maybe Text)] = [
("1.2.3", Just "1.2.3"),
(" 1.2.3 ", Just "1.2.3"),
(" 1.2.3-4 ", Just "1.2.3-4"),
(" 1.2.3-pre ", Just "1.2.3-pre"),
(" =v1.2.3 ", Just "1.2.3"),
("v1.2.3", Just "1.2.3"),
(" v1.2.3 ", Just "1.2.3"),
("\t1.2.3", Just "1.2.3"),
(">1.2.3", Nothing),
("~1.2.3", Nothing),
("<=1.2.3", Nothing)
-- The example below is given in the tests but this doesn't
-- seem like an error to me, so there.
-- ("1.2.x", Nothing)
]
forM_ examples $ \(string, result) -> case result of
Just string' -> do
it ("should parse " <> show string <> " same as " <> show string') $ do
parseSemVer string `shouldSatisfy` isRight
parseSemVer string `shouldBe` parseSemVer string'
Nothing -> do
it ("should not parse " <> show string) $ do
parseSemVer string `shouldSatisfy` isLeft
-- | These test cases were adapted from
-- https://github.com/npm/node-semver/blob/master/test/index.js#L134
rangeTests :: Spec
rangeTests = describe "range tests" $ do
-- In each case, the range described in the first element of the
-- tuple should be satisfied by the concrete version described in
-- the second element of the tuple.
let testCases :: [(Bool, Text, Text)] = [
-- Range constraints with pre-release tags require that any
-- version satisfying the constraint must be equivalent (in
-- its semantic version tuple) to the minimum of all semantic
-- versions within the range. In this case the minimum of the
-- range is "1.2.3" and the version's semantic version tuple
-- is "1.2.4", therefore it does not satisfy the constraints
-- of the range given the presence of pre-release tags.
(False, "1.2.3-pre+asdf - 2.4.3-pre+asdf", "1.2.4-pre+asdf"),
(False, "1.2.3-pre+asdf - 2.4.3-pre+asdf", "2.4.3-alpha"),
(False, ">=0.0.1-alpha <0.2.0-alpha", "0.1.1-alpha"),
(False, "^0.0.1-alpha", "0.0.4-alpha"),
-- Range constraints without prerelease tags are very strict
-- about not admitting versions *with* prerelease tags
(False, "^0.1.2", "0.1.2-beta1"),
(False, "^0.1.2", "0.1.4-beta1"),
-- Despite the numeric quantity, these versions have
-- prerelease tags and are therefore subjected to the same
-- invariant checking.
(False, "^1.2.3-1", "1.8.1-1"),
(False, "^1.2.3-1", "1.8.1-4"),
-- If we ever have an exact version tuple match at the top of
-- a given range then it must satisfy the range constraint!
--
-- e.g. "^1.2.3-alpha" translates to ">=1.2.3-alpha
-- <2.0.0-alpha" and the version to check is "2.0.0-alpha". In
-- this case the version tuples are equivalent, sans
-- prerelease tags, but it does not satisfy the upper-bound
-- less-than relation.
(False, "^1.2.3-alpha", "2.0.0-alpha"),
(True, "1.2.3-pre+asdf - 2.4.3-pre+asdf", "1.2.3-pre+asdf"),
(True, "", "1.0.0"),
(True, "*", "1.2.3"),
(True, "*", "1.2.3"),
(True, "*", "v1.2.3"),
(True, "0.1.20 || 1.2.4", "1.2.4"),
(True, "1.0.0 - 2.0.0", "1.2.3"),
(True, "1.0.0", "1.0.0"),
(True, "1.2.* || 2.*", "1.2.3"),
(True, "1.2.* || 2.*", "2.1.3"),
(True, "1.2.*", "1.2.3"),
(True, "1.2.3 - 2.4.3", "1.2.4"),
(True, "1.2.3 >=1.2.1", "1.2.3"),
(True, "1.2.3+asdf - 2.4.3+asdf", "1.2.3"),
(True, "1.2.3-pre+asdf - 2.4.3-pre+asdf", "1.2.3"),
(True, "1.2.3-pre+asdf - 2.4.3-pre+asdf", "1.2.3-pre.2"),
(True, "1.2.3-pre+asdf - 2.4.3-pre+asdf", "1.2.3-pred"),
(True, "1.2.3-pre+asdf - 2.4.3pre+asdf", "1.2.3"),
(True, "1.2.3pre+asdf - 2.4.3pre+asdf", "1.2.3"),
(True, "1.2.x || 2.x", "1.2.3"),
(True, "1.2.x || 2.x", "2.1.3"),
(True, "1.2.x", "1.2.3"),
(True, "2", "2.1.2"),
(True, "2.*.*", "2.1.3"),
(True, "2.3", "2.3.1"),
(True, "2.x.x", "2.1.3"),
(True, "< 2.0.0", "1.9999.9999"),
(True, "< 1.2", "1.1.1"),
(True, "<1.2", "1.1.1"),
(True, "<2.0.0", "0.2.9"),
(True, "<2.0.0", "1.9999.9999"),
(True, "<= 2.0.0", "2.0.0"),
(True, "<= 2.0.0", "0.2.9"),
(True, "<= 2.0.0", "1.9999.9999"),
(True, "<=0.7.x", "0.6.2"),
(True, "<=0.7.x", "0.7.2"),
(True, "<=2.0.0", "0.2.9"),
(True, "<=2.0.0", "1.9999.9999"),
(True, "<=2.0.0", "2.0.0"),
(True, "<\t2.0.0", "0.2.9"),
(True, "=0.7.x", "0.7.2"),
(True, "> 1.0.0", "1.1.0"),
(True, "> 1.0.0", "1.0.1"),
(True, ">1.0.0", "1.0.1"),
(True, ">1.0.0", "1.1.0"),
(True, ">= 1.0.0", "1.1.0"),
(True, ">= 1.0.0", "1.0.1"),
(True, ">= 1", "1.0.0"),
(True, ">= 1.0.0", "1.0.0"),
(True, ">= 4.0.0 <4.1.0-0", "4.0.1"),
(True, ">=*", "0.2.4"),
(True, ">=0.1.97", "0.1.97"),
(True, ">=0.1.97", "v0.1.97"),
(True, ">=0.2.3 || <0.0.1", "0.0.0"),
(True, ">=0.2.3 || <0.0.1", "0.2.3"),
(True, ">=0.2.3 || <0.0.1", "0.2.4"),
(True, ">=0.7.x", "0.7.2"),
(True, ">=1", "1.0.0"),
(True, ">=1.0.0", "1.0.0"),
(True, ">=1.0.0", "1.0.1"),
(True, ">=1.0.0", "1.1.0"),
(True, ">=1.2", "1.2.8"),
(True, ">=1.2.1 1.2.3", "1.2.3"),
(True, ">=1.2.1 >=1.2.3", "1.2.3"),
(True, ">=1.2.3 >=1.2.1", "1.2.3"),
(True, "^0.0.1-alpha", "0.0.1-beta"),
(True, "^0.0.1-alpha.1", "0.0.1-alpha.t"),
(True, "^0.0.1-alpha.1", "0.0.1-alpha.tdff.dddddddddd"),
(True, "^0.1", "0.1.2"),
(True, "^0.1.2", "0.1.2"),
(True, "^1.2 ^1", "1.4.2"),
(True, "^1.2", "1.4.2"),
(True, "^1.2.0-alpha", "1.2.0-pre"),
(True, "^1.2.3", "1.8.1"),
(True, "^1.2.3+build", "1.2.3"),
(True, "^1.2.3+build", "1.3.0"),
(True, "^1.2.3-alpha", "1.2.3-pre"),
(True, "^1.2.3-alpha.1", "1.2.3-alpha.7"),
(True, "^1.2.3-boop", "1.2.4"),
(True, "x", "1.2.3"),
(True, "||", "1.3.4"),
(True, "~ 1.0", "1.0.2"),
(True, "~ 1.0.3", "1.0.12"),
(True, "~1", "1.2.3"),
(True, "~1.0", "1.0.2"),
(True, "~1.2.1 1.2.3 >=1.2.3", "1.2.3"),
(True, "~1.2.1 1.2.3", "1.2.3"),
(True, "~1.2.1 1.2.3", "1.2.3"),
(True, "~1.2.1 =1.2.3", "1.2.3"),
(True, "~1.2.1 >=1.2.3 1.2.3", "1.2.3"),
(True, "~1.2.1 >=1.2.3", "1.2.3"),
(True, "~2.4", "2.4.0"),
(True, "~2.4", "2.4.5"),
(True, "~> 1", "1.2.3"),
(True, "~>1", "1.2.3"),
(True, "~v0.5.4-pre", "0.5.4"),
(True, "~v0.5.4-pre", "0.5.5"),
(True, "~>3.2.1", "3.2.2")
]
forM_ testCases $ \(expectedMatchBool, range, version) -> do
let fail = expectationFailure
it (show version <> " satisfies range " <> show range) $ do
case (parseSemVerRange range, parseSemVer version) of
(Left err, _) -> fail $ "Semver range parse failed: " <> show err
(_, Left err) -> fail $ "Semver parse failed: " <> show err
(Right range, Right version) -> matches range version `shouldBe` expectedMatchBool
| adnelson/semver-range | tests/Unit.hs | mit | 12,768 | 0 | 23 | 3,423 | 3,351 | 1,931 | 1,420 | 240 | 3 |
module Scripting.Fuligite.RunFile where
import qualified Scripting.Fuligite.DefaultState as DS
import Scripting.Fuligite.Expr (Expr(..), Object, ObjKey,
EvalMonad2, doEM)
import Scripting.Fuligite.Eval (eval, declareVar, lookupPath)
import Scripting.Fuligite.Literal (toString)
import Scripting.Fuligite.FileLoader (loadFile)
import Scripting.Fuligite.State
import Control.Monad.State.Strict
import Data.Maybe (fromMaybe)
import Scripting.Fuligite.Path (Path(..))
import qualified Scripting.Fuligite.PropertyList as PropList
import Scripting.Fuligite.PropertyList (Item(..))
runFile :: String -> IO ()
runFile fileName = do
object <- loadFile fileName
runObjectFile object
runObjectFile :: Object -> IO ()
runObjectFile obj = do
let st = DS.new
--let eResult = runStateT (runObject obj) st
let eResult = doEM st (runObject obj)
let (str, st') = case eResult of
Left err -> (show err, st)
Right (_, st'') -> ("OK", st'')
print str
let mOut = doEM st' getStdOut
case mOut of
Right (Just out, _) -> putStrLn out
Right _ -> print "Could not get stdout"
Left err -> print (show err)
runObject :: Object -> EvalMonad2 ()
runObject obj =
-- Bind (but not evaluated) named properties
-- execute numbered properties
forM_ (PropList.toList obj)
(\item ->
case item of
(KeyValue key expr) -> bindExpr key expr
(Value expr) -> eval expr)
where
bindExpr :: String -> Expr -> EvalMonad2 Expr
bindExpr = declareVar
runPropFile :: [(ObjKey, Expr)] -> IO ()
runPropFile props = do
-- set up the environment
let env = foldr
(\(key,expr) acc -> PropList.insert key expr acc)
DS.defaultEnv props
let mMain = PropList.lookup "main" env
case mMain of
Just expr -> do
let eResult = doEM (makeEvalState env) (eval expr)
case eResult of
Left err -> print err
Right (_,st) -> do
let mOut = doEM st getStdOut
case mOut of
Right (out, _) -> print $ fromMaybe "" out
Left err -> print $ show err
Nothing -> print "No main"
getStdOut :: EvalMonad2 (Maybe String)
getStdOut = do
mExpr <- lookupPath (Item "stdout")
return $ case mExpr of
Just (Lit l) -> Just $ toString l
_ -> Nothing
| tomjefferys/fuligite | src/Scripting/Fuligite/RunFile.hs | mit | 2,473 | 0 | 21 | 731 | 790 | 408 | 382 | 62 | 4 |
module Graphics.Urho3D.Input.Events(
MouseButtonDown(..)
, MouseButtonUp(..)
, MouseMove(..)
, MouseWheel(..)
, EventKeyDown(..)
, EventKeyUp(..)
, EventTextInput(..)
, EventTextEditing(..)
, EventJoystickConnected(..)
, EventJoystickDisconnected(..)
, EventJoystickButtonDown(..)
, EventJoystickButtonUp(..)
, EventJoystickAxisMove(..)
, EventJoystickHatMove(..)
, EventTouchBegin(..)
, EventTouchEnd(..)
) where
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Cpp as C
import Data.Maybe
import Data.Monoid
import Data.Text (Text)
import Graphics.Urho3D.Container.FlagSet
import Graphics.Urho3D.Core.Object
import Graphics.Urho3D.Core.Variant
import Graphics.Urho3D.Input.InputConstants
import Graphics.Urho3D.Math.StringHash
C.context (C.cppCtx <> stringHashContext)
C.include "<Urho3D/Input/InputEvents.h>"
C.using "namespace Urho3D"
-- | Fires when user press down keyboard key
data MouseButtonDown = MouseButtonDown {
mouseButtonDownButton :: !MouseButton
, mouseButtonDownButtons :: !MouseButtonFlags
, mouseButtonDownQualifiers :: !QualifierFlags
} deriving (Show)
instance Event MouseButtonDown where
eventID _ = [C.pure| const StringHash* {&E_MOUSEBUTTONDOWN} |]
loadEventData vmap = do
pbutton :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&MouseButtonDown::P_BUTTON} |]
pbuttons :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&MouseButtonDown::P_BUTTONS} |]
qualifiers :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&MouseButtonDown::P_QUALIFIERS} |]
return $ MouseButtonDown {
mouseButtonDownButton = maybe MouseButtonNone toEnum pbutton
, mouseButtonDownButtons = FlagSet $ maybe 0 fromIntegral pbuttons
, mouseButtonDownQualifiers = FlagSet $ maybe 0 fromIntegral qualifiers
}
-- | Fires when user press down keyboard key
data MouseButtonUp = MouseButtonUp {
mouseButtonUpButton :: !MouseButton
, mouseButtonUpButtons :: !MouseButtonFlags
, mouseButtonUpQualifiers :: !QualifierFlags
} deriving (Show)
instance Event MouseButtonUp where
eventID _ = [C.pure| const StringHash* {&E_MOUSEBUTTONUP} |]
loadEventData vmap = do
pbutton :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&MouseButtonUp::P_BUTTON} |]
pbuttons :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&MouseButtonUp::P_BUTTONS} |]
qualifiers :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&MouseButtonUp::P_QUALIFIERS} |]
return $ MouseButtonUp {
mouseButtonUpButton = maybe MouseButtonNone toEnum pbutton
, mouseButtonUpButtons = FlagSet $ maybe 0 fromIntegral pbuttons
, mouseButtonUpQualifiers = FlagSet $ maybe 0 fromIntegral qualifiers
}
-- | Fires when user press down keyboard key
data MouseMove = MouseMove {
mouseMoveX :: !Int
, mouseMoveY :: !Int
, mouseMoveDX :: !Int
, mouseMoveDY :: !Int
, mouseMoveButtons :: !MouseButtonFlags
, mouseMoveQualifiers :: !QualifierFlags
} deriving (Show)
instance Event MouseMove where
eventID _ = [C.pure| const StringHash* {&E_MOUSEMOVE} |]
loadEventData vmap = do
px :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&MouseMove::P_X} |]
py :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&MouseMove::P_Y} |]
pdx :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&MouseMove::P_DX} |]
pdy :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&MouseMove::P_DY} |]
pbuttons :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&MouseMove::P_BUTTONS} |]
qualifiers :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&MouseMove::P_QUALIFIERS} |]
return $ MouseMove {
mouseMoveX = fromMaybe 0 px
, mouseMoveY = fromMaybe 0 py
, mouseMoveDX = fromMaybe 0 pdx
, mouseMoveDY = fromMaybe 0 pdy
, mouseMoveButtons = FlagSet $ maybe 0 fromIntegral pbuttons
, mouseMoveQualifiers = FlagSet $ maybe 0 fromIntegral qualifiers
}
-- | Fires when user press down keyboard key
data MouseWheel = MouseWheel {
mouseWheelWheel :: !Int
, mouseWheelButtons :: !MouseButtonFlags
, mouseWheelQualifiers :: !QualifierFlags
} deriving (Show)
instance Event MouseWheel where
eventID _ = [C.pure| const StringHash* {&E_MOUSEMOVE} |]
loadEventData vmap = do
pwheel :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&MouseWheel::P_WHEEL} |]
pbuttons :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&MouseWheel::P_BUTTONS} |]
pqualifiers :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&MouseWheel::P_QUALIFIERS} |]
return $ MouseWheel {
mouseWheelWheel = fromMaybe 0 pwheel
, mouseWheelButtons = FlagSet $ maybe 0 fromIntegral pbuttons
, mouseWheelQualifiers = FlagSet $ maybe 0 fromIntegral pqualifiers
}
-- | Fires when user press down keyboard key
data EventKeyDown = EventKeyDown {
pressKey :: !Key
, pressScancode :: !Scancode
, pressButtons :: !MouseButtonFlags
, pressQualifiers :: !QualifierFlags
, pressRepeat :: !Bool
} deriving (Show)
instance Event EventKeyDown where
eventID _ = [C.pure| const StringHash* {&E_KEYDOWN} |]
loadEventData vmap = do
pkey :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&KeyDown::P_KEY} |]
pscan :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&KeyDown::P_SCANCODE} |]
pbuttons :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&KeyDown::P_BUTTONS} |]
pqualifiers :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&KeyDown::P_QUALIFIERS} |]
prepeat :: Maybe Bool <- variantMapGet' vmap [C.pure| const StringHash* {&KeyDown::P_REPEAT} |]
return $ EventKeyDown {
pressKey = maybe KeyUnknown toEnum pkey
, pressScancode = maybe ScancodeUnknown toEnum pscan
, pressButtons = FlagSet $ maybe 0 fromIntegral pbuttons
, pressQualifiers = FlagSet $ maybe 0 fromIntegral pqualifiers
, pressRepeat = fromMaybe False prepeat
}
-- | Fires when user release keyboard key
data EventKeyUp = EventKeyUp {
upKey :: !Key
, upScancode :: !Scancode
, upButtons :: !MouseButtonFlags
, upQualifiers :: !QualifierFlags
} deriving (Show)
instance Event EventKeyUp where
eventID _ = [C.pure| const StringHash* {&E_KEYUP} |]
loadEventData vmap = do
pkey :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&KeyUp::P_KEY} |]
pscan :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&KeyUp::P_SCANCODE} |]
pbuttons :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&KeyUp::P_BUTTONS} |]
pqualifiers :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&KeyUp::P_QUALIFIERS} |]
return $ EventKeyUp {
upKey = maybe KeyUnknown toEnum pkey
, upScancode = maybe ScancodeUnknown toEnum pscan
, upButtons = FlagSet $ maybe 0 fromIntegral pbuttons
, upQualifiers = FlagSet $ maybe 0 fromIntegral pqualifiers
}
-- | Text input event
data EventTextInput = EventTextInput {
eventTextInputText :: !Text
} deriving (Show)
instance Event EventTextInput where
eventID _ = [C.pure| const StringHash* {&E_TEXTINPUT} |]
loadEventData vmap = do
txt :: Maybe Text <- variantMapGet' vmap [C.pure| const StringHash* {&TextInput::P_TEXT} |]
return $ EventTextInput {
eventTextInputText = fromMaybe "" txt
}
-- | Text editing event.
data EventTextEditing = EventTextEditing {
eventTextEditingCompositon :: !Text
, eventTextEditingCursor :: !Int
, eventTextEditingSelectionLength :: !Int
} deriving (Show)
instance Event EventTextEditing where
eventID _ = [C.pure| const StringHash* {&E_TEXTEDITING} |]
loadEventData vmap = do
txt :: Maybe Text <- variantMapGet' vmap [C.pure| const StringHash* {&TextEditing::P_COMPOSITION} |]
cursor :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&TextEditing::P_CURSOR} |]
sel :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&TextEditing::P_SELECTION_LENGTH} |]
return $ EventTextEditing {
eventTextEditingCompositon = fromMaybe "" txt
, eventTextEditingCursor = fromMaybe 0 cursor
, eventTextEditingSelectionLength = fromMaybe 0 sel
}
-- | Joystick connected.
data EventJoystickConnected = EventJoystickConnected {
eventJoystickConnectedId :: !Int
} deriving (Show)
instance Event EventJoystickConnected where
eventID _ = [C.pure| const StringHash* {&E_JOYSTICKCONNECTED} |]
loadEventData vmap = do
jid :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&JoystickConnected::P_JOYSTICKID} |]
return $ EventJoystickConnected {
eventJoystickConnectedId = fromMaybe 0 jid
}
-- | Joystick disconnected.
data EventJoystickDisconnected = EventJoystickDisconnected {
eventJoystickDisconnectedId :: !Int
} deriving (Show)
instance Event EventJoystickDisconnected where
eventID _ = [C.pure| const StringHash* {&E_JOYSTICKDISCONNECTED} |]
loadEventData vmap = do
jid :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&JoystickDisconnected::P_JOYSTICKID} |]
return $ EventJoystickDisconnected {
eventJoystickDisconnectedId = fromMaybe 0 jid
}
-- | Joystick button pressed.
data EventJoystickButtonDown = EventJoystickButtonDown {
eventJoystickButtonDownId :: !Int
, eventJoystickButtonDownBtn :: !ControllerButton
} deriving (Show)
instance Event EventJoystickButtonDown where
eventID _ = [C.pure| const StringHash* {&E_JOYSTICKBUTTONDOWN} |]
loadEventData vmap = do
jid :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&JoystickButtonDown::P_JOYSTICKID} |]
btn :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&JoystickButtonDown::P_BUTTON} |]
return $ EventJoystickButtonDown {
eventJoystickButtonDownId = fromMaybe 0 jid
, eventJoystickButtonDownBtn = maybe ControllerButtonA toEnum btn
}
-- | Joystick button released.
data EventJoystickButtonUp = EventJoystickButtonUp {
eventJoystickButtonUpId :: !Int
, eventJoystickButtonUpBtn :: !ControllerButton
} deriving (Show)
instance Event EventJoystickButtonUp where
eventID _ = [C.pure| const StringHash* {&E_JOYSTICKBUTTONUP} |]
loadEventData vmap = do
jid :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&JoystickButtonUp::P_JOYSTICKID} |]
btn :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&JoystickButtonUp::P_BUTTON} |]
return $ EventJoystickButtonUp {
eventJoystickButtonUpId = fromMaybe 0 jid
, eventJoystickButtonUpBtn = maybe ControllerButtonA toEnum btn
}
-- | Joystick axis moved.
data EventJoystickAxisMove = EventJoystickAxisMove {
eventJoystickAxisMoveId :: !Int
, eventJoystickAxisMoveAxis :: !ControllerAxis
, eventJoystickAxisMovePosition :: !Float
} deriving (Show)
instance Event EventJoystickAxisMove where
eventID _ = [C.pure| const StringHash* {&E_JOYSTICKAXISMOVE} |]
loadEventData vmap = do
jid :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&JoystickAxisMove::P_JOYSTICKID} |]
axis :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&JoystickAxisMove::P_AXIS} |]
pos :: Maybe Float <- variantMapGet' vmap [C.pure| const StringHash* {&JoystickAxisMove::P_POSITION} |]
return $ EventJoystickAxisMove {
eventJoystickAxisMoveId = fromMaybe 0 jid
, eventJoystickAxisMoveAxis = maybe ControllerAxisLeftX toEnum axis
, eventJoystickAxisMovePosition = fromMaybe 0 pos
}
-- | Joystick POV hat moved.
data EventJoystickHatMove = EventJoystickHatMove {
eventJoystickHatMoveId :: !Int
, eventJoystickHatMoveHat :: !HatPosition
, eventJoystickHatMovePosition :: !Int
} deriving (Show)
instance Event EventJoystickHatMove where
eventID _ = [C.pure| const StringHash* {&E_JOYSTICKHATMOVE} |]
loadEventData vmap = do
jid :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&JoystickHatMove::P_JOYSTICKID} |]
hat :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&JoystickHatMove::P_HAT} |]
pos :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&JoystickHatMove::P_POSITION} |]
return $ EventJoystickHatMove {
eventJoystickHatMoveId = fromMaybe 0 jid
, eventJoystickHatMoveHat = maybe HatCenter toEnum hat
, eventJoystickHatMovePosition = fromMaybe 0 pos
}
-- | Fires when user touches the screen
data EventTouchBegin = EventTouchBegin {
eventTouchId :: !Int
, eventTouchX :: !Int
, eventTouchY :: !Int
, eventTouchPressure :: !Float
} deriving (Show)
instance Event EventTouchBegin where
eventID _ = [C.pure| const StringHash* {&E_TOUCHBEGIN} |]
loadEventData vmap = do
tid <- variantMapGet' vmap [C.pure| const StringHash* {&TouchBegin::P_TOUCHID} |]
tx <- variantMapGet' vmap [C.pure| const StringHash* {&TouchBegin::P_X} |]
ty <- variantMapGet' vmap [C.pure| const StringHash* {&TouchBegin::P_Y} |]
tp <- variantMapGet' vmap [C.pure| const StringHash* {&TouchBegin::P_PRESSURE} |]
return $ EventTouchBegin {
eventTouchId = fromMaybe 0 tid
, eventTouchX = fromMaybe 0 tx
, eventTouchY = fromMaybe 0 ty
, eventTouchPressure = fromMaybe 0 tp
}
-- | Finger released from the screen.
data EventTouchEnd = EventTouchEnd {
eventTouchEndId :: !Int
, eventTouchEndX :: !Int
, eventTouchEndY :: !Int
} deriving (Show)
instance Event EventTouchEnd where
eventID _ = [C.pure| const StringHash* {&E_TOUCHEND} |]
loadEventData vmap = do
tid :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&TouchEnd::P_TOUCHID} |]
px :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&TouchEnd::P_X} |]
py :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&TouchEnd::P_Y} |]
return $ EventTouchEnd {
eventTouchEndId = fromMaybe 0 tid
, eventTouchEndX = fromMaybe 0 px
, eventTouchEndY = fromMaybe 0 py
}
-- | Finger moved on the screen.
data EventTouchMove = EventTouchMove {
eventTouchMoveId :: !Int
, eventTouchMoveX :: !Int
, eventTouchMoveY :: !Int
, eventTouchMoveDX :: !Int
, eventTouchMoveDY :: !Int
, eventTouchMovePressure :: !Float
} deriving (Show)
instance Event EventTouchMove where
eventID _ = [C.pure| const StringHash* {&E_TOUCHMOVE} |]
loadEventData vmap = do
tid :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&TouchMove::P_TOUCHID} |]
px :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&TouchMove::P_X} |]
py :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&TouchMove::P_Y} |]
pdx :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&TouchMove::P_DX} |]
pdy :: Maybe Int <- variantMapGet' vmap [C.pure| const StringHash* {&TouchMove::P_DY} |]
press :: Maybe Float <- variantMapGet' vmap [C.pure| const StringHash* {&TouchMove::P_PRESSURE} |]
return $ EventTouchMove {
eventTouchMoveId = fromMaybe 0 tid
, eventTouchMoveX = fromMaybe 0 px
, eventTouchMoveY = fromMaybe 0 py
, eventTouchMoveDX = fromMaybe 0 pdx
, eventTouchMoveDY = fromMaybe 0 pdy
, eventTouchMovePressure = fromMaybe 0 press
}
{-
TODO: Bind these
/// A touch gesture finished recording.
URHO3D_EVENT(E_GESTURERECORDED, GestureRecorded)
{
URHO3D_PARAM(P_GESTUREID, GestureID); // unsigned
}
/// A recognized touch gesture was input by the user.
URHO3D_EVENT(E_GESTUREINPUT, GestureInput)
{
URHO3D_PARAM(P_GESTUREID, GestureID); // unsigned
URHO3D_PARAM(P_CENTERX, CenterX); // int
URHO3D_PARAM(P_CENTERY, CenterY); // int
URHO3D_PARAM(P_NUMFINGERS, NumFingers); // int
URHO3D_PARAM(P_ERROR, Error); // float
}
/// Pinch/rotate multi-finger touch gesture motion update.
URHO3D_EVENT(E_MULTIGESTURE, MultiGesture)
{
URHO3D_PARAM(P_CENTERX, CenterX); // int
URHO3D_PARAM(P_CENTERY, CenterY); // int
URHO3D_PARAM(P_NUMFINGERS, NumFingers); // int
URHO3D_PARAM(P_DTHETA, DTheta); // float (degrees)
URHO3D_PARAM(P_DDIST, DDist); // float
}
/// A file was drag-dropped into the application window.
URHO3D_EVENT(E_DROPFILE, DropFile)
{
URHO3D_PARAM(P_FILENAME, FileName); // String
}
/// Application input focus or minimization changed.
URHO3D_EVENT(E_INPUTFOCUS, InputFocus)
{
URHO3D_PARAM(P_FOCUS, Focus); // bool
URHO3D_PARAM(P_MINIMIZED, Minimized); // bool
}
/// OS mouse cursor visibility changed.
URHO3D_EVENT(E_MOUSEVISIBLECHANGED, MouseVisibleChanged)
{
URHO3D_PARAM(P_VISIBLE, Visible); // bool
}
/// Mouse mode changed.
URHO3D_EVENT(E_MOUSEMODECHANGED, MouseModeChanged)
{
URHO3D_PARAM(P_MODE, Mode); // MouseMode
URHO3D_PARAM(P_MOUSELOCKED, MouseLocked); // bool
}
/// Application exit requested.
URHO3D_EVENT(E_EXITREQUESTED, ExitRequested)
{
}
/// Raw SDL input event.
URHO3D_EVENT(E_SDLRAWINPUT, SDLRawInput)
{
URHO3D_PARAM(P_SDLEVENT, SDLEvent); // SDL_Event*
URHO3D_PARAM(P_CONSUMED, Consumed); // bool
}
/// Input handling begins.
URHO3D_EVENT(E_INPUTBEGIN, InputBegin)
{
}
/// Input handling ends.
URHO3D_EVENT(E_INPUTEND, InputEnd)
{
}
-}
| Teaspot-Studio/Urho3D-Haskell | src/Graphics/Urho3D/Input/Events.hs | mit | 17,617 | 0 | 12 | 3,417 | 3,525 | 1,934 | 1,591 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module BT.Mining where
import Network.Bitcoin (HashData, blockData, HashData, hdTarget, BTC)
import qualified Data.ByteString as B hiding (head)
import qualified Data.ByteString.Char8 as BC
import Prelude hiding (take, drop)
import Data.Text.Encoding as E
import BT.Types
import BT.Redis
import BT.Util
import Numeric (readHex)
import Data.IORef (readIORef)
import Control.Monad (when, liftM, unless)
import Control.Monad.IO.Class (liftIO)
getMiningAddress :: PersistentConns -> IO (Maybe B.ByteString)
getMiningAddress conn = get conn "g:" "global" "mining_address"
setMiningAddress :: PersistentConns -> B.ByteString -> IO Bool
setMiningAddress conn = setnx conn "g:" "global" "mining_address"
storeMerkleDiff :: PersistentConns -> HashData -> IO ()
storeMerkleDiff conn hashData = do
let merkle = extractMerkle hashData
let diffstring = encodeUtf8 $ hdTarget hashData
res <- setMerkleDiff conn merkle diffstring
unless res (storeMerkleDiff conn hashData)
extractMerkle :: HashData -> B.ByteString
extractMerkle hash = BC.take 64 . BC.drop 72 .E.encodeUtf8 . blockData $ hash
extractMerkleRecieved :: String -> B.ByteString
extractMerkleRecieved hash = BC.take 64 . BC.drop 72 . BC.pack $ hash
setMerkleDiff :: PersistentConns -> B.ByteString -> B.ByteString -> IO Bool
setMerkleDiff conn merkle value = do
resp <- set conn "m:" merkle "diff" value
_ <- expire conn "m:" merkle 600
return resp
getMerkleDiff :: PersistentConns -> B.ByteString -> IO (Maybe B.ByteString)
getMerkleDiff conn merkle = get conn "m:" merkle "diff"
hexDiffToInt :: B.ByteString -> BTC
hexDiffToInt hd = fromIntegral int
where int = (fst . head . readHex . BC.unpack . B.reverse) hd :: Integer
getPayout :: PersistentConns -> B.ByteString -> IO BTC
getPayout conn hexdiff = do
payout <- liftIO . readIORef . curPayout $ conn
logMsg $ "got curPayout" ++ show payout
miningDiff <- liftIO . readIORef . curTarget $ conn
logMsg $ "got curTarget" ++ show miningDiff
let diff = hexDiffToInt hexdiff :: BTC
logMsg $ "calculate diff curPayout: " ++ show payout ++ " curTarget: " ++ show miningDiff ++ " miningDiff: " ++ show diff
return $ (miningDiff * payout) / diff
setShareUsername :: PersistentConns -> B.ByteString -> B.ByteString -> IO Bool
setShareUsername conn shareid = setnx conn "s:" shareid "username"
getShareUsername :: PersistentConns -> B.ByteString -> IO (Maybe B.ByteString)
getShareUsername conn shareid = get conn "s:" shareid "username"
setSharePayout :: PersistentConns -> B.ByteString -> BTC -> IO Bool
setSharePayout conn shareid = setbtc conn "s:" shareid "payout"
getSharePayout :: PersistentConns -> B.ByteString -> IO BTC
getSharePayout conn shareid = getbtc conn "s:" shareid "payout"
getMineRecieved :: PersistentConns -> IO BTC
getMineRecieved conn = getbtc conn "g:" "global" "mine_recieved"
setMineRecieved :: PersistentConns -> BTC -> IO Bool
setMineRecieved conn = setbtc conn "g:" "global" "mine_recieved"
incrementSharePayout :: PersistentConns -> B.ByteString -> BTC -> IO BTC
incrementSharePayout conn shareid = incrementbtc conn "s:" shareid "payout"
setSharePercentPaid :: PersistentConns -> B.ByteString -> BTC -> IO Bool
setSharePercentPaid conn shareid payout = set conn "s:" shareid "percentpaid" (BC.pack . show $ payout)
getSharePercentPaid :: PersistentConns -> B.ByteString -> IO BTC
getSharePercentPaid conn shareid = do
resp <- getMaybe (RedisException "No share set") =<< get conn "s:" shareid "percentpaid"
return $ (read . BC.unpack) resp
getUserShares :: PersistentConns -> B.ByteString -> Double -> Double -> IO [B.ByteString]
getUserShares conn = zrangebyscore conn "us:"
getGlobalShares :: PersistentConns -> Double -> Double -> IO [B.ByteString]
getGlobalShares conn = zrangebyscore conn "us:" "global_"
getNextShareLevel :: PersistentConns -> Double -> IO Double
getNextShareLevel conn start = do
totalwrap <- zrangebyscoreWithscores conn "us:" "global" start 1.0
let total = filter (\s -> snd s > start) totalwrap
case total of
x:_ -> return $ snd x
[] -> return 1.0
--- Make a share object containing a payout, percent paid, username
--- Also adds it to the appropriate indices
makeShare :: PersistentConns -> B.ByteString -> IO B.ByteString
makeShare conn username = do
shareid <- liftM BC.pack random256String
resp <- setShareUsername conn shareid username
when resp $ do
_ <- setSharePayout conn shareid 0
_ <- setSharePercentPaid conn shareid 0.0
_ <- addShareUserQueue conn username shareid 0.0
_ <- addShareGlobalQueue conn shareid 0.0
return ()
if resp then return shareid
else makeShare conn username
addShareUserQueue :: PersistentConns -> BC.ByteString -> BC.ByteString -> Double -> IO Integer
addShareUserQueue conn username shareid payout = zadd conn "us:" username payout shareid
remShareUserQueue :: PersistentConns -> BC.ByteString -> BC.ByteString -> IO Integer
remShareUserQueue conn username shareid = zrem conn "us:" username [shareid]
addShareGlobalQueue :: PersistentConns -> BC.ByteString -> Double -> IO Integer
addShareGlobalQueue conn shareid payout = zadd conn "us:" "global" payout shareid
getCurrentMiningShares :: PersistentConns -> IO [B.ByteString]
getCurrentMiningShares conn = zrangebyscore conn "us:" "global" 0.0 0.0
removeGlobalMiningShares :: PersistentConns -> [B.ByteString] -> IO Integer
removeGlobalMiningShares conn = zrem conn "us:" "global"
--- Structure
--- username set of all share keys sorted by payout
--- global sorted set of all share keys sorted by payout
--- Get the current mining share
getCurrentMiningShare :: PersistentConns -> B.ByteString -> IO B.ByteString
getCurrentMiningShare conn username = do
shares <- zrangebyscore conn "us:" username 0.0 0.0
case Prelude.length shares of
0 -> makeShare conn username
_ -> (return.head) shares
| c00w/BitToll | haskell/BT/Mining.hs | mit | 5,983 | 1 | 14 | 1,036 | 1,780 | 880 | 900 | 106 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Monad
import Control.Monad.Except (MonadError (..))
import Data.Char
import Data.Foldable (fold)
import Data.Time.Format (TimeLocale (..), defaultTimeLocale, formatTime)
import Data.Time.LocalTime (TimeZone (..), utcToLocalTime)
import Hakyll
import Hakyll.Web.Sass
import Skylighting (pygments, styleToCss)
import System.FilePath
import Text.Pandoc.Extensions
import Text.Pandoc.Options
import Archives
import Compiler
import ContextField
import FontAwesome
main :: IO ()
main = hakyllWith hakyllConfig $ do
faIcons <- fold <$> preprocess loadFontAwesomeIcons
-- "entry/year/month/day/title/index.md"
let entryPattern = "entry/*/*/*/*/index.md"
entryFilesPattern = "entry/*/*/*/*/**"
let tagPagesPath tag = "entry" </> "tags" </> sanitizeTagName tag </> "index.html"
tags <- buildTags entryPattern $ fromFilePath . tagPagesPath
let appendFooter locale zone item = do
utc <- fmap Just (getItemUTC locale (itemIdentifier item))
`catchError` const (return Nothing)
let y = fmap (formatTime locale "%Y" . utcToLocalTime zone) utc
appendFooterWith y item
appendFooterWith y item = do
footer <- loadBody $ setVersion y "footer.html"
appendItemBody footer item
match entryPattern $ do
route $ setExtension "html"
compile $
pandocCompilerWith readerOptions writerOptions
>>= absolutizeUrls
>>= saveSnapshot "feed-content"
>>= renderKaTeX
>>= saveSnapshot "content"
>>= loadAndApplyTemplate "templates/entry.html" (postContext tags)
>>= appendFooter defaultTimeLocale' timeZoneJST
>>= loadAndApplyTemplate "templates/default.html" (postContext tags)
>>= modifyExternalLinkAttributes
>>= cleanIndexHtmls
>>= renderFontAwesome faIcons
match entryFilesPattern $ do
route idRoute
compile copyFileCompiler
let listPageRules title footerVer pages = paginateRules pages $ \num pat -> do
route idRoute
compile $ do
posts <- recentFirst =<< loadAllSnapshots pat "content"
let listContext' = listField "posts" postContext' (return posts)
<> boolField "noindex" (const (num /= 1))
<> paginateContext pages num
<> maybe missingField (constField "title") title
<> listContext
postContext' = teaserField "teaser" "content" <> postContext tags
makeEmptyItem'
>>= loadAndApplyTemplate "templates/entry_list.html" listContext'
>>= appendFooterWith footerVer
>>= loadAndApplyTemplate "templates/default.html" listContext'
>>= modifyExternalLinkAttributes
>>= cleanIndexHtmls
>>= renderFontAwesome faIcons
tagsRules tags $ \tag pat ->
let grouper = fmap (paginateEvery 5) . sortRecentFirst
makeId = makePageIdentifier $ tagPagesPath tag
title = "Tag archives: " ++ tag
in buildPaginateWith grouper pat makeId >>= listPageRules (Just title) Nothing
let yearlyPagePath year = "entry" </> year </> "index.html"
yearlyArchives <- buildYearlyArchives defaultTimeLocale' timeZoneJST entryPattern $
fromFilePath . yearlyPagePath
archivesRules yearlyArchives $ \year pat ->
let grouper = fmap (paginateEvery 5) . sortRecentFirst
makeId = makePageIdentifier $ yearlyPagePath year
title = "Yearly archives: " <> year
in buildPaginateWith grouper pat makeId >>= listPageRules (Just title) (Just year)
let monthlyPagePath (year, month) = "entry" </> year </> month </> "index.html"
monthlyArchives <- buildMonthlyArchives defaultTimeLocale' timeZoneJST entryPattern $
fromFilePath . monthlyPagePath
archivesRules monthlyArchives $ \key@(year, month) pat ->
let grouper = fmap (paginateEvery 5) . sortRecentFirst
makeId = makePageIdentifier $ monthlyPagePath key
title = "Monthly archives: " <> year <> "/" <> month
in buildPaginateWith grouper pat makeId >>= listPageRules (Just title) (Just year)
listPageRules Nothing Nothing =<<
let grouper = fmap (paginateEvery 5) . sortRecentFirst
makeId = makePageIdentifier "index.html"
in buildPaginateWith grouper entryPattern makeId
let years = map fst $ archivesMap yearlyArchives
version' = maybe id version
forM_ (Nothing:map Just years) $ \year -> version' year $
create ["footer.html"] $
compile $ do
recent <- fmap (take 5) . recentFirst =<< loadAllSnapshots entryPattern "content"
let ctx = listField "recent-posts" (postContext tags) (return recent)
<> tagCloudField' "tag-cloud" tags
<> yearMonthArchiveField "archives" yearlyArchives monthlyArchives year
<> siteContext
makeEmptyItem' >>= loadAndApplyTemplate "templates/footer.html" ctx
create ["feed.xml"] $ do
route idRoute
compile $ do
let ctx = bodyField "description" <> postContext tags
loadAllSnapshots entryPattern "feed-content"
>>= fmap (take 20) . recentFirst
>>= mapM (prependBaseUrl (feedRoot atomFeedConfig))
>>= renderAtom atomFeedConfig ctx
match "images/**/*.svg" $ do
route idRoute
compile $ optimizeSVGCompiler ["-p", "4"]
match "images/icon/cocoa.ico" $ do
route $ constRoute "favicon.ico"
compile copyFileCompiler
match ("CNAME" .||. "images/**") $ do
route idRoute
compile copyFileCompiler
scssDependencies <- makePatternDependency "stylesheets/*/**.scss"
match "stylesheets/*/**.scss" $ compile getResourceBody
rulesExtraDependencies [scssDependencies] $
match "stylesheets/*.scss" $ do
route $ setExtension "css"
compile $ fmap compressCss <$> sassCompiler
match "stylesheets/*.css" $ do
route idRoute
compile compressCssCompiler
create ["stylesheets/highlight.css"] $ do
route idRoute
compile $ makeItem $ compressCss $ styleToCss pygments
match "node_modules/@fortawesome/fontawesome-svg-core/styles.css" $ do
route $ constRoute "vendor/fontawesome/style.css"
compile compressCssCompiler
match ("node_modules/katex/dist/katex.min.css" .||. "node_modules/katex/dist/fonts/**") $ do
route $ gsubRoute "node_modules/katex/dist/" (const "vendor/katex/")
compile copyFileCompiler
match "node_modules/normalize.css/normalize.css" $ do
route $ gsubRoute "node_modules/" (const "vendor/")
compile copyFileCompiler
match "templates/*" $ compile templateBodyCompiler
--- Contexts
postContext :: Tags -> Context String
postContext tags = localDateField defaultTimeLocale' timeZoneJST "date" "%Y/%m/%d %R"
<> tagsField' "tags" tags
<> descriptionField "description" 150
<> imageField "image"
<> siteContext
<> defaultContext
listContext :: Context String
listContext = siteContext <> defaultContext'
siteContext :: Context String
siteContext = constField "lang" "ja"
<> constField "site-title" "Tosainu Lab"
<> constField "site-description" "とさいぬのブログです"
<> constField "site-url" "https://blog.myon.info"
<> constField "site-image" "/images/icon/cocoa-512.jpg"
<> constField "copyright" "© 2011-2022 Tosainu."
<> constField "google-analytics" "UA-57978655-1"
<> constField "disqus" "tosainu"
<> authorContext
authorContext :: Context String
authorContext = constField "author-name" "Tosainu"
<> constField "author-profile" "❤ Arch Linux, ごちうさ"
<> constField "author-portfolio" "https://myon.info"
<> constField "author-avatar" "/images/icon/cocoa.svg"
<> constField "author-twitter" "myon___"
defaultContext' :: Context String
defaultContext' = bodyField "body"
<> metadataField
<> urlField "url"
<> pathField "path"
--- Misc
sanitizeTagName :: String -> String
sanitizeTagName = map (\x -> if x == ' ' then '-' else toLower x) .
filter (liftM2 (||) isAlphaNum (`elem` [' ', '-', '_']))
makePageIdentifier :: FilePath -> PageNumber -> Identifier
makePageIdentifier p 1 = fromFilePath p
makePageIdentifier p n = fromFilePath $ takeDirectory' p </> "page" </> show n </> takeFileName p
where takeDirectory' x = let x' = takeDirectory x in if x' == "." then "" else x'
makeEmptyItem :: Monoid a => Compiler (Item a)
makeEmptyItem = makeItem mempty
makeEmptyItem' :: Compiler (Item String)
makeEmptyItem' = makeEmptyItem
appendItemBody :: Semigroup a => a -> Item a -> Compiler (Item a)
appendItemBody x = withItemBody (return . (<> x))
--- Configurations
hakyllConfig :: Configuration
hakyllConfig = defaultConfiguration
{ destinationDirectory = "build"
, storeDirectory = ".cache"
, tmpDirectory = ".cache/tmp"
, previewHost = "0.0.0.0"
, previewPort = 4567
}
atomFeedConfig :: FeedConfiguration
atomFeedConfig = FeedConfiguration
{ feedTitle = "Tosainu Lab"
, feedDescription = "とさいぬのブログです"
, feedAuthorName = "Tosainu"
, feedAuthorEmail = "[email protected]"
, feedRoot = "https://blog.myon.info"
}
readerOptions :: ReaderOptions
readerOptions = defaultHakyllReaderOptions
{ readerExtensions = enableExtension Ext_east_asian_line_breaks $
enableExtension Ext_emoji $
disableExtension Ext_citations $
readerExtensions defaultHakyllReaderOptions
}
writerOptions :: WriterOptions
writerOptions = defaultHakyllWriterOptions
{ writerHTMLMathMethod = KaTeX ""
}
timeZoneJST :: TimeZone
timeZoneJST = TimeZone (9 * 60) False "JST"
defaultTimeLocale' :: TimeLocale
defaultTimeLocale' = defaultTimeLocale
{ knownTimeZones = knownTimeZones defaultTimeLocale ++ [timeZoneJST]
}
| Tosainu/blog | src/Main.hs | mit | 10,398 | 0 | 29 | 2,665 | 2,425 | 1,169 | 1,256 | 213 | 2 |
-- Figurate Numbers #1 - Pentagonal Number
-- http://www.codewars.com/kata/55ab9eee6badbdaf72000075/
module Codewars.G964.Penta (pNum, gpNum, spNum) where
import Control.Arrow ((&&&))
f :: (Int -> [Int]) -> Int -> Bool
f g = uncurry (&&) . (uncurry (==) . (floor . ff &&& ceiling . ff) &&& any ((== 5) . (`mod` 6)) . g . floor . ff)
ff :: Int -> Float
ff = sqrt . succ . (*24) . fromIntegral
pNum :: Int -> Bool
pNum = f (: [])
gpNum :: Int -> Bool
gpNum = f (\a -> [a, negate a])
spNum :: Int -> Bool
spNum = uncurry (&&) . (uncurry (==) . (floor . sqrt . fromIntegral &&& ceiling . sqrt . fromIntegral) &&& pNum)
| gafiatulin/codewars | src/6 kyu/Penta.hs | mit | 619 | 0 | 15 | 123 | 284 | 163 | 121 | -1 | -1 |
module Main where
import System.Environment
import System.IO
import Control.Monad
import Parser
import Evaluator
import Vals
flushStr :: String -> IO ()
flushStr str = putStr str >> hFlush stdout
readPrompt :: String -> IO String
readPrompt prompt = flushStr prompt >> getLine
evalString :: Env -> String -> IO String
evalString env expr = runIOThrows $ liftM show $ (liftThrows . readExpr) expr >>= eval env
evalAndPrint :: Env -> String -> IO ()
evalAndPrint env expr = evalString env expr >>= putStrLn
untilM :: Monad m => (a -> Bool) -> m a -> (a -> m b) -> b -> m b
untilM pred first second otherwise = do
result <- first
if pred result then
second result >> untilM pred first second otherwise
else
return otherwise
repl :: Env -> IO ()
repl env = untilM (/= ":quit") (readPrompt ">> ") (evalAndPrint env) ()
runOne :: [String] -> IO ()
runOne args = do
env <- primitiveBindings >>= flip bindVars [('z', List $ map String $ drop 1 args)]
(runIOThrows $ liftM show $ eval env (List [Atom 'L', String (args !! 0)]))
>>= hPutStrLn stderr
main :: IO ()
main = do
args <- getArgs
env <- primitiveBindings
case length args of
0 -> repl env
_ -> runOne args
| eligottlieb/chaitin | src/Main.hs | mit | 1,195 | 6 | 16 | 253 | 515 | 253 | 262 | 35 | 2 |
module Main where
import Data.Foldable (traverse_)
import System.Environment (getArgs)
data Q5 = Q5 Rational Rational deriving (Show)
instance Num Q5 where
(Q5 p1 q1) + (Q5 p2 q2) = Q5 (p1 + p2) (q1 + q2)
(Q5 p1 q1) * (Q5 p2 q2) = Q5 (p1 * p2 + 5 * q1 * q2) (p1 * q2 + p2 * q1)
negate (Q5 p q) = Q5 (-p) (-q)
signum (Q5 p 0) = Q5 (signum p) 0
signum x@(Q5 p q) | p > 0 && q > 0 = 1
| p < 0 && q < 0 = -1
| q > 0 = Q5 (signum (-p * p / q * q + 5)) 0
| otherwise = negate . signum $ negate x
abs x = x * signum x
fromInteger n = Q5 (fromInteger n) 0
instance Fractional Q5 where
fromRational r = Q5 r 0
recip (Q5 p q) = Q5 p (-q) * (fromRational . recip $ p * p - 5 * q * q)
rationalPart :: Q5 -> Rational
rationalPart (Q5 a _) = a
score :: Int -> Integer
score = floor . rationalPart . binet
where
binet n = (φ ^ n - recip φ ^ n) / sqrt5
φ = (1 + sqrt5) / 2
sqrt5 = Q5 0 1
main :: IO ()
main = traverse_ (print . score . read) =<< getArgs
| genos/Programming | workbench/Binet.hs | mit | 1,056 | 0 | 15 | 352 | 595 | 301 | 294 | 27 | 1 |
module Parser (parseExpr) where
import Text.Parsec
import Text.Parsec.String (Parser)
import Text.Parsec.Language (haskellStyle)
import qualified Text.Parsec.Expr as Ex
import qualified Text.Parsec.Token as Tok
type Id = String
data Expr
= Lam Id Expr
| App Expr Expr
| Var Id
| Num Int
| Op Binop Expr Expr
deriving (Show)
data Binop = Add | Sub | Mul deriving Show
--
lexer :: Tok.TokenParser ()
lexer = Tok.makeTokenParser style
where ops = ["->","\\","+","*","-","="]
style = haskellStyle {Tok.reservedOpNames = ops }
reservedOp :: String -> Parser ()
reservedOp = Tok.reservedOp lexer
identifier :: Parser String
identifier = Tok.identifier lexer
parens :: Parser a -> Parser a
parens = Tok.parens lexer
contents :: Parser a -> Parser a
contents p = do
Tok.whiteSpace lexer
r <- p
eof
return r
--
natural :: Parser Integer
natural = Tok.natural lexer
variable :: Parser Expr
variable = do
x <- identifier
return (Var x)
number :: Parser Expr
number = do
n <- natural
return (Num (fromIntegral n))
lambda :: Parser Expr
lambda = do
reservedOp "\\"
x <- identifier
reservedOp "->"
e <- expr
return (Lam x e)
aexp :: Parser Expr
aexp = parens expr
<|> variable
<|> number
<|> lambda
term :: Parser Expr
term = Ex.buildExpressionParser table aexp
where infixOp x f = Ex.Infix (reservedOp x >> return f)
table = [[infixOp "*" (Op Mul) Ex.AssocLeft],
[infixOp "+" (Op Add) Ex.AssocLeft]]
expr :: Parser Expr
expr = do
es <- many1 term
return (foldl1 App es)
parseExpr :: String -> Expr
parseExpr input =
case parse (contents expr) "<stdin>" input of
Left err -> error (show err)
Right ast -> ast
main :: IO ()
main = getLine >>= print . parseExpr >> main
| riwsky/wiwinwlh | src/parser.hs | mit | 1,778 | 0 | 11 | 407 | 689 | 355 | 334 | 69 | 2 |
module Test1SpecWE where
import Test.Hspec
import Test.QuickCheck
import Control.Exception (evaluate)
main :: IO ()
main = hspec spec
spec::Spec
spec = do
describe "Prelude.head" $ do
it "returns the first element of a list" $ do
head [23 ..] `shouldBe` (23 :: Int)
it "returns the first element of another list" $ do
head [24 ..] `shouldBe` (24 :: Int)
| codeboardio/kali | test/src_examples/haskell/error_one_file/Root/Test/Test1SpecWE.hs | mit | 367 | 0 | 15 | 73 | 126 | 68 | 58 | 13 | 1 |
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Hadoop.Protos.ClientNamenodeProtocolProtos.SetTimesResponseProto (SetTimesResponseProto(..)) where
import Prelude ((+), (/))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data SetTimesResponseProto = SetTimesResponseProto{}
deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data)
instance P'.Mergeable SetTimesResponseProto where
mergeAppend SetTimesResponseProto SetTimesResponseProto = SetTimesResponseProto
instance P'.Default SetTimesResponseProto where
defaultValue = SetTimesResponseProto
instance P'.Wire SetTimesResponseProto where
wireSize ft' self'@(SetTimesResponseProto)
= case ft' of
10 -> calc'Size
11 -> P'.prependMessageSize calc'Size
_ -> P'.wireSizeErr ft' self'
where
calc'Size = 0
wirePut ft' self'@(SetTimesResponseProto)
= case ft' of
10 -> put'Fields
11 -> do
P'.putSize (P'.wireSize 10 self')
put'Fields
_ -> P'.wirePutErr ft' self'
where
put'Fields
= do
Prelude'.return ()
wireGet ft'
= case ft' of
10 -> P'.getBareMessageWith update'Self
11 -> P'.getMessageWith update'Self
_ -> P'.wireGetErr ft'
where
update'Self wire'Tag old'Self
= case wire'Tag of
_ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
instance P'.MessageAPI msg' (msg' -> SetTimesResponseProto) SetTimesResponseProto where
getVal m' f' = f' m'
instance P'.GPB SetTimesResponseProto
instance P'.ReflectDescriptor SetTimesResponseProto where
getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList [])
reflectDescriptorInfo _
= Prelude'.read
"DescriptorInfo {descName = ProtoName {protobufName = FIName \".hadoop.hdfs.SetTimesResponseProto\", haskellPrefix = [MName \"Hadoop\",MName \"Protos\"], parentModule = [MName \"ClientNamenodeProtocolProtos\"], baseName = MName \"SetTimesResponseProto\"}, descFilePath = [\"Hadoop\",\"Protos\",\"ClientNamenodeProtocolProtos\",\"SetTimesResponseProto.hs\"], isGroup = False, fields = fromList [], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
instance P'.TextType SetTimesResponseProto where
tellT = P'.tellSubMessage
getT = P'.getSubMessage
instance P'.TextMsg SetTimesResponseProto where
textPut msg = Prelude'.return ()
textGet = Prelude'.return P'.defaultValue | alexbiehl/hoop | hadoop-protos/src/Hadoop/Protos/ClientNamenodeProtocolProtos/SetTimesResponseProto.hs | mit | 2,861 | 1 | 16 | 531 | 554 | 291 | 263 | 53 | 0 |
-- Final Interpreters
-- Using typeclasses we can implement a final interpreter which models a set of extensible terms using functions bound to typeclasses rather than data constructors. Instances of the typeclass form interpreters over these terms.
-- For example we can write a small language that includes basic arithmetic, and then retroactively extend our expression language with a multiplication operator without changing the base. At the same time our interpreter logic remains invariant under extension with new expressions.
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
class Expr repr where
lit :: Int -> repr
neg :: repr -> repr
add :: repr -> repr -> repr
mul :: repr -> repr -> repr
instance Expr Int where
lit n = n
neg a = -a
add a b = a + b
mul a b = a * b
instance Expr String where
lit n = show n
neg a = "(-" ++ a ++ ")"
add a b = "(" ++ a ++ " + " ++ b ++ ")"
mul a b = "(" ++ a ++ " * " ++ b ++ ")"
class BoolExpr repr where
eq :: repr -> repr -> repr
tr :: repr
fl :: repr
instance BoolExpr Int where
eq a b = if a == b then tr else fl
tr = 1
fl = 0
instance BoolExpr String where
eq a b = "(" ++ a ++ " == " ++ b ++ ")"
tr = "true"
fl = "false"
eval :: Int -> Int
eval = id
render :: String -> String
render = id
expr :: (BoolExpr repr, Expr repr) => repr
expr = eq (add (lit 1) (lit 2)) (lit 3)
result :: Int
result = eval expr
-- 1
string :: String
string = render expr
-- "((1 + 2) == 3)" | Airtnp/Freshman_Simple_Haskell_Lib | Intro/WIW/Interpreter/Final-interpreters.hs | mit | 1,574 | 0 | 9 | 370 | 430 | 228 | 202 | 41 | 1 |
module Control.Biegunka.BiegunkaSpec
( spec
) where
import Control.Exception (bracket)
import Data.Maybe (fromMaybe)
import System.Directory (getHomeDirectory)
import System.FilePath ((</>))
import qualified System.Posix as Posix
import Test.Hspec
import Control.Biegunka.Biegunka (expandHome)
spec :: Spec
spec =
describe "expandHome" $ do
it "expands bare ~ to the user home directory" $ do
home <- getHomeDirectory
dir <- expandHome "~"
dir `shouldBe` home
it "reflects changes to HOME" $
bracket (Posix.getEnv "HOME") (\home -> Posix.putEnv ("HOME=" ++ fromMaybe "" home)) $ \_ -> do
Posix.putEnv "HOME=foo"
dir <- expandHome "~"
dir `shouldBe` "foo"
it "expands ~/$path to $path in the user home directory" $ do
home <- getHomeDirectory
dir <- expandHome "~/foo"
dir `shouldBe` home </> "foo"
it "expands ~$user to the $user user home directory" $ do
name <- getName
home <- getHome
dir <- expandHome ("~" ++ name)
dir `shouldBe` home
it "expands ~$user/$path to $path in the $user user home directory" $ do
name <- getName
home <- getHome
dir <- expandHome ("~" ++ name ++ "/foo")
dir `shouldBe` home </> "foo"
it "is 'id' for other absolute patterns" $
expandHome "/foo/bar~" `shouldReturn` "/foo/bar~"
it "is 'id' for other relative patterns" $
expandHome "baz/qu~ux" `shouldReturn` "baz/qu~ux"
getName :: IO String
getName = fmap Posix.userName . Posix.getUserEntryForID =<< Posix.getEffectiveUserID
getHome :: IO FilePath
getHome = fmap Posix.homeDirectory . Posix.getUserEntryForID =<< Posix.getEffectiveUserID
| biegunka/biegunka | test/spec/Control/Biegunka/BiegunkaSpec.hs | mit | 1,754 | 0 | 16 | 450 | 461 | 231 | 230 | 43 | 1 |
module ChordData where
import Data.Map
import Sound.ALSA.Sequencer.Event (Pitch, Channel)
type Interval = Int
-- Input chord which is represented by its list of intervals or symbolic shorthand.
-- Received chords are matched against the list of input chords to find the dispatch
-- rules. Additionally, an entry matching any chord may be provided.
data InputChord = AnyChord
| Intervals [Interval] [[Interval]]
| Shorthand String deriving (Show, Eq, Ord)
intervals = flip Intervals ([])
-- Output chord which is represented by the destination channel, and notes to be sent.
-- Not all notes of the matched chord may need to be sent, it may be an unrelated absolute
-- note, or one or more notes of the actual chord with possible offset. A shortcut
-- constructor AllNotes exists to send all notes of the chord.
data NoteOut = AbsNote Pitch |
AllNotes |
ChordNote {
idx :: Int, -- 1-based
offset :: Int
} deriving (Show)
-- How to play the chord. Chords may go to multiple ports at once, so the
-- 'also' field serves as a chain link to the next port to output the chord.
data OutputChord = OutputChord {
outport :: String,
outchan :: Channel,
outnotes :: [NoteOut],
also :: Maybe OutputChord
} deriving (Show)
-- Routing rules represented as a map of input to output chords.
type ChordRouting = Map InputChord OutputChord
| dmgolubovsky/chordemux | src/ChordData.hs | mit | 1,436 | 0 | 9 | 340 | 192 | 120 | 72 | 21 | 1 |
module Colored where
import Colors
class Colored a where
getColor :: a -> ColorFG
| mrlovre/LMTetrys | src/Colored.hs | gpl-2.0 | 88 | 0 | 7 | 20 | 25 | 14 | 11 | 4 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Text.Bristle where
-- Parse mustache(5) templates
--
-- Variable: {{name}}
-- - Search for key in current context, parent context recursively
-- - Nothing is rendered if key not found
-- - HTML is escaped
--
-- Variable: {{{name}}}
-- - Same as variable, but HTML is not escaped
--
-- Sections: {{#section}}{{/section}}
-- - False value or empty list -> text not displayed
-- - Non-empty list -> Context of the block is rendered for every item in the
-- list
-- - Lambdas -> Not supported now
-- - Non-false values -> value is used as the context for a single rendering
--
-- Inverted sections: {{^section}}{{/section}}
-- - Render the text if the key doesn't exist, is false or an empty list
--
-- Comments: {{! comment }}
--
-- Partials: {{> box}}
--
-- Set delimiter:
-- - Not supported
import Prelude hiding (lookup)
import Data.Text
import Text.Parsec
import Text.Parsec.Text (Parser)
import Control.Applicative ((<$>), (<*>))
import Text.Bristle.Types
parseMustache :: Parser Mustache
parseMustache = manyTill parseMustacheNode eof
parseMustacheNode :: Parser MustacheNode
parseMustacheNode =
try partial
<|> try section
<|> try invSection
<|> try comment
<|> try noEscapeVar
<|> try ampVar
<|> try var
<|> try text
where partial = MustachePartial <$>
(mustache $ string "> " >> key) >>= stripNewline
section = prefixSection '#' >>= \(name, mustache) ->
return $ MustacheSection name mustache
invSection = prefixSection '^' >>= \(name, mustache) ->
return $ MustacheSectionInv name mustache
comment = mustache (char '!' >> key) >> return MustacheComment
noEscapeVar = MustacheVar True <$>
(mustache $ between (char '{') (char '}') key)
ampVar = MustacheVar True <$> (mustache $ string "& " >> key)
var = MustacheVar False <$> (mustache key)
text = MustacheText <$>
(many1Till anyChar (try eof <|> startToken) >>= return . pack)
startToken :: Parser ()
startToken = lookAhead $ try $ string "{{" >> return ()
endToken :: Parser ()
endToken = lookAhead $ try $ string "}}" >> return ()
key :: Parser Text
key = manyTill anyChar (lookAhead $ try (string "}}")) >>= return . pack
mustache :: Parser a -> Parser a
mustache f = between (string "{{") (string "}}") f
prefixSection :: Char -> Parser (Text, Mustache)
prefixSection prefix = do
sectionName <- mustache $ char prefix >> key >>= return . unpack
n <- optionMaybe newline
mustache <- manyTill parseMustacheNode $ lookAhead $ try $ sectionEnd sectionName
_ <- sectionEnd sectionName
case n of
Just _ -> newline >> return ()
Nothing -> return ()
return (pack sectionName, mustache)
where sectionEnd name = mustache $ char '/' >> string name
many1Till :: Parser a -> Parser b -> Parser [a]
many1Till f end = do
x <- f
xs <- manyTill f end
return (x:xs)
stripNewline :: a -> Parser a
stripNewline x = optional newline >> return x
| sgillis/bristle | src/Text/Bristle.hs | gpl-2.0 | 3,165 | 0 | 14 | 811 | 827 | 423 | 404 | 59 | 2 |
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-}
module Lamdu.Infer.Recursive
( inferEnv
) where
import Prelude.Compat
import qualified Lamdu.Expr.Val as V
import Lamdu.Infer (InferCtx, freshInferredVar)
import qualified Lamdu.Infer as Infer
import Lamdu.Infer.Internal.Scope (Scope)
import qualified Lamdu.Infer.Internal.Scope as Scope
{-# INLINE inferEnv #-}
inferEnv :: Monad m => V.Var -> Scope -> InferCtx m Infer.Payload
inferEnv recurseVar scope =
do
recursiveType <- freshInferredVar scope "r"
return $
Infer.Payload recursiveType $
Scope.insertTypeOf recurseVar recursiveType scope
| da-x/Algorithm-W-Step-By-Step | Lamdu/Infer/Recursive.hs | gpl-3.0 | 689 | 0 | 10 | 163 | 147 | 85 | 62 | 17 | 1 |
module Mudblood.Colour
( parseColour
, colourToGdk
) where
import Data.Colour
import Data.Colour.SRGB
import Data.Colour.Names
import qualified Graphics.UI.Gtk as G
type MBColour = Colour Double
parseColour :: String -> Maybe MBColour
parseColour col@('#':rest) = Just $ sRGB24read col
parseColour col = readColourName col
colourToGdk :: MBColour -> G.Color
colourToGdk col = let (RGB a b c) = toSRGB24 col
in G.Color (fromIntegral a * 256) (fromIntegral b * 256) (fromIntegral c * 256)
| talanis85/mudblood | src/Mudblood/Colour.hs | gpl-3.0 | 521 | 0 | 10 | 106 | 180 | 96 | 84 | 14 | 1 |
module Board where
import qualified Data.Vector as V
type Location = (Int, Int)
data Shape = Square | Triangle | Hexagon
data Board = Board { minX :: Maybe Int ,
maxX :: Maybe Int ,
minY :: Maybe Int ,
maxY :: Maybe Int ,
minZ :: Maybe Int ,
maxZ :: Maybe Int ,
shape :: Shape}
chessboard = Board (Just 1) (Just 8) (Just 1) (Just 8) (Just 1) (Just 1) Square
chessboard3D = Board (Just 1) (Just 8) (Just 1) (Just 8) (Just 1) (Just 8) Square
chessboardNxN = Board (Just 1) (Nothing) (Just 1) (Nothing) (Just 1) (Just 1) Square
distanceBoard = makeDistanceBoard chessboard
boardRange :: (Enum t1, Num t1) => (t -> Maybe t1) -> (t -> Maybe t1) -> t -> [t1]
boardRange param_min param_max board =
case param_min board of
Just min_p -> case param_max board of
Just max_p -> [min_p..max_p]
Nothing -> [min_p..]
Nothing -> [-1..1] --TODO: Infinite list in both directions??!
boardXrange :: Board -> [Int]
boardXrange = boardRange minX maxX
boardYrange :: Board -> [Int]
boardYrange = boardRange minY maxY
boardZrange :: Board -> [Int]
boardZrange = boardRange minZ maxZ
numberOfSquares2d :: Board -> Int
numberOfSquares2d board = (length $ boardXrange board) * (length $ boardYrange board)
makeDistanceBoard :: Board -> Board
makeDistanceBoard board = Board (Just 1) (doubleMinus1 $ maxX board) (Just 1) (doubleMinus1 $ maxY board) (Just 1) (doubleMinus1 $ maxZ board) Square
doubleMinus1 :: Num a => Maybe a -> Maybe a
doubleMinus1 (Just x) = Just ((x*2)-1)
---Here are the functions moved out of DistanceTables that I thought should be
--board functions---
--
emptyTable :: V.Vector Integer
emptyTable = V.replicate (numberOfSquares2d distanceBoard) (-1)
--emptyTable board = V.replicate (numberOfSquares2d $ makeDistanceBoard board) (-1)
emptyChessTable :: V.Vector Integer
emptyChessTable = V.replicate (numberOfSquares2d chessboard) (-1)
placeObst :: V.Vector Integer -> [Location] -> V.Vector Integer
placeObst table [] = table
placeObst table locals = V.update table $ V.fromList $ zip (map translatePairToVector locals) (repeat (-2))
translatePairToVector :: (Int, Int) -> Int
translatePairToVector pair@(x,y) = (x-1) + ((y-1) * 15)
translateChessPairToVector pair@(x,y) = (8-x) + ((8-y) * 8)
displayTable :: (Show a) => String -> V.Vector a-> IO ()
displayTable tableName table = do
putStrLn tableName
let displaiedTable = breakIntoRows $ map (poundObstical.xUnreach.show) $ V.toList table
putStrLn $ unlines.(map unwords) $ displaiedTable
where xUnreach = (replaceValueWith "-1" "X")
poundObstical = (replaceValueWith "-2" "#")
displayTableToString :: (Show a) => String -> V.Vector a-> String
displayTableToString tableName table = do
let displaiedTable = breakIntoRows $ map (poundObstical.xUnreach.show) $ V.toList table
tableName ++ "\n" ++ (unlines.(map unwords) $ displaiedTable)
where xUnreach = (replaceValueWith "-1" "X")
poundObstical = (replaceValueWith "-2" "#")
displayTableToPython :: (Show a) => String -> V.Vector a-> String
displayTableToPython tableName table = do
show $ zip [(x,y,z) | x<-[1..5], y<-[1..15], z<-[1]] $ concat.map (poundObstical.xUnreach.show) $ V.toList table
where xUnreach = (replaceValueWith "-1" "X")
poundObstical = (replaceValueWith "-2" "#")
entwine [] _ = []
entwine (x:[]) _ = [x]
entwine (x:xs) str = [x] ++ str ++ (entwine xs str)
breakIntoRows :: [a] -> [[a]]
breakIntoRows [] = []
breakIntoRows list = do
let squareRoot = floor . sqrt . (fromIntegral :: Int -> Double)
let base = squareRoot (length list)
[x | x <- take base list] : breakIntoRows' base (drop base list)
breakIntoRows' :: Int -> [a] -> [[a]]
breakIntoRows' _ [] = []
breakIntoRows' size list = [x | x <- take size list] : breakIntoRows' size (drop size list)
replaceValueWith :: Eq a => a -> a -> a -> a
replaceValueWith value withThis replaceThis
| replaceThis == value = withThis
| otherwise = replaceThis
replaceZeroWith :: Integer -> Integer -> Integer
replaceZeroWith = replaceValueWith 0
replaceUnreachableWith :: Integer -> Integer -> Integer
replaceUnreachableWith = replaceValueWith (-1)
| joshuaunderwood7/HaskeLinGeom | Board.hs | gpl-3.0 | 4,361 | 2 | 15 | 966 | 1,674 | 870 | 804 | 82 | 3 |
-- | Generic model wrapper.
module Biobase.SElab.Model.Types where
import Control.Lens
import Data.Text (Text)
import GHC.Generics (Generic)
import Biobase.Types.Accession
import Biobase.SElab.CM.Types (CM)
import Biobase.SElab.HMM.Types (HMM)
import qualified Biobase.SElab.CM.Types as CM
import qualified Biobase.SElab.HMM.Types as HMM
-- | Generic model wrapper.
type Model = Either (HMM ()) CM
-- | A getter for the name of the model. Be it CM or HMM.
modelName :: Getter Model Text
modelName = to f
where f m = case m of
Left hmm -> HMM._name hmm
Right cm -> CM._name cm
modelAccession :: Getter Model (Accession ())
modelAccession = to f
where f m = case m of
Left hmm -> retagAccession $ HMM._accession hmm
Right cm -> retagAccession $ CM._accession cm
| choener/BiobaseInfernal | Biobase/SElab/Model/Types.hs | gpl-3.0 | 902 | 0 | 12 | 259 | 241 | 134 | 107 | 20 | 2 |
{-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module SecretSanta.CyclicArrangement
( CyclicArrangement
, selectCyclicArrangement
) where
import Control.Applicative ((<$>),(<*>),(<|>))
import Control.Arrow (second)
import Control.Monad.State
import Data.List (delete,find,minimumBy)
import Data.Map ((!),assocs,empty,fromList,keys)
import Data.Foldable (foldl')
import Data.Maybe (mapMaybe)
import Data.Ord (comparing)
import Data.Tree
import SecretSanta.Types
import System.Random
import System.Random.Shuffle (shuffle')
-- | Represents a valid secret santa arrangement
-- | which is also a Hamiltonian Cycle
instance Constrainable CyclicArrangement where
feasibleArrangements = feasibleCyclicArrangements
toArrangement = cycleToMap
selectArrangement = selectCyclicArrangement
-- | Converts a CyclicArrangement to a normal Arrangement
cycleToMap :: CyclicArrangement -> Arrangement
cycleToMap [] = fromList []
cycleToMap (x:xs) = fromList $ cycleToMap' (x:xs)
where
cycleToMap' [] = []
cycleToMap' [y] = [(y,x)]
cycleToMap' (y:z:zs) = (y,z) : cycleToMap' (z:zs)
-- | List of all hamiltonian cycles satisfying the constraints
feasibleCyclicArrangements :: ConstraintMap -> [CyclicArrangement]
feasibleCyclicArrangements xs = cycles len $ mapToTree xs
where len = foldl' (\x _ -> x+1) 0 xs
-- | Builds an intermidate Tree data structure used for cycle search
mapToTree :: ConstraintMap -> Tree Name
mapToTree = constructNode
<$> assocs
<*> (minimumBy (comparing (length . snd)) . assocs)
-- | Recursively builds Tree from associating list
constructNode :: Eq a => [(a,[a])] -> (a,[a]) -> Tree a
constructNode ys (x,xs)
-- if the "MapList" is empty, we cannot recurse
| null ys = Node x []
-- otherwise we create the node and recurse for it's children
| otherwise = Node x $ fmap (constructNode ys') xs'
where
-- remove the current node from the "MapList"
-- remove it's reference from the value list of all keys
ys' = fmap (second (delete x)) $ delete (x,xs) ys
-- get the node data to expand
-- ignore nodes with
xs' = mapMaybe (flip find ys' . (\y -> (==y).fst)) xs
-- | Augmented Depth-Limited Search on tree structure
-- | to find hamiltonian cycles satisfying the constraints
cycles :: Int -> Tree Name -> [CyclicArrangement]
cycles 1 tree = [[rootLabel tree]]
cycles n tree
| (null . subForest) tree = []
| otherwise = concatMap
( fmap (rootLabel tree :)
. filter (not.null)
. cycles (n-1)
) $ subForest tree
-- | Augmented depth-limited search
-- | over a randomization of the hamiltonian cycle search space.
-- | Returns the first valid hamiltonian cycle found during the random search
-- | /Ω(n)/ & /O(n!)/
-- | Best Case Complexity:
-- | Linear time to generate a valid solution in the first few attempts
-- | Worst Case Complexity:
-- | Factorial time to generate all possible solutions
-- | and deterimine none satisfy constraints
selectCyclicArrangement :: ConstraintMap -> IO (Maybe CyclicArrangement)
selectCyclicArrangement originalConstraints =
newStdGen >>= return . selectCyclicArrangement' originalConstraints 0 root
where
-- The height of the expanded tree iff it
-- contains a path representing a hamiltonian cycle
height = pred . length $ keys originalConstraints
-- Without loss of generality, we can arbitrarily fix the root node
-- We choose for complexity sake, to select the key with
-- the most constrainted value set.
root = mostConstraintedKey originalConstraints
-- Recursive Definition
selectCyclicArrangement' :: RandomGen gen => ConstraintMap -> Int -> Name -> gen -> Maybe CyclicArrangement
selectCyclicArrangement' constraints depth key gen
| constraints == empty
|| not atTerminalDepth
&& null branches
|| atTerminalDepth
&& not validTerminalNode = Nothing
| atTerminalDepth
&& validTerminalNode = Just [key]
| otherwise = prependKey
. coalesce
. map branchMay
$ zip branches' branchGens
where
atTerminalDepth = depth == height
validTerminalNode = root `elem` originalRecipients
originalRecipients = originalConstraints ! key
prependKey = fmap (key:)
branchMay = uncurry $ selectCyclicArrangement' constraints' (depth + 1)
branches = constraints ! key
branches' = shuffle' branches branchCount shuffleGen
branchCount = length branches
constraints' = reduceReceipiants key constraints
(branchGens,shuffleGen) = runState (replicateM branchCount (state split >> get)) gen
mostConstraintedKey :: ConstraintMap -> Name
mostConstraintedKey = fst
. minimumBy (comparing (length . snd))
. assocs
reduceReceipiants :: Name -> ConstraintMap -> ConstraintMap
reduceReceipiants key = fmap (delete key)
coalesce :: [Maybe a] -> Maybe a
coalesce = foldr (<|>) Nothing
| recursion-ninja/SecretSanta | Constraint/CyclicArrangement.hs | gpl-3.0 | 5,223 | 0 | 14 | 1,249 | 1,165 | 630 | 535 | 85 | 3 |
{-# LANGUAGE BangPatterns, FlexibleContexts #-}
-- | kd-Tree data structure for building multi-dimensional, real-valued
-- indices.
--
-- /References/
--
-- (1) <http://en.wikipedia.org/wiki/Kdtree>
module Data.KDTree
( Tree
, empty
, fromList
, elems
, Distance
, sqrEuclidianDistance
, closest
, withinRadius
) where
import Control.Applicative (Applicative(..), (<$>))
import Control.Arrow
import Control.DeepSeq (NFData(..))
import Data.Foldable
import qualified Data.List as List
import Data.Monoid
import Data.Ord
import Data.Traversable
import Data.Vector.Generic (Vector, (!))
import qualified Data.Vector.Generic as V
import qualified Data.Vector.Unboxed as UV
-- import Statistics.Sample
data Node v a = Leaf !(v Double) a
| Node {-# UNPACK #-} !Int {-# UNPACK #-} !Double (Node v a) (Node v a)
instance Functor (Node v) where
fmap f (Leaf v a) = Leaf v (f a)
fmap f (Node i x l r) = Node i x (fmap f l) (fmap f r)
instance Foldable (Node v) where
foldMap f (Leaf v a) = f a
foldMap f (Node _ _ l r) = foldMap f l `mappend` foldMap f r
instance Traversable (Node v) where
traverse f (Leaf v x) = Leaf v <$> f x
traverse f (Node i p l r) = Node i p <$> traverse f l <*> traverse f r
instance NFData a => NFData (Node v a) where
rnf (Leaf x1 x2) = x1 `seq` rnf x2 `seq` ()
rnf (Node x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
data Tree v a = Empty | Tree (Node v a)
-- instance (Vector v Double, Show (v Double), Show a) => Show (Tree v a) where
-- show (Node i b l r) = "Node " ++ show i ++ " " ++ show b ++ " (" ++ show l ++ ")" ++ " (" ++ show r ++ ")"
-- show (Leaf v a) = "Leaf (" ++ show v ++ ") (" ++ show a ++ ")"
instance Functor (Tree v) where
fmap _ Empty = Empty
fmap f (Tree n) = Tree (fmap f n)
instance Foldable (Tree v) where
foldMap _ Empty = mempty
foldMap f (Tree n) = foldMap f n
instance Traversable (Tree v) where
traverse _ Empty = pure Empty
traverse f (Tree n) = Tree <$> traverse f n
instance NFData a => NFData (Tree v a) where
rnf Empty = ()
rnf (Tree x1) = rnf x1 `seq` ()
transposeV :: Vector v a => [v a] -> [v a]
transposeV [] = []
transposeV vs@(v0:_) = map f [0..V.length v0 - 1]
where f i = V.fromList (map (\v -> v ! i) vs)
empty :: Tree v a
empty = Empty
errorEmpty :: String -> a
errorEmpty who = error $ who ++ ": Empty tree"
fromList :: (Vector v Double) => [(v Double, a)] -> Tree v a
fromList [] = Empty
fromList xs@((v0, _):_) = Tree (nodeFromList (V.length v0) xs)
nodeFromList :: (Vector v Double) => Int -> [(v Double, a)] -> Node v a
nodeFromList _ [(v, a)] = Leaf v a
nodeFromList k xs = build k 0 xs
where
at v i | V.length v < k = error "fromList: Vector too short"
| otherwise = v ! i
build k depth xs =
let axis = depth `mod` k
xs' = List.sortBy (comparing (flip (!) axis . fst)) xs
median = length xs' `div` 2
in Node axis (fst (xs' !! median) `at` axis)
(nodeFromList k (take median xs'))
(nodeFromList k (drop median xs'))
-- fromList [] = Empty
-- fromList [(v, a)] = Leaf v [a]
-- fromList xs =
-- let
-- dims = transposeV (map fst xs)
-- meanVars = filter (\(_, (_, v)) -> v > 0) (zip [0..] (map meanVariance dims))
-- in
-- if null meanVars
-- then Leaf (fst (head xs)) (map snd xs)
-- else let (minVarDim, (minMean, _)) = List.minimumBy (comparing (snd.snd)) meanVars
-- (left, right) = List.partition (\(v, _) -> v ! minVarDim < minMean) xs
-- in Node minVarDim minMean (fromList (traceShow left left)) (fromList right)
elems :: Tree v a -> [a]
elems = toList
type Distance v = v Double -> v Double -> Double
sqr :: Double -> Double
{-# INLINE sqr #-}
sqr x = x * x
sqrAxisDistance :: Vector v Double => Int -> Double -> v Double -> Double
{-# INLINE sqrAxisDistance #-}
sqrAxisDistance i x v = sqr (v ! i - x)
sqrEuclidianDistance :: Vector v Double => v Double -> v Double -> Double
{-# INLINE sqrEuclidianDistance #-}
sqrEuclidianDistance a b = loop 0 0 (V.length a `min` V.length b)
where
loop !acc !i !n
| i >= n = acc
| otherwise = let x = (a V.! i) - (b V.! i) in loop (acc + x*x) (i+1) n
closest :: Vector v Double => Distance v -> v Double -> Tree v a -> Maybe ((v Double, a), Double)
closest _ _ Empty = Nothing
closest dist point (Tree node) = Just $ second sqrt $ go node (error "closest: current best node uninitialized") (1/0)
where
go node best bestDist =
case node of
Leaf v a ->
let bestDist' = point `dist` v
in if bestDist' < bestDist
then ((v, a), bestDist')
else (best, bestDist)
Node dim dimValue left right ->
let (nearChild, farChild) = if point ! dim < dimValue then (left, right) else (right, left)
(best', bestDist') = go nearChild best bestDist
in if sqrAxisDistance dim dimValue point < bestDist'
then go farChild best' bestDist'
else (best', bestDist')
withinRadius :: Vector v Double => Distance v -> v Double -> Double -> Tree v a -> [((v Double, a), Double)]
withinRadius _ _ _ Empty = []
withinRadius dist point radius (Tree node) = go node []
where
sqrRadius = sqr radius
go node result =
case node of
Leaf v a ->
let d = point `dist` v
in if d < sqrRadius
then ((v, a), sqrt d) : result
else result
Node dim dimValue left right ->
let (nearChild, farChild) = if point ! dim < dimValue then (left, right) else (right, left)
result' = go nearChild result
in if sqrAxisDistance dim dimValue point < sqrRadius
then go farChild result'
else result'
| kaoskorobase/mescaline | lib/mescaline/Data/KDTree.hs | gpl-3.0 | 6,328 | 0 | 16 | 2,095 | 2,166 | 1,138 | 1,028 | 121 | 5 |
module Monite.Test (
runTests
, runTest
, process
) where
import Monite.Interpret
import System.Process
import System.IO
import System.Exit (exitFailure)
import System.Directory (setCurrentDirectory, getDirectoryContents, removeFile)
import Control.Monad.IO.Class
import Control.Monad (foldM)
import Data.List (isSuffixOf)
-- | Run all tests using the supplied binary, and the directory to the test
-- files
runTests :: FilePath -> FilePath -> IO ()
runTests bin dirTests = do
-- Get all files in the test directory
files <- getDirectoryContents dirTests
-- Filter out the scripts, and create their relative paths
let scripts = map (dirTests ++) $ filter (".sh" `isSuffixOf`) files
-- Test all the scripts
passed <- foldM test True scripts
if passed then return () else exitFailure
where
test :: Bool -> FilePath -> IO Bool
test b path = do
passed <- runTest bin path
return $ b && passed
-- | Run a test scripts, and check if the output is the same as the expected
-- output
runTest :: FilePath -> FilePath -> IO Bool
runTest bin path = do
(fp, h) <- openTempFile "." ".temp"
(_, _, _, p) <- createProcess $ process bin path (UseHandle h)
waitForProcess p
h1 <- openFile fp ReadMode
output <- hGetContents h1
putStr output
eOutput <- readFile $ (path ++ ".output")
putStr eOutput
removeFile fp
if output == eOutput then return True
else do putStrLn ("----------------------------------------------------")
putStrLn ("-- Testfile: " ++ path ++ " failed")
putStrLn ("----------------------------------------------------")
putStrLn ("Output:\n" ++ output)
putStrLn ("Expected:\n" ++ eOutput)
return False
-- | Spawn a process with the moniteshell running a script file
process :: FilePath -> FilePath -> StdStream -> CreateProcess
process bin t output = CreateProcess { cmdspec = RawCommand bin [t],
cwd = Nothing,
env = Nothing,
std_in = Inherit,
std_out = output,
std_err = Inherit,
close_fds = False,
create_group = False,
delegate_ctlc = False}
| sebiva/monite | src/Monite/Test.hs | gpl-3.0 | 2,285 | 0 | 13 | 638 | 565 | 296 | 269 | 50 | 2 |
{-# OPTIONS_GHC -optc-DDBUS_API_SUBJECT_TO_CHANGE #-}
{-# LINE 1 "DBus/Connection.hsc" #-}
-- HDBus -- Haskell bindings for D-Bus.
{-# LINE 2 "DBus/Connection.hsc" #-}
-- Copyright (C) 2006 Evan Martin <[email protected]>
{-# LINE 5 "DBus/Connection.hsc" #-}
{-# LINE 6 "DBus/Connection.hsc" #-}
module DBus.Connection (
-- * Connection Basics
Connection,
BusType(..),
busGet, busConnectionUnref,
send, sendWithReplyAndBlock,
flush, close,
withConnection,
-- * Main Loop Management
readWriteDispatch, addFilter, addMatch,
RequestNameReply(..),
busRequestName,
) where
import Control.Exception (bracket)
import Control.Monad (when)
import Foreign
import Foreign.C.String
import Foreign.C.Types (CInt)
import DBus.Internal
import DBus.Message
import DBus.Shared
type Connection = ForeignPtr ConnectionTag
-- |Multiple buses may be active simultaneously on a single system.
-- The BusType indicates which one to use.
data BusType = Session -- ^The session bus is restricted to the user's current
-- GNOME session.
| System -- ^This bus is system-wide.
| Starter -- ^The bus that started us, if any.
foreign import ccall unsafe "&dbus_connection_unref"
connection_unref :: FunPtr (ConnectionP -> IO ())
connectionPTOConnection conn = do
when (conn == nullPtr) $ fail "null connection"
newForeignPtr connection_unref conn
-- |Force the dereference of a connection. Note that this is usually not
-- necessary since the connections are garbage collected automatically.
busConnectionUnref :: Connection -> IO ()
busConnectionUnref = finalizeForeignPtr
foreign import ccall unsafe "dbus_bus_get"
bus_get :: CInt -> ErrorP -> IO ConnectionP
-- |Connect to a standard bus.
busGet :: BusType -> IO Connection
busGet bt = withErrorP (bus_get (toInt bt)) >>= connectionPTOConnection where
toInt Session = 0
{-# LINE 61 "DBus/Connection.hsc" #-}
toInt System = 1
{-# LINE 62 "DBus/Connection.hsc" #-}
toInt Starter = 2
{-# LINE 63 "DBus/Connection.hsc" #-}
data RequestNameReply = PrimaryOwner | InQueue | Exists | AlreadyOwner
foreign import ccall unsafe "dbus_bus_request_name"
bus_request_name :: ConnectionP -> CString -> CInt -> ErrorP -> IO CInt
busRequestName :: Connection -> String -> [Int] -> IO RequestNameReply
busRequestName conn name flags =
withForeignPtr conn $ \conn -> do
withCString name $ \cname -> do
ret <- withErrorP (bus_request_name conn cname 2)
return $ fromInt ret where
fromInt 1 = PrimaryOwner
{-# LINE 74 "DBus/Connection.hsc" #-}
fromInt 2 = InQueue
{-# LINE 75 "DBus/Connection.hsc" #-}
fromInt 3 = Exists
{-# LINE 76 "DBus/Connection.hsc" #-}
fromInt 4 = AlreadyOwner
{-# LINE 77 "DBus/Connection.hsc" #-}
-- |Close a connection. A connection must be closed before its last
-- reference disappears.
-- You may not close a connection created with @busGet@.
foreign import ccall unsafe "dbus_connection_close"
connection_close :: ConnectionP -> IO ()
close :: Connection -> IO ()
close conn = withForeignPtr conn connection_close
-- |Open a connection and run an IO action, ensuring it is properly closed when
-- you're done.
withConnection :: BusType -> (Connection -> IO a) -> IO a
withConnection bt = bracket (busGet bt) busConnectionUnref
foreign import ccall unsafe "dbus_connection_send"
connection_send :: ConnectionP -> MessageP -> Ptr Word32 -> IO Bool
-- |Adds a 'Message' to the outgoing message queue.
send :: Connection -> Message
-> Word32 -- ^Serial.
-> IO Word32 -- ^Returned serial.
send conn msg serial =
withForeignPtr conn $ \conn -> do
withForeignPtr msg $ \msg -> do
with serial $ \serial -> do
catchOom $ connection_send conn msg serial
peek serial
type PendingCallTag = ()
type PendingCallP = Ptr PendingCallTag
type PendingCall = ForeignPtr PendingCallTag
foreign import ccall unsafe "dbus_connection_send_with_reply"
connection_send_with_reply :: ConnectionP -> MessageP
-> Ptr PendingCallP -> IO Bool
foreign import ccall unsafe "&dbus_pending_call_unref"
pending_call_unref :: FunPtr (PendingCallP -> IO ())
sendWithReply :: Connection -> Message
-> Maybe Int -- ^Optional timeout in milliseconds.
-> IO PendingCall
-- XXX a NULL PendingCall lets us track timeout errors
sendWithReply conn msg timeout = do
withForeignPtr conn $ \conn -> do
withForeignPtr msg $ \msg -> do
with (nullPtr :: PendingCallP) $ \ppcp -> do
catchOom $ connection_send_with_reply conn msg ppcp
throwIfNull "null PPendingCall" (return ppcp)
pcp <- peek ppcp
throwIfNull "null PendingCall" (return pcp)
newForeignPtr pending_call_unref pcp
foreign import ccall unsafe "dbus_connection_send_with_reply_and_block"
connection_send_with_reply_and_block :: ConnectionP -> MessageP -> Int -> ErrorP -> IO MessageP
sendWithReplyAndBlock :: Connection -> Message
-> Int -- ^Timeout in milliseconds.
-> IO Message
sendWithReplyAndBlock conn msg timeout =
withForeignPtr conn $ \conn -> do
withForeignPtr msg $ \msg -> do
ret <- withErrorP $ connection_send_with_reply_and_block conn msg timeout
messagePToMessage ret False
foreign import ccall unsafe "dbus_connection_flush"
connection_flush :: ConnectionP -> IO ()
-- |Block until all pending messages have been sent.
flush :: Connection -> IO ()
flush conn = withForeignPtr conn connection_flush
foreign import ccall "dbus_connection_read_write_dispatch"
connection_read_write_dispatch :: ConnectionP -> Int -> IO Bool
-- |Block until a message is read or written, then return True unless a
-- disconnect message is received.
readWriteDispatch :: Connection
-> Int -- ^Timeout, in milliseconds.
-> IO Bool
readWriteDispatch conn timeout = do
withForeignPtr conn $ \conn ->
connection_read_write_dispatch conn timeout
-- "a" here is the type of the callback function.
data FreeClosure a = FreeClosure { fcCallback :: FunPtr a,
fcFree :: FunPtr (FreeFunction a) }
type FreeFunction a = StablePtr (FreeClosure a) -> IO ()
foreign import ccall "wrapper"
wrapFreeFunction :: FreeFunction a -> IO (FunPtr (FreeFunction a))
mkFreeClosure :: FunPtr a -> IO (FreeClosure a)
mkFreeClosure callback = do
freef <- wrapFreeFunction freeFunction
return $ FreeClosure callback freef
where
freeFunction :: FreeFunction a
freeFunction sptr = do
(FreeClosure cb freef) <- deRefStablePtr sptr
freeStablePtr sptr
freeHaskellFunPtr cb
freeHaskellFunPtr freef -- XXX we are freeing ourselves.
-- XXX this is officially not ok,
-- XXX but it seems like it'll do.
type HandleMessageFunction = ConnectionP -> MessageP -> Ptr () -> IO CInt
foreign import ccall "wrapper"
wrapHandleMessageFunction :: HandleMessageFunction
-> IO (FunPtr HandleMessageFunction)
foreign import ccall "dbus_connection_add_filter"
connection_add_filter :: ConnectionP
-> FunPtr HandleMessageFunction -> StablePtr a
-> FunPtr (StablePtr a -> IO ()) -> IO Bool
addFilter :: Connection
-> (Message -> IO Bool) -- ^A callback that returns True if
-- the message has been handled.
-> IO ()
addFilter conn callback = do
withForeignPtr conn $ \conn -> do
hmf <- wrapHandleMessageFunction handleMessageFunction
closure <- mkFreeClosure hmf
pclosure <- newStablePtr closure
catchOom $ connection_add_filter conn hmf pclosure (fcFree closure)
where
handleMessageFunction :: HandleMessageFunction
handleMessageFunction connp messagep datap = do
message <- messagePToMessage messagep True
res <- callback message
if res then return 0
{-# LINE 205 "DBus/Connection.hsc" #-}
else return 1
{-# LINE 206 "DBus/Connection.hsc" #-}
foreign import ccall "dbus_bus_add_match"
bus_add_match :: ConnectionP -> CString -> ErrorP -> IO ()
addMatch :: Connection
-> Bool -- ^Whether to block waiting for a response, allowing
-- us to raise an exception if a response never comes.
-> String -> IO ()
addMatch conn block rule =
withForeignPtr conn $ \conn ->
withCString rule $ \rule -> do
if block
then withErrorP $ bus_add_match conn rule
else bus_add_match conn rule nullPtr
-- vim: set ts=2 sw=2 tw=72 et ft=haskell :
| hamaxx/unity-2d-for-xmonad | xmonad-files/DBus-0.4/dist/build/DBus/Connection.hs | gpl-3.0 | 8,651 | 0 | 21 | 1,958 | 1,808 | 927 | 881 | 159 | 4 |
{-# 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.Autoscaler.Autoscalers.Get
-- 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)
--
-- Gets the specified Autoscaler resource.
--
-- /See:/ <http://developers.google.com/compute/docs/autoscaler Google Compute Engine Autoscaler API Reference> for @autoscaler.autoscalers.get@.
module Network.Google.Resource.Autoscaler.Autoscalers.Get
(
-- * REST Resource
AutoscalersGetResource
-- * Creating a Request
, autoscalersGet
, AutoscalersGet
-- * Request Lenses
, agProject
, agZone
, agAutoscaler
) where
import Network.Google.Autoscaler.Types
import Network.Google.Prelude
-- | A resource alias for @autoscaler.autoscalers.get@ method which the
-- 'AutoscalersGet' request conforms to.
type AutoscalersGetResource =
"autoscaler" :>
"v1beta2" :>
"projects" :>
Capture "project" Text :>
"zones" :>
Capture "zone" Text :>
"autoscalers" :>
Capture "autoscaler" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Autoscaler
-- | Gets the specified Autoscaler resource.
--
-- /See:/ 'autoscalersGet' smart constructor.
data AutoscalersGet = AutoscalersGet'
{ _agProject :: !Text
, _agZone :: !Text
, _agAutoscaler :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'AutoscalersGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'agProject'
--
-- * 'agZone'
--
-- * 'agAutoscaler'
autoscalersGet
:: Text -- ^ 'agProject'
-> Text -- ^ 'agZone'
-> Text -- ^ 'agAutoscaler'
-> AutoscalersGet
autoscalersGet pAgProject_ pAgZone_ pAgAutoscaler_ =
AutoscalersGet'
{ _agProject = pAgProject_
, _agZone = pAgZone_
, _agAutoscaler = pAgAutoscaler_
}
-- | Project ID of Autoscaler resource.
agProject :: Lens' AutoscalersGet Text
agProject
= lens _agProject (\ s a -> s{_agProject = a})
-- | Zone name of Autoscaler resource.
agZone :: Lens' AutoscalersGet Text
agZone = lens _agZone (\ s a -> s{_agZone = a})
-- | Name of the Autoscaler resource.
agAutoscaler :: Lens' AutoscalersGet Text
agAutoscaler
= lens _agAutoscaler (\ s a -> s{_agAutoscaler = a})
instance GoogleRequest AutoscalersGet where
type Rs AutoscalersGet = Autoscaler
type Scopes AutoscalersGet =
'["https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly"]
requestClient AutoscalersGet'{..}
= go _agProject _agZone _agAutoscaler (Just AltJSON)
autoscalerService
where go
= buildClient (Proxy :: Proxy AutoscalersGetResource)
mempty
| rueshyna/gogol | gogol-autoscaler/gen/Network/Google/Resource/Autoscaler/Autoscalers/Get.hs | mpl-2.0 | 3,497 | 0 | 16 | 837 | 463 | 276 | 187 | 72 | 1 |
{-# LANGUAGE OverlappingInstances #-}
module Pkg.PParser where
import Text.Trifecta hiding (span, stringLiteral, charLiteral, natural, symbol, char, string, whiteSpace)
import Idris.Core.TT
import Idris.REPL
import Idris.AbsSyntaxTree
import Idris.ParseHelpers
import Paths_idris
import Control.Monad.State.Strict
import Control.Applicative
type PParser = StateT PkgDesc IdrisInnerParser
data PkgDesc = PkgDesc { pkgname :: String,
libdeps :: [String],
objs :: [String],
makefile :: Maybe String,
idris_opts :: [Opt],
sourcedir :: String,
modules :: [Name],
idris_main :: Name,
execout :: Maybe String
}
deriving Show
instance TokenParsing PParser where
someSpace = many (simpleWhiteSpace <|> singleLineComment <|> multiLineComment) *> pure ()
defaultPkg = PkgDesc "" [] [] Nothing [] "" [] (sUN "") Nothing
parseDesc :: FilePath -> IO PkgDesc
parseDesc fp = do p <- readFile fp
case runparser pPkg defaultPkg fp p of
Failure err -> fail (show err)
Success x -> return x
pPkg :: PParser PkgDesc
pPkg = do reserved "package"; p <- identifier
st <- get
put (st { pkgname = p })
some pClause
st <- get
eof
return st
pClause :: PParser ()
pClause = do reserved "executable"; lchar '=';
exec <- iName []
st <- get
put (st { execout = Just (show exec) })
<|> do reserved "main"; lchar '=';
main <- iName []
st <- get
put (st { idris_main = main })
<|> do reserved "sourcedir"; lchar '=';
src <- identifier
st <- get
put (st { sourcedir = src })
<|> do reserved "opts"; lchar '=';
opts <- stringLiteral
st <- get
let args = parseArgs (words opts)
put (st { idris_opts = args })
<|> do reserved "modules"; lchar '=';
ms <- sepBy1 (iName []) (lchar ',')
st <- get
put (st { modules = modules st ++ ms })
<|> do reserved "libs"; lchar '=';
ls <- sepBy1 identifier (lchar ',')
st <- get
put (st { libdeps = libdeps st ++ ls })
<|> do reserved "objs"; lchar '=';
ls <- sepBy1 identifier (lchar ',')
st <- get
put (st { objs = libdeps st ++ ls })
<|> do reserved "makefile"; lchar '=';
mk <- iName []
st <- get
put (st { makefile = Just (show mk) })
| DanielWaterworth/Idris-dev | src/Pkg/PParser.hs | bsd-3-clause | 2,772 | 0 | 20 | 1,089 | 909 | 452 | 457 | 71 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
module Court.Builder
( builder
, buildNext
) where
import Control.Concurrent
import Control.Exception
import Control.Monad
import Data.List
import Data.Maybe
import Data.Time
import System.Directory
import System.FilePath
import System.IO
import System.Locale
import System.Process
import Court.Job
import Court.Options
import Court.Queue
import Court.Result
import Court.Utils
builder :: Options -> TVar Queue -> IO ()
builder opts queueTVar = builder' []
where
builder' :: [MVar ()] -> IO ()
builder' mvars = do
mJob <- takeNextJob queueTVar
mvars' <- case mJob of
Nothing -> do
threadDelay $ 1000 * 1000
return mvars
Just job -> builder'' job mvars
builder' mvars'
builder'' :: Job -> [MVar ()] -> IO [MVar ()]
builder'' job mvars = do
mvars' <- cleanMVars mvars
if length mvars' >= optThreads opts
then do
threadDelay $ 5 * 1000 * 1000
builder'' job mvars'
else do
mvar' <- newEmptyMVar
_ <- forkIO $ buildNext opts job mvar'
return $ mvar' : mvars'
cleanMVars :: [MVar ()] -> IO [MVar ()]
cleanMVars mvars = do
mMVars <- forM mvars $ \mvar -> do
mres <- tryTakeMVar mvar
return $ maybe (Just mvar) (const Nothing) mres
return $ catMaybes mMVars
buildNext :: Options -> Job -> MVar () -> IO ()
buildNext opts job mvar = handle errorHandler $ do
hPutStrLn stderr $ "Building " ++ show job ++ " ..."
(buildPath, outputPath, processHandle) <- spawnBuild job
exitCode <- waitForProcess processHandle
output <- readFile outputPath
let result = Result
{ resultExitCode = exitCode
, resultOutput = output
, resultPath = buildPath
}
modifyGlobalResults opts $ changeResults result
modifyLocalResults job $ changeResults result
cleanBuilds 20 $ jobProjectPath job
putMVar mvar ()
where
changeResults :: Result -> Results -> Results
changeResults result (Results results) = Results $ take 20 $ result : results
errorHandler :: SomeException -> IO ()
errorHandler e = do
hPutStrLn stderr $ "ERROR: " ++ show e
putMVar mvar ()
spawnBuild :: Job -> IO (FilePath, FilePath, ProcessHandle)
spawnBuild job = do
now <- getCurrentTime
let buildDir = "build." ++ formatTime defaultTimeLocale "%Y%m%d%H%M%S" now
executablePath = jobProjectPath job </> "build"
buildPath = jobProjectPath job </> buildDir
outputPath = buildPath </> "build.out"
createDirectory buildPath
(inR, inW) <- createPipeHandles
hClose inW
stdout' <- openFile outputPath ReadWriteMode
processHandle <- runProcess
executablePath (jobArguments job) (Just buildPath) Nothing
(Just inR) (Just stdout') Nothing
return (buildPath, outputPath, processHandle)
cleanBuilds :: Int -> FilePath -> IO ()
cleanBuilds n path = do
items <- getDirectoryContents path
mapM_ (removeDirectoryRecursive . (path </>))
. drop n
. sortBy (\a b -> b `compare` a)
. filter ("build." `isPrefixOf`)
$ items
| thoferon/court | src/Court/Builder.hs | bsd-3-clause | 3,173 | 0 | 17 | 822 | 1,028 | 500 | 528 | 91 | 3 |
module System.HDFS.HDFSClient (
Config,
hdfsListFiles, Location(_path),
hdfsReadCompleteFile,
hdfsFileBlockLocations, hdfsFileDistribution,
hdfsWriteNewFile
) where
import Control.Exception (catch, SomeException)
import Data.Bool (bool)
import qualified Data.Int as I
import qualified Data.Text.Lazy as TL
import Data.Vector (toList)
import qualified GHC.IO.Handle.Types as GHC
import qualified Hadoopfs_Types as Types
import qualified Network as N
import qualified ThriftHadoopFileSystem_Client as C
import qualified Thrift.Transport as T
import qualified Thrift.Transport.Handle as H
import Thrift.Protocol.Binary (BinaryProtocol(..))
import System.HDFS.InternalUtils
type Config = (String, Int)
type Path = String
data Location = Location {
_protocolPart :: String,
_path :: Path
} deriving (Show)
{-|
List file names at path. The HDFS will return full qualified file names including protocol, host and port.
For simplicity, these can be used for opening files etc without stripping, but will access the referenced
host which is sometimes undesirable. Constructing the prototol part should not be done manually, since port and hostname are local knowledge
of the thrift server, strictly speaking.
|-}
hdfsListFiles :: Config -> Path -> IO [Location]
hdfsListFiles config path = do
putStrLn $ "looking at " ++ path
res <- listStatus config path
return $ map convertFileStatusToLocation res
where convertFileStatusToLocation = uncurry Location . splitLocation . TL.unpack . Types.fileStatus_path
{-|
Read file content of path
- throws an exception if path does not point at a regular file.
|-}
hdfsReadCompleteFile :: Config -> Path -> IO TL.Text
hdfsReadCompleteFile config path =
forRegularFilePath config path $ \thriftPath fileSize ->
withThriftChannelsForRead config (
\channels -> withThriftHandleForReading channels thriftPath (
\thriftHandle -> C.read channels thriftHandle 0 (fromIntegral fileSize) -- TODO: unchecked conversion Int64 to Int32
))
{-|
Get the data locations for a file
- throws an exception if path does not point at a regular file.
|-}
hdfsFileBlockLocations :: Config -> Path -> IO [Types.BlockLocation]
hdfsFileBlockLocations config path =
forRegularFilePath config path $ \thriftPath fileSize ->
withThriftChannelsForRead config (
\channels -> C.getFileBlockLocations channels thriftPath 0 fileSize >>= return . toList)
hdfsFileDistribution :: Config -> Path -> IO [(String, Int)]
hdfsFileDistribution config path = do
blockLocations <- hdfsFileBlockLocations config path
return $ groupCount (concat $ map hostNames blockLocations)
where
hostNames :: Types.BlockLocation -> [String]
hostNames = map TL.unpack . toList . Types.blockLocation_names
hdfsWriteNewFile :: Config -> Path -> TL.Text -> IO ()
hdfsWriteNewFile config path content =
withThriftChannelsForWrite config (
\channels -> withThriftHandleForWriteNew channels (toThriftPath path) (
\thriftHandle -> C.write channels thriftHandle content >>= return . bool (error "unknown write handle") ()
))
-- internals
forRegularFilePath :: Config -> Path -> (Types.Pathname -> I.Int64 -> IO a) -> IO a
forRegularFilePath config path action = do
fileStatus <- listStatus config path
if length fileStatus /= 1
then error $ path ++ " is not a regular file: " ++ (show fileStatus)
else action (toThriftPath path) (filesize fileStatus)
where
filesize = Types.fileStatus_length . head
listStatus :: Config -> Path -> IO [Types.FileStatus]
listStatus config path = withThriftChannelsForRead config (\channels -> C.listStatus channels (toThriftPath path)) >>= return . toList
toThriftPath :: String -> Types.Pathname
toThriftPath = Types.Pathname . TL.pack
type Channels = (BinaryProtocol GHC.Handle,
BinaryProtocol GHC.Handle) -- TODO generalize?
withThriftChannelsForRead :: Config -> (Channels -> IO result) -> IO result
withThriftChannelsForRead = withThriftChannels T.tClose
withThriftChannelsForWrite :: Config -> (Channels -> IO result) -> IO result
withThriftChannelsForWrite = withThriftChannels T.tClose
type CloseHandleAction = (GHC.Handle -> IO ())
withThriftChannels :: CloseHandleAction -> Config -> (Channels -> IO result) -> IO result
withThriftChannels closeAction (host, port) action = do
handle <- openHandle host port
res <- action (BinaryProtocol handle, BinaryProtocol handle)
closeAction handle
return res
openHandle :: String -> Int -> IO GHC.Handle
openHandle host port = H.hOpen (host, N.PortNumber (toEnum port)) `catch` wrapException
where
wrapException :: SomeException -> a
wrapException e = error $ "Cannot connect to "++host++":"++(show port)++": "++(show e)
withThriftHandleForReading :: Channels -> Types.Pathname -> (Types.ThriftHandle -> IO result) -> IO result
withThriftHandleForReading = withThriftHandle C.open C.closeReadHandle
withThriftHandleForWriteNew :: Channels -> Types.Pathname -> (Types.ThriftHandle -> IO result) -> IO result
withThriftHandleForWriteNew = withThriftHandle C.create C.closeWriteHandle
type CloseChannelAction = Channels -> Types.ThriftHandle -> IO Bool
withThriftHandle :: (Channels -> Types.Pathname -> IO Types.ThriftHandle) -> CloseChannelAction -> Channels -> Types.Pathname -> (Types.ThriftHandle -> IO result) -> IO result
withThriftHandle allocationMethod closeAction channels hdfsPath action = do
thriftHandle <- allocationMethod channels hdfsPath
res <- action thriftHandle
_ <- closeAction channels thriftHandle
return res
groupCount :: (Eq key) => [key] -> [(key, Int)]
groupCount = foldr groupCount' []
where
groupCount' :: (Eq key) => key -> [(key, Int)] -> [(key, Int)]
groupCount' key [] = [(key, 1)]
groupCount' key (next:collected) = if (fst next == key) then (fst next, snd next +1):collected else next:(groupCount' key collected)
{-
updateOrInsert :: (Eq key) => (value -> value -> value) -> [(key, value)] -> (key, value) -> [(key, value)]
updateOrInsert _ [] entry = [entry]
updateOrInsert updater (next:rest) entry =
if (fst entry == fst next)
then (fst next, updater (snd next) (snd entry)):rest
else next:(updateOrInsert updater rest entry)
-}
| michaxm/haskell-hdfs-thrift-client | src/System/HDFS/HDFSClient.hs | bsd-3-clause | 6,235 | 0 | 15 | 1,029 | 1,605 | 850 | 755 | 99 | 3 |
module Problem147 where
main :: IO ()
main = print . sum $ [ count (x, y) | x <- [1 .. m], y <- [1 .. n] ]
where
m = 47
n = 43
sizes (m, n) = [ (x, y) | x <- [1 .. 2 * m], y <- [1 .. 2 * n], x + y <= 2 * min m n ]
count sz@(m, n) = countDiamonds sz + m * n * (m + 1) * (n + 1) `div` 4
countDiamonds sz = sum . map (countDiamond sz) $ sizes sz
countDiamond (m, n) (a, b) =
(m - off1 + 1)
* (n + 1 - (if even b then off1 else off2))
+ (m - off2 + 1)
* (n + 1 - (if odd b then off1 else off2))
where
off1 = div (a + 1) 2 + div (b + 1) 2 -- offset when diamond vertex on edge
off2 = div a 2 + div b 2 + 1 -- offset when diamond vertex not on edge
| adityagupta1089/Project-Euler-Haskell | src/problems/Problem147.hs | bsd-3-clause | 698 | 0 | 12 | 235 | 409 | 223 | 186 | 15 | 3 |
import Criterion.Main
--
import Data.Sound
import Data.Sound.WAVE hiding (ByteString)
test :: Sound
test = sine 3 1 100 0
main :: IO ()
main = defaultMain [
bgroup "Encoding"
[ bench "8 bits per sample" $ nf (\n -> encode $ fromSound n test) 8
, bench "16 bits per sample" $ nf (\n -> encode $ fromSound n test) 16
, bench "32 bits per sample" $ nf (\n -> encode $ fromSound n test) 32
]
]
| Daniel-Diaz/wavy | bench/encoding.hs | bsd-3-clause | 422 | 0 | 14 | 111 | 165 | 86 | 79 | 11 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- | Server types and operations for items that don't involve server state
-- nor our custom monads.
module Game.LambdaHack.Server.ItemRev
( ItemRev, buildItem, newItem, UniqueSet
-- * Item discovery types
, DiscoveryKindRev, serverDiscos, ItemSeedDict
-- * The @FlavourMap@ type
, FlavourMap, emptyFlavourMap, dungeonFlavourMap
) where
import Prelude ()
import Prelude.Compat
import Control.Exception.Assert.Sugar
import Control.Monad
import Data.Binary
import qualified Data.EnumMap.Strict as EM
import qualified Data.EnumSet as ES
import qualified Data.HashMap.Strict as HM
import qualified Data.Ix as Ix
import Data.List (delete)
import qualified Data.Set as S
import Game.LambdaHack.Common.Flavour
import Game.LambdaHack.Common.Frequency
import Game.LambdaHack.Common.Item
import qualified Game.LambdaHack.Common.Kind as Kind
import Game.LambdaHack.Common.Misc
import Game.LambdaHack.Common.Msg
import Game.LambdaHack.Common.Random
import Game.LambdaHack.Content.ItemKind (ItemKind)
import qualified Game.LambdaHack.Content.ItemKind as IK
-- | The reverse map to @DiscoveryKind@, needed for item creation.
type DiscoveryKindRev = EM.EnumMap (Kind.Id ItemKind) ItemKindIx
-- | The map of item ids to item seeds, needed for item creation.
type ItemSeedDict = EM.EnumMap ItemId ItemSeed
type UniqueSet = ES.EnumSet (Kind.Id ItemKind)
serverDiscos :: Kind.COps -> Rnd (DiscoveryKind, DiscoveryKindRev)
serverDiscos Kind.COps{coitem=Kind.Ops{obounds, ofoldrWithKey}} = do
let ixs = map toEnum $ take (Ix.rangeSize obounds) [0..]
shuffle :: Eq a => [a] -> Rnd [a]
shuffle [] = return []
shuffle l = do
x <- oneOf l
(x :) <$> shuffle (delete x l)
shuffled <- shuffle ixs
let f ik _ (ikMap, ikRev, ix : rest) =
(EM.insert ix ik ikMap, EM.insert ik ix ikRev, rest)
f ik _ (ikMap, _, []) =
assert `failure` "too short ixs" `twith` (ik, ikMap)
(discoS, discoRev, _) =
ofoldrWithKey f (EM.empty, EM.empty, shuffled)
return (discoS, discoRev)
-- | Build an item with the given stats.
buildItem :: FlavourMap -> DiscoveryKindRev -> Kind.Id ItemKind -> ItemKind
-> LevelId
-> Item
buildItem (FlavourMap flavour) discoRev ikChosen kind jlid =
let jkindIx = discoRev EM.! ikChosen
jsymbol = IK.isymbol kind
jname = IK.iname kind
jflavour =
case IK.iflavour kind of
[fl] -> fl
_ -> flavour EM.! ikChosen
jfeature = IK.ifeature kind
jweight = IK.iweight kind
in Item{..}
-- | Generate an item based on level.
newItem :: Kind.COps -> FlavourMap -> DiscoveryKindRev -> UniqueSet
-> Freqs ItemKind -> Int -> LevelId -> AbsDepth -> AbsDepth
-> Rnd (Maybe ( ItemKnown, ItemFull, ItemDisco
, ItemSeed, GroupName ItemKind ))
newItem Kind.COps{coitem=Kind.Ops{ofoldrGroup}}
flavour discoRev uniqueSet itemFreq lvlSpawned jlid
ldepth@(AbsDepth ldAbs) totalDepth@(AbsDepth depth) = do
-- Effective generation depth of actors (not items) increases with spawns.
let scaledDepth = ldAbs * 10 `div` depth
numSpawnedCoeff = lvlSpawned `div` 2
ldSpawned = max ldAbs -- the first fast spawns are of the nominal level
$ min depth
$ ldAbs + numSpawnedCoeff - scaledDepth
findInterval _ x1y1 [] = (x1y1, (11, 0))
findInterval ld x1y1 ((x, y) : rest) =
if fromIntegral ld * 10 <= x * fromIntegral depth
then (x1y1, (x, y))
else findInterval ld (x, y) rest
linearInterpolation ld dataset =
-- We assume @dataset@ is sorted and between 0 and 10.
let ((x1, y1), (x2, y2)) = findInterval ld (0, 0) dataset
in ceiling
$ fromIntegral y1
+ fromIntegral (y2 - y1)
* (fromIntegral ld * 10 - x1 * fromIntegral depth)
/ ((x2 - x1) * fromIntegral depth)
f _ _ _ ik _ acc | ik `ES.member` uniqueSet = acc
f itemGroup q p ik kind acc =
-- Don't consider lvlSpawned for uniques.
let ld = if IK.Unique `elem` IK.iaspects kind then ldAbs else ldSpawned
rarity = linearInterpolation ld (IK.irarity kind)
in (q * p * rarity, ((ik, kind), itemGroup)) : acc
g (itemGroup, q) = ofoldrGroup itemGroup (f itemGroup q) []
freqDepth = concatMap g itemFreq
freq = toFreq ("newItem ('" <> tshow ldSpawned <> ")") freqDepth
if nullFreq freq then return Nothing
else do
((itemKindId, itemKind), itemGroup) <- frequency freq
-- Number of new items/actors unaffected by number of spawned actors.
itemN <- castDice ldepth totalDepth (IK.icount itemKind)
seed <- fmap toEnum random
let itemBase = buildItem flavour discoRev itemKindId itemKind jlid
itemK = max 1 itemN
itemTimer = []
itemDiscoData = ItemDisco {itemKindId, itemKind, itemAE = Just iae}
itemDisco = Just itemDiscoData
-- Bonuses on items/actors unaffected by number of spawned actors.
iae = seedToAspectsEffects seed itemKind ldepth totalDepth
itemFull = ItemFull {..}
return $ Just ( (jkindIx itemBase, iae)
, itemFull
, itemDiscoData
, seed
, itemGroup )
-- | Flavours assigned by the server to item kinds, in this particular game.
newtype FlavourMap = FlavourMap (EM.EnumMap (Kind.Id ItemKind) Flavour)
deriving (Show, Binary)
emptyFlavourMap :: FlavourMap
emptyFlavourMap = FlavourMap EM.empty
-- | Assigns flavours to item kinds. Assures no flavor is repeated for the same
-- symbol, except for items with only one permitted flavour.
rollFlavourMap :: S.Set Flavour -> Kind.Id ItemKind -> ItemKind
-> Rnd ( EM.EnumMap (Kind.Id ItemKind) Flavour
, EM.EnumMap Char (S.Set Flavour) )
-> Rnd ( EM.EnumMap (Kind.Id ItemKind) Flavour
, EM.EnumMap Char (S.Set Flavour) )
rollFlavourMap fullFlavSet key ik rnd =
let flavours = IK.iflavour ik
in if length flavours == 1
then rnd
else do
(assocs, availableMap) <- rnd
let available =
EM.findWithDefault fullFlavSet (IK.isymbol ik) availableMap
proper = S.fromList flavours `S.intersection` available
assert (not (S.null proper)
`blame` "not enough flavours for items"
`twith` (flavours, available, ik, availableMap)) $ do
flavour <- oneOf (S.toList proper)
let availableReduced = S.delete flavour available
return ( EM.insert key flavour assocs
, EM.insert (IK.isymbol ik) availableReduced availableMap)
-- | Randomly chooses flavour for all item kinds for this game.
dungeonFlavourMap :: Kind.COps -> Rnd FlavourMap
dungeonFlavourMap Kind.COps{coitem=Kind.Ops{ofoldrWithKey}} =
liftM (FlavourMap . fst) $
ofoldrWithKey (rollFlavourMap (S.fromList stdFlav))
(return (EM.empty, EM.empty))
-- | Reverse item map, for item creation, to keep items and item identifiers
-- in bijection.
type ItemRev = HM.HashMap ItemKnown ItemId
| beni55/LambdaHack | Game/LambdaHack/Server/ItemRev.hs | bsd-3-clause | 7,187 | 0 | 18 | 1,807 | 2,023 | 1,093 | 930 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable, FlexibleContexts #-}
import qualified Language.Conversion.Dep2Con as Dep2Con
import qualified Language.Structure.Constituency as Con
import qualified Language.Structure.Dependency as Dep
import qualified Language.Structure.Dependency.Parse as Dep
import System.Console.CmdArgs
import Text.ParserCombinators.UU.BasicInstances (Parser)
import Text.ParserCombinators.UU.Utils (runParser)
data Output
= Default
| ASCII
| Markdown
deriving (Data, Typeable)
data Options = Options
{ stanfordDependencies :: Bool
, output :: Output
} deriving (Data, Typeable)
defaultOptions :: Options
defaultOptions = Options
{ stanfordDependencies = False
&= help "Parse Stanford-style dependencies."
, output = Default
&= help "Set output format (default, ASCII or markdown)"
}
&= summary "Dep2Con v1.0, (c) Pepijn Kokke 2014"
&= program "dep2con"
main :: IO ()
main = do
opts <- cmdArgs defaultOptions
cont <- getContents
let parser :: Parser Dep.Tree
parser = if stanfordDependencies opts then Dep.pDeps else Dep.pTree
depTree = runParser "StdIn" parser cont
conTree = Dep2Con.collins depTree
case output opts of
Default -> print conTree
ASCII -> putStrLn (Con.asASCII conTree)
Markdown -> putStrLn (Con.asMarkdown conTree)
| pepijnkokke/Dep2Con | src/Dep2Con.hs | bsd-3-clause | 1,446 | 0 | 13 | 363 | 318 | 177 | 141 | 37 | 4 |
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import Control.Exception (evaluate)
import Control.Monad.IO.Class
import Data.Aeson
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C hiding (length, map)
import qualified Data.CaseInsensitive as CI
import Data.Maybe
import Data.Text hiding (head, length, map)
import Data.Typeable
import Netsuite.Connect
import Netsuite.Restlet
import Netsuite.Restlet.Configuration
import Netsuite.Restlet.Response
import Netsuite.Restlet.ResponseHandler
import Netsuite.Types.Data
import Netsuite.Types.Data.Core
import Netsuite.Types.Data.TypeFamily
import Netsuite.Types.Fields.Core
import Network.URI
import Network.Http.Internal
import System.Exit
import Test.Hspec
-- | Actual test suite
suite :: Spec
suite = do
describe "NsAction" $
it "can marshal all NsAction types as valid JSON" $
case mapMaybe (decode . encode) exampleNsActions of
(x :: [Value]) -> length x `shouldBe` length exampleNsActions
y -> error $ show y ++ " should be a list of valid JSON objects"
describe "NsRestletConfig" $ do
it "can create identical NsRestletConfig object from dissimilar origins" $ do
let a = ("http://example.com:8080", 12345 :: Int, 1000 :: Int, "[email protected]", "bar")
let b = NsRestletConfig (fromJust . parseURI $ "http://example.com:8080")
(12345 :: Integer)
(1000 :: Integer)
"[email protected]"
"bar"
Nothing
Nothing
toNsRestletConfig a `shouldBe` b
it "does not accept invalid URLs" $ do
let a = ("obviously incorrect ha ha", 12345 :: Int, 1000 :: Int, "[email protected]", "bar")
evaluate (show $ toNsRestletConfig a) `shouldThrow` errorCall "Maybe.fromJust: Nothing"
describe "Restlet Requests" $
it "creates the expected headers" $ do
let (nsid, nsrole, nsident, nspwd) = (12345 :: Int, 1000 :: Int, "[email protected]", "bar")
let a = ("http://example.com:8080", nsid, nsrole, nsident, nspwd)
let p = "/test"
r <- makeRequest (toNsRestletConfig a) p
qPath r `shouldBe` C.pack p
let hdrs = retrieveHeaders . qHeaders $ r
liftIO $ putStrLn $ show hdrs
tryBsMatch "Content-Type" "application/json" hdrs
tryBsMatch "Accept" "application/json" hdrs
tryBsMatch "User-Agent" "NsRestlet" hdrs
tryBsMatch "Authorization" (Prelude.concat ["NLAuth nlauth_account=",
show nsid,
",nlauth_email=",
nsident,
",nlauth_role=",
show nsrole,
",nlauth_signature=",
nspwd]) hdrs
describe "Restlet Errors" $ do
it "should parse GibberishError correctly" $
interpretError (head exampleRestletErrors) `shouldBe` GibberishError 400 "Unparseable response, expecting JSON." (C.pack "Bad Request")
it "should parse BeginChunking correctly" $
interpretError (exampleRestletErrors !! 1) `shouldBe` BeginChunking 400
it "should parse EndChunking correctly" $
interpretError (exampleRestletErrors !! 2) `shouldBe` EndChunking 400
it "should parse NotFound correctly" $
interpretError (exampleRestletErrors !! 3) `shouldBe` NotFound 404 ""
it "should parse InvalidSearchFilter correctly" $
interpretError (exampleRestletErrors !! 4) `shouldBe` InvalidSearchFilter 400 ""
it "should parse CCProcessorError correctly" $
interpretError (exampleRestletErrors !! 5) `shouldBe` CCProcessorError 400 ""
it "should parse ResourceConflict correctly" $
interpretError (exampleRestletErrors !! 6) `shouldBe` ResourceConflict 400 ""
it "should parse fall back to UnknownError correctly" $
interpretError (exampleRestletErrors !! 7) `shouldBe` UnknownError 400 "IDK_LOL" (C.pack "{\"error\": {\"message\": \"IDK_LOL\"}}")
-- | Tries to match header key values
tryBsMatch :: String -> String -> [(C.ByteString, C.ByteString)] -> Expectation
tryBsMatch a b h = shouldBe (lookup (C.pack a) h) (Just . C.pack $ b)
-- | Run everything
main :: IO ()
main = hspec suite
-- | Just pass
pass :: Expectation
pass = return ()
-- | Example NsActions
exampleNsActions :: [NsAction]
exampleNsActions = [
NsActRetrieve type1 (toNsDataId (12345 :: Int)) fields1 exampleCode,
NsActFetchSublist subtype1 (toNsId (12345 :: Int)) fields2 exampleCode,
NsActRawSearch type1 filters1 cols1 exampleCode,
NsActSearch type1 filters1 fields1 exampleCode,
NsActCreate type1 data1 subdata1 fields1 exampleCode,
NsActAttach type1 multiId type2 (toNsId (4 :: Int)) data1 exampleCode,
NsActDetach type1 multiId type2 (toNsId (4 :: Int)) exampleCode,
NsActUpdate type1 data2 fields1 exampleCode,
NsActUpdateSublist subtype1 (toNsId (12334 :: Int)) [data1, data2] exampleCode,
NsActDelete type1 (toNsDataId (12356 :: Int)) exampleCode,
NsActInvoicePDF (toNsId (9999 :: Int)) exampleCode,
NsActTransform type1 (toNsId (12345 :: Int)) type2 data1 fields2 exampleCode ]
where
type1 = toNsType "customer"
type2 = toNsType "contact"
subtype1 = toNsSubtype ("customer","addressbook")
filters1 = [toNsFilter ("foo", IsEmpty),
toNsFilter ("bar", Is, "1"),
toNsFilter ("baz", "beep", EqualTo, "1"),
toNsFilter ("fing", Contains, "fang", "foom"),
toNsFilter ("person", "location", Between, "rock", "hard place")]
cols1 = map toNsSearchCol [["foo"], ["bar"], ["baz", "beep"], ["a column"]]
data1 = toNsData [(pack "foo") .= (String . pack $ "bar"),
(pack "baz") .= (String . pack $ "frob"),
(pack "companyname") .= (String . pack $ "Sturm und Drang Inc.")]
data2 = toNsData [(pack "id") .= (String . pack $ "1234"),
(pack "foo") .= (String . pack $ "baz")]
subdata1 = toNsSublistData [("addressbook", [ [(pack "address1") .= (String . pack $ "1 Boog Street"),
(pack "city") .= (String . pack $ "Sydney")] ] )]
multiId = map toNsId [1 :: Int, 2 :: Int, 3 :: Int]
fields1 = NsFields ["id", "companyname"]
fields2 = NsFields ["phone", "email"]
exampleCode = NsRestletCode $ pack "alert(\"Hello world!\");"
-- | Test Restlet errors
exampleRestletErrors :: [RestletResponse]
exampleRestletErrors = map RestletErrorResp [ HttpRestletError 400 txBadRequest hdrs1 txBadRequest
, HttpRestletError 400 txBadRequest hdrs2 txChunky
, HttpRestletError 400 txBadRequest hdrs2 txEndChunk
, HttpRestletError 404 txNotFound hdrs2 txDoesntExist
, HttpRestletError 400 txBadRequest hdrs2 txInvalidSearch
, HttpRestletError 400 txBadRequest hdrs2 txCcProcessor
, HttpRestletError 400 txBadRequest hdrs2 txAlreadyExists
, HttpRestletError 400 txBadRequest hdrs2 txUnknown ]
where
txBadRequest = C.pack "Bad Request"
txNotFound = C.pack "Not Found"
txChunky = C.pack "{\"error\": {\"message\": \"CHUNKY_MONKEY\"}}"
txEndChunk = C.pack "{\"error\": {\"message\": \"NO_MORE_CHUNKS\"}}"
txDoesntExist = C.pack "{\"error\": {\"code\": \"RCRD_DOESNT_EXIST\"}}"
txInvalidSearch = C.pack "{\"error\": {\"code\": \"SSS_INVALID_SRCH_FILTER\"}}"
txCcProcessor = C.pack "{\"error\": {\"code\": \"CC_PROCESSOR_ERROR\"}}"
txAlreadyExists = C.pack "{\"error\": {\"code\": \"FOO_ALREADY_EXISTS\"}}"
txUnknown = C.pack "{\"error\": {\"message\": \"IDK_LOL\"}}"
hdrs1 = updateHeader emptyHeaders (C.pack "Content-Type") (C.pack "text/plain")
hdrs2 = updateHeader emptyHeaders (C.pack "Content-Type") (C.pack "application/json")
| anchor/haskell-netsuite | tests/UnitTests.hs | bsd-3-clause | 8,650 | 0 | 19 | 2,605 | 2,006 | 1,076 | 930 | 143 | 2 |
module ComplexSpec (main, spec) where
import Test.Hspec
import Test.QuickCheck
import Control.Exception (evaluate)
import Data.Maybe
import qualified Data.Aeson as A
import Complex
import qualified Data.ByteString.Lazy.Char8 as L
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "Complex" $ do
it "should add tow Cartesian numbers" $ do
Cartesian 1 1 + Cartesian 2 (-3) `shouldBe` Cartesian 3 (-2)
it "should sum Cartesian numbers" $ do
sum [Cartesian 1 2, Cartesian 3 4, Cartesian 6 4] `shouldBe` Cartesian 10 10
| balopat/quantum-computing | test/ComplexSpec.hs | bsd-3-clause | 559 | 0 | 17 | 114 | 195 | 105 | 90 | 17 | 1 |
-- FIXME: Should probably be merged with the Barcode module.
module Math.PersistentHomology.Bar where
import Math.Misc.PlusInfinity
import qualified Math.VectorSpaces.Metric2 as Met
-- | A bar in a barcode. Construct with 'bar'.
data Bar a = C a (PlusInfinity a)
deriving (Eq)
-- | 'bar @l u@' constructs the bar @[l, u]@. If @l > u@, then
-- the bar @[l, l]@ is created instead.
bar :: (Ord a) => a -> PlusInfinity a -> Bar a
bar l u
| (Regular l) <= u = C l u
| otherwise = C l (Regular l)
instance (Ord a) => Ord (Bar a) where
compare (C l1 u1) (C l2 u2) = compare (l1, u1) (l2, u2)
instance (Show a) => Show (Bar a) where
show (C l u) = "[" ++ show l ++ ", " ++ show u ++ ")"
javaPlexShow :: (Show a) => Bar a -> String
javaPlexShow (C l Infinity) = "[" ++ show l ++ ", infinity)"
javaPlexShow (C l (Regular r)) = "[" ++ show l ++ ", " ++ show r ++ ")"
compactShow :: (Show a) => Bar a -> String
compactShow (C l1 (Regular u1)) = show l1 ++ " " ++ show u1
compactShow (C l1 Infinity) = show l1 ++ " inf"
finiteBar :: (Ord a) => a -> a -> Bar a
finiteBar l u = bar l (Regular u)
infiniteBar :: (Ord a) => a -> Bar a
infiniteBar l = bar l Infinity
reIndex :: (Ord a, Ord b) => (a -> b) -> Bar a -> Bar b
reIndex f (C l Infinity) = C (f l) Infinity
reIndex f (C l (Regular u)) = C (f l) (Regular (f u))
intersection :: (Ord a) => Bar a -> Bar a -> Bar a
intersection (C l1 Infinity) (C l2 Infinity) = infiniteBar (max l1 l2)
intersection (C l1 Infinity) (C l2 (Regular u2)) = finiteBar (max l1 l2) u2
intersection (C l1 (Regular u1)) (C l2 Infinity) = finiteBar (max l1 l2) u1
intersection (C l1 (Regular u1)) (C l2 (Regular u2)) = finiteBar (max l1 l2) (min u1 u2)
measure :: (Met.Metric a a) => Bar a -> PlusInfinity a
measure (C _ Infinity) = Infinity
measure (C l (Regular u)) = Regular (Met.distance l u) | michiexile/hplex | pershom/src/Math/PersistentHomology/Bar.hs | bsd-3-clause | 1,851 | 0 | 10 | 422 | 922 | 463 | 459 | 34 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Dropbox.Conflict where
import FileConflict
import qualified Dropbox.FileNameParser as P
import Data.Monoid ((<>))
parse :: ConflictParser
parse baseName =
case P.parse baseName of
Just (P.FileInfo realBaseName host date) ->
Just (realBaseName, "Version " <> date <> " from " <> host)
Nothing -> Nothing
| dan-t/confsolve | Dropbox/Conflict.hs | bsd-3-clause | 378 | 0 | 12 | 81 | 100 | 56 | 44 | 11 | 2 |
Subsets and Splits