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 OverloadedStrings, UnicodeSyntax #-}
module Main where
import Prelude.Unicode
import Development.Shake.FilePath
import Hakyll
import Text.Pandoc.Options
import Paths
main :: IO ()
main = hakyllWith myConfiguration $ do
match "installation-guide/*.md" $ do
route $ setExtension ".html"
compile $ toHtml
match ("installation-guide/*.sh" .||. "installation-guide/*.png") $ do
route idRoute
compile copyFileCompiler
myConfiguration :: Configuration
myConfiguration = defaultConfiguration
{ providerDirectory = srcDir
, destinationDirectory = binDir
, storeDirectory = hakyllTmpDir </> "store"
, tmpDirectory = hakyllTmpDir </> "tmp"
}
toHtml = pandocCompilerWith readerOptions writerOptions
where
readerOptions = def
writerOptions = def { writerHtml5 = True }
|
c0c0n3/archlinux
|
vm/src/build/Site.hs
|
gpl-3.0
| 882
| 0
| 12
| 206
| 180
| 97
| 83
| 24
| 1
|
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
-- This is required due to the MonadBaseControl instance.
{-# LANGUAGE UndecidableInstances #-}
-- Module : Control.Monad.Trans.AWS
-- Copyright : (c) 2013-2015 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
-- | A monad transformer built on top of functions from "Network.AWS" which
-- encapsulates various common parameters, errors, and usage patterns.
module Control.Monad.Trans.AWS
(
-- * Requests
-- ** Synchronous
send
, send_
, sendCatch
-- ** Paginated
, paginate
, paginateCatch
-- ** Eventual consistency
, await
, awaitCatch
-- ** Pre-signing URLs
, presign
, presignURL
-- * Transformer
, AWS
, AWST
, MonadAWS
-- * Running
, runAWST
-- * Regionalisation
, Region (..)
, within
-- * Retries
, once
-- * Environment
, Env
-- ** Lenses
, envRegion
, envLogger
, envRetryCheck
, envRetryPolicy
, envManager
, envAuth
-- ** Creating the environment
, AWS.newEnv
, AWS.getEnv
-- ** Specifying credentials
, Credentials (..)
, fromKeys
, fromSession
, getAuth
, accessKey
, secretKey
-- * Logging
, newLogger
, info
, debug
, trace
-- * Errors
, Error
, hoistEither
, throwAWSError
, verify
, verifyWith
-- ** Streaming body helpers
, sourceBody
, sourceHandle
, sourceFile
, sourceFileIO
-- * Types
, ToBuilder (..)
, module Network.AWS.Types
, module Network.AWS.Error
) where
import Control.Applicative
import Control.Arrow (first)
import Control.Lens
import Control.Monad.Base
import Control.Monad.Catch
import Control.Monad.Except
import Control.Monad.Morph
import Control.Monad.Reader
import Control.Monad.Trans.Control
import Control.Monad.Trans.Resource
import Control.Retry (limitRetries)
import Data.ByteString (ByteString)
import Data.Conduit hiding (await)
import Data.Time (UTCTime)
import qualified Network.AWS as AWS
import Network.AWS.Data (ToBuilder (..))
import Network.AWS.Error
import Network.AWS.Internal.Auth
import Network.AWS.Internal.Body
import Network.AWS.Internal.Env
import Network.AWS.Internal.Log hiding (debug, info, trace)
import qualified Network.AWS.Internal.Log as Log
import Network.AWS.Types
import Network.AWS.Waiters
import qualified Network.HTTP.Conduit as Client
-- | The top-level error type.
type Error = ServiceError String
-- | A convenient alias for 'AWST' 'IO'.
type AWS = AWST IO
-- | Provides an alias for shortening type signatures if preferred.
--
-- /Note:/ requires the @ConstraintKinds@ extension.
type MonadAWS m =
( MonadBaseControl IO m
, MonadCatch m
, MonadResource m
, MonadError Error m
, MonadReader Env m
)
-- | The transformer. This satisfies all of the constraints that the functions
-- in this module require, such as providing 'MonadResource' instances,
-- and keeping track of the 'Env' environment.
--
-- The 'MonadError' instance for this transformer internally uses 'ExceptT'
-- to handle actions that result in an 'Error'. For more information see
-- 'sendCatch' and 'paginateCatch'.
newtype AWST m a = AWST
{ unAWST :: ReaderT (Env, InternalState) (ExceptT Error m) a
} deriving
( Functor
, Applicative
, Alternative
, Monad
, MonadIO
, MonadPlus
, MonadThrow
, MonadCatch
, MonadError Error
)
instance Monad m => MonadReader Env (AWST m) where
ask = AWST (fst `liftM` ask)
{-# INLINE ask #-}
local f = AWST . local (first f) . unAWST
{-# INLINE local #-}
instance MonadTrans AWST where
lift = AWST . lift . lift
{-# INLINE lift #-}
instance MonadBase b m => MonadBase b (AWST m) where
liftBase = liftBaseDefault
{-# INLINE liftBase #-}
instance MonadTransControl AWST where
type StT AWST a =
StT (ExceptT Error) (StT (ReaderT (Env, InternalState)) a)
liftWith f = AWST $
liftWith $ \g ->
liftWith $ \h ->
f (h . g . unAWST)
{-# INLINE liftWith #-}
restoreT = AWST . restoreT . restoreT
{-# INLINE restoreT #-}
instance MonadBaseControl b m => MonadBaseControl b (AWST m) where
type StM (AWST m) a = ComposeSt AWST m a
liftBaseWith = defaultLiftBaseWith
{-# INLINE liftBaseWith #-}
restoreM = defaultRestoreM
{-# INLINE restoreM #-}
instance MFunctor AWST where
hoist nat m = AWST (ReaderT (ExceptT . nat . runAWST' m))
{-# INLINE hoist #-}
instance MMonad AWST where
embed f m = liftM2 (,) ask resources
>>= f . runAWST' m
>>= either throwError return
{-# INLINE embed #-}
instance (Applicative m, MonadIO m, MonadBase IO m, MonadThrow m)
=> MonadResource (AWST m) where
liftResourceT f = resources >>= liftIO . runInternalState f
{-# INLINE liftResourceT #-}
-- | Unwrap an 'AWST' transformer, calling all of the registered 'ResourceT'
-- release actions.
runAWST :: MonadBaseControl IO m => Env -> AWST m a -> m (Either Error a)
runAWST e m = runResourceT . withInternalState $ runAWST' f . (e,)
where
f = liftBase (_envLogger e Debug (build e)) >> m
runAWST' :: AWST m a -> (Env, InternalState) -> m (Either Error a)
runAWST' (AWST k) = runExceptT . runReaderT k
resources :: Monad m => AWST m InternalState
resources = AWST (ReaderT (return . snd))
-- | Hoist an 'Either' throwing the 'Left' case, and returning the 'Right'.
hoistEither :: (MonadError Error m, AWSError e) => Either e a -> m a
hoistEither = either throwAWSError return
-- | Throw any 'AWSError' using 'throwError'.
throwAWSError :: (MonadError Error m, AWSError e) => e -> m a
throwAWSError = throwError . awsError
-- | Verify that an 'AWSError' matches the given 'Prism', otherwise throw the
-- error using 'throwAWSError'.
verify :: (AWSError e, MonadError Error m)
=> Prism' e a
-> e
-> m ()
verify p e
| isn't p e = throwAWSError e
| otherwise = return ()
-- | Verify that an 'AWSError' matches the given 'Prism', with an additional
-- guard on the result of the 'Prism'.
--
-- /See:/ 'verify'
verifyWith :: (AWSError e, MonadError Error m)
=> Prism' e a
-> (a -> Bool)
-> e
-> m ()
verifyWith p f e = either (const err) g (matching p e)
where
g x | f x = return ()
| otherwise = err
err = throwAWSError e
-- | Pass the current environment to a function.
scoped :: MonadReader Env m => (Env -> m a) -> m a
scoped f = ask >>= f
-- | Use the supplied logger from 'envLogger' to log info messages.
--
-- /Note:/ By default, the library does not output 'Info' level messages.
-- Exclusive output is guaranteed via use of this function.
info :: (MonadIO m, MonadReader Env m, ToBuilder a) => a -> m ()
info x = view envLogger >>= (`Log.info` x)
-- | Use the supplied logger from 'envLogger' to log debug messages.
debug :: (MonadIO m, MonadReader Env m, ToBuilder a) => a -> m ()
debug x = view envLogger >>= (`Log.debug` x)
-- | Use the supplied logger from 'envLogger' to log trace messages.
trace :: (MonadIO m, MonadReader Env m, ToBuilder a) => a -> m ()
trace x = view envLogger >>= (`Log.trace` x)
-- | Scope a monadic action within the specific 'Region'.
within :: MonadReader Env m => Region -> m a -> m a
within r = local (envRegion .~ r)
-- | Scope a monadic action such that any retry logic for the 'Service' is
-- ignored and any requests will at most be sent once.
once :: MonadReader Env m => m a -> m a
once = local $ \e ->
e & envRetryPolicy ?~ limitRetries 0
& envRetryCheck .~ (\_ _ -> return False)
-- | Send a data type which is an instance of 'AWSRequest', returning it's
-- associated 'Rs' response type.
--
-- This will throw any 'HTTPException' or 'AWSServiceError' returned by the
-- service using the 'MonadError' instance. In the case of 'AWST' this will
-- cause the internal 'ExceptT' to short-circuit and return an 'Error' in
-- the 'Left' case as the result of the computation.
--
-- /See:/ 'sendCatch'
send :: ( MonadCatch m
, MonadResource m
, MonadReader Env m
, MonadError Error m
, AWSRequest a
)
=> a
-> m (Rs a)
send = sendCatch >=> hoistEither
-- | A variant of 'send' which discards any successful response.
--
-- /See:/ 'send'
send_ :: ( MonadCatch m
, MonadResource m
, MonadReader Env m
, MonadError Error m
, AWSRequest a
)
=> a
-> m ()
send_ = void . send
-- | Send a data type which is an instance of 'AWSRequest', returning either the
-- associated 'Rs' response type in the success case, or the related service's
-- 'Er' type in the error case.
--
-- This includes 'HTTPExceptions', serialisation errors, and any service
-- errors returned as part of the 'Response'.
--
-- /Note:/ Requests will be retried depending upon each service's respective
-- strategy. This can be overriden using 'once' or 'envRetry'.
-- Requests which contain streaming request bodies (such as S3's 'PutObject') are
-- never considered for retries.
sendCatch :: ( MonadCatch m
, MonadResource m
, MonadReader Env m
, AWSRequest a
)
=> a
-> m (Response a)
sendCatch x = scoped (`AWS.send` x)
-- | Send a data type which is an instance of 'AWSPager' and paginate while
-- there are more results as defined by the related service operation.
--
-- Errors will be handle identically to 'send'.
--
-- /Note:/ The 'ResumableSource' will close when there are no more results or the
-- 'ResourceT' computation is unwrapped. See: 'runResourceT' for more information.
--
-- /See:/ 'paginateCatch'
paginate :: ( MonadCatch m
, MonadResource m
, MonadReader Env m
, MonadError Error m
, AWSPager a
)
=> a
-> Source m (Rs a)
paginate x = paginateCatch x $= awaitForever (hoistEither >=> yield)
-- | Send a data type which is an instance of 'AWSPager' and paginate over
-- the associated 'Rs' response type in the success case, or the related service's
-- 'Er' type in the error case.
--
-- /Note:/ The 'ResumableSource' will close when there are no more results or the
-- 'ResourceT' computation is unwrapped. See: 'runResourceT' for more information.
paginateCatch :: ( MonadCatch m
, MonadResource m
, MonadReader Env m
, AWSPager a
)
=> a
-> Source m (Response a)
paginateCatch x = scoped (`AWS.paginate` x)
-- | Poll the API until a predfined condition is fulfilled using the
-- supplied 'Wait' specification from the respective service.
--
-- Any errors which are unhandled by the 'Wait' specification during retries
-- will be thrown in the same manner as 'send'.
--
-- /See:/ 'awaitCatch'
await :: ( MonadCatch m
, MonadResource m
, MonadReader Env m
, MonadError Error m
, AWSRequest a
)
=> Wait a
-> a
-> m (Rs a)
await w = awaitCatch w >=> hoistEither
-- | Poll the API until a predfined condition is fulfilled using the
-- supplied 'Wait' specification from the respective service.
--
-- The response will be either the first error returned that is not handled
-- by the specification, or the successful response from the await request.
--
-- /Note:/ You can find any available 'Wait' specifications under the
-- namespace @Network.AWS.<ServiceName>.Waiters@ for supported services.
awaitCatch :: ( MonadCatch m
, MonadResource m
, MonadReader Env m
, AWSRequest a
)
=> Wait a
-> a
-> m (Response a)
awaitCatch w x = scoped (\e -> AWS.await e w x)
-- | Presign an HTTP request that expires at the specified amount of time
-- in the future.
--
-- /Note:/ Requires the service's signer to be an instance of 'AWSPresigner'.
-- Not all signing process support this.
presign :: ( MonadIO m
, MonadReader Env m
, AWSRequest a
, AWSPresigner (Sg (Sv a))
)
=> a -- ^ Request to presign.
-> UTCTime -- ^ Signing time.
-> Integer -- ^ Expiry time in seconds.
-> m Client.Request
presign x t ex = scoped (\e -> AWS.presign e x t ex)
-- | Presign a URL that expires at the specified amount of time in the future.
--
-- /See:/ 'presign'
presignURL :: ( MonadIO m
, MonadReader Env m
, AWSRequest a
, AWSPresigner (Sg (Sv a))
)
=> a -- ^ Request to presign.
-> UTCTime -- ^ Signing time.
-> Integer -- ^ Expiry time in seconds.
-> m ByteString
presignURL x t ex = scoped (\e -> AWS.presignURL e x t ex)
|
dysinger/amazonka
|
amazonka/src/Control/Monad/Trans/AWS.hs
|
mpl-2.0
| 13,967
| 0
| 13
| 3,973
| 2,607
| 1,459
| 1,148
| 256
| 1
|
{-# LANGUAGE TypeFamilies #-}
module Gonimo.Server.Db.Internal where
import Control.Lens
import Control.Monad.State.Class
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Maybe (MaybeT)
import Control.Monad.Trans.Reader (ReaderT (..))
import Control.Monad.Trans.State (StateT (..))
import Gonimo.Server.Error (ServerError)
import Control.Monad.Base (MonadBase)
import Control.Monad.IO.Class (MonadIO)
import Database.Persist.Class (Key, PersistStoreWrite, PersistRecordBackend)
import qualified Database.Persist.Class as Db
import qualified Gonimo.Database.Effects.Servant as Db
type UpdateT entity m a = StateT entity (MaybeT m) a
-- | Update db entity as specified by the given UpdateFamilyT - on Nothing, no update occurs.
updateRecord :: ( PersistStoreWrite backend, PersistRecordBackend record backend
, MonadIO m, MonadBase IO m)
=> (Key record -> ServerError) -> Key record
-> UpdateT record (ReaderT backend m) a
-> MaybeT (ReaderT backend m) a
updateRecord noSuchRecord recordId f = do
oldRecord <- lift $ Db.getErr (noSuchRecord recordId) recordId
r <- flip runStateT oldRecord $ do
r <- f
newRecord <- get
lift.lift $ Db.replace recordId newRecord
pure r
pure $ r^._1
|
gonimo/gonimo-back
|
src/Gonimo/Server/Db/Internal.hs
|
agpl-3.0
| 1,463
| 0
| 13
| 415
| 358
| 203
| 155
| -1
| -1
|
{-# LANGUAGE GADTs #-}
module Main where
import Criterion.Main
import Crypto.Noise
import Crypto.Noise.DH
import Keys
import Types
genMessage :: (Cipher c, DH d, Hash h)
=> Bool -- ^ True if we are writing a message
-> Maybe ScrubbedBytes -- ^ If a PSK is called for, this value will be used
-> ScrubbedBytes -- ^ The payload to write/read
-> NoiseState c d h -- ^ The NoiseState to use
-> NoiseResult c d h
genMessage write mpsk payload state = case result of
NoiseResultNeedPSK s -> case mpsk of
Nothing -> NoiseResultException . error $ "PSK requested but none has been configured"
Just k -> genMessage write mpsk k s
r -> r
where
operation = if write then writeMessage else readMessage
result = operation payload state
genMessages :: (Cipher c, DH d, Hash h)
=> Bool -- ^ Set to False for one-way patterns
-> NoiseState c d h -- ^ Initiator NoiseState
-> NoiseState c d h -- ^ Responder NoiseState
-> Maybe ScrubbedBytes -- ^ PSK
-> [(ScrubbedBytes, ScrubbedBytes)]
genMessages swap = go []
where
go acc s r _ | handshakeComplete s && handshakeComplete r = acc
go acc sendingState receivingState mpsk =
case genMessage True mpsk "" sendingState of
NoiseResultMessage ct sendingState' ->
case genMessage False mpsk ct receivingState of
NoiseResultMessage pt receivingState' ->
if swap
then go ((pt, ct) : acc) receivingState' sendingState' mpsk
else go ((pt, ct) : acc) sendingState' receivingState' mpsk
_ -> error $ "problem encountered during message generation"
_ -> error $ "problem encountered during message generation"
genNoiseStates :: (Cipher c, DH d, Hash h)
=> CipherType c
-> HashType h
-> PatternName
-> (HandshakeOpts d, HandshakeOpts d)
-> (NoiseState c d h, NoiseState c d h)
genNoiseStates _ _ pat (iopts, ropts) =
(noiseState iopts hs, noiseState ropts hs)
where
hs = patternToHandshake pat
genOpts :: DH d
=> DHType d
-> PatternName
-> (HandshakeOpts d, HandshakeOpts d)
genOpts d pat = (iopts, ropts)
where
idho = defaultHandshakeOpts InitiatorRole mempty
rdho = defaultHandshakeOpts ResponderRole mempty
keys = getKeys (WrapDHType d) pat
iopts = setLocalEphemeral (dhBytesToPair =<< hskInitEphemeral keys)
. setLocalStatic (dhBytesToPair =<< hskInitStatic keys)
. setRemoteStatic (dhBytesToPub =<< hskInitRemoteStatic keys)
$ idho
ropts = setLocalEphemeral (dhBytesToPair =<< hskRespEphemeral keys)
. setLocalStatic (dhBytesToPair =<< hskRespStatic keys)
. setRemoteStatic (dhBytesToPub =<< hskRespRemoteStatic keys)
$ rdho
toBench :: SomeCipherType
-> SomeDHType
-> SomeHashType
-> PatternName
-> [(ScrubbedBytes, ScrubbedBytes)]
toBench (WrapCipherType c) (WrapDHType d) (WrapHashType h) pat =
genMessages swap ins rns (Just psk)
where
psk = "This is my Austrian perspective!"
swap = pat /= PatternN && pat /= PatternK && pat /= PatternX &&
pat /= PatternNpsk0 && pat /= PatternKpsk0 && pat /= PatternXpsk1
opts = genOpts d pat
(ins, rns) = genNoiseStates c h pat opts
allHandshakes :: [HandshakeName]
allHandshakes = do
pattern <- [minBound .. maxBound]
cipher <- [ WrapCipherType AESGCM
, WrapCipherType ChaChaPoly1305
]
dh <- [ WrapDHType Curve25519
, WrapDHType Curve448
]
hash <- [ WrapHashType BLAKE2b
, WrapHashType BLAKE2s
, WrapHashType SHA256
, WrapHashType SHA512
]
return $ HandshakeName pattern cipher dh hash
main :: IO ()
main = do
let benches = do
hs <- allHandshakes
let b = toBench (hsCipher hs) (hsDH hs) (hsHash hs)
pat = hsPatternName hs
return $ bench (show hs) (nf b pat)
defaultMain benches
|
centromere/cacophony
|
benchmarks/Main.hs
|
unlicense
| 4,237
| 0
| 17
| 1,343
| 1,142
| 577
| 565
| 95
| 5
|
module Algo.Graph (
bellmanFord
) where
-- Bellman for algorithm for shortest path search
bellmanFord = undefined
dijkstra = undefined
|
seckcoder/lang-learn
|
haskell/algo/src/Algo/Graph.hs
|
unlicense
| 157
| 0
| 4
| 42
| 22
| 14
| 8
| 4
| 1
|
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
module Chinese.Game where
import Chinese.Dictionary
import Chinese.Player
import Data.Time
import Prelude hiding (Word)
import System.IO.Unsafe
import System.Random
data Question = CharToPinyin Word
-- ^Ask the pronunciation of a chinese character
| FrenchToChinese String
-- ^Ask chinese word for french
deriving Show
data Answer = Pinyin String
| Chinese String
| French String
| Selected GameType
| Skip
| Cancel
deriving (Show, Read, Eq)
data Result = Correct
-- ^Provided answer is correct
| Wrong [Answer]
-- ^Answer is wrong, and correct answer is provided
deriving (Show, Read)
data Game = Game { gameDictionary :: Dictionary
-- ^Dictionary to use for game, linking chinese characters, pinyin and french
, wordsList :: [ Word ]
-- ^random list of wordsList from dictionary, to be used for asking questions according
-- to type of question
, playerState :: Player
, gameType :: GameType
, gameStartedAt :: UTCTime
, gameEndedAt :: Maybe UTCTime
}
-- | Defines the type of questions that are asked
data GameType = Sound -- ^ Get pinyin for given word
| Version -- ^ Translate from chinese to french
| Theme -- ^ Translate from french to chinese
deriving (Show,Read,Eq,Enum)
instance Show Game where
show Game{..} = "Game " ++ show (length gameDictionary) ++
" words, type: " ++ show gameType ++
", player: " ++ show playerState ++
", started: " ++ show gameStartedAt ++
", ended: " ++ show gameEndedAt
newGame :: StdGen -> PlayerName -> Dictionary -> UTCTime -> Game
newGame rand name dict start = let qs g = let (re, g') = randomWord g dict
in re : qs g'
in Game dict (qs rand) (newPlayer name) Sound start Nothing
{-# NOINLINE randomElement #-}
randomElement :: [ a ] -> a
randomElement as = let g = unsafePerformIO $ randomRIO (0,length as -1)
in as !! g
nextQuestion :: Game -> Question
nextQuestion Game{..} | gameType == Sound = CharToPinyin $ head wordsList
| gameType == Theme = let (Word _ _ frs) = head wordsList
in FrenchToChinese $ randomElement frs
| otherwise = undefined
checkAnswer :: Game -> Answer -> Result
checkAnswer (Game _ qs _ Sound _ _) (Pinyin s) = let (Word _ p fr) = head qs
in if p == s
then Correct
else Wrong $ Pinyin p:(map French fr)
checkAnswer (Game _ qs _ Theme _ _) (Chinese s) = let (Word s' p _) = head qs
in if s' == s
then Correct
else Wrong [Chinese s', Pinyin p]
checkAnswer Game{..} Cancel = Correct
checkAnswer (Game _ qs _ Sound _ _) _ = let (Word _ p _) = head qs
in Wrong [Pinyin p]
checkAnswer (Game _ qs _ Theme _ _) _ = let (Word zh p _) = head qs
in Wrong [Chinese zh, Pinyin p]
checkAnswer Game{..} _ = undefined -- TODO
correctAnswer :: Game -> Game
correctAnswer g@Game{..} = g { playerState = successAnswer playerState
, wordsList = tail wordsList
}
wrongAnswer :: Game -> Game
wrongAnswer g@Game{..} = g { playerState = failureAnswer playerState
, wordsList = tail wordsList
}
|
abailly/acquire
|
chinese/src/Chinese/Game.hs
|
apache-2.0
| 4,285
| 0
| 17
| 1,856
| 996
| 518
| 478
| 74
| 3
|
{-# LANGUAGE DeriveDataTypeable #-}
module CabalNew.Types
( CabalNew(..)
, CabalTarget(..)
, YesodBackend(..)
, GitLevel(..)
) where
import Data.Data
data GitLevel = GitHere | ParentGit | Gitless
deriving (Show, Eq, Data, Typeable)
data CabalTarget = Executable
| Library
| Yesod
| GhcJs
| Sandbox
deriving (Show, Eq, Data, Typeable)
data YesodBackend = Sqlite
| Postgres
| PostFay
| MongoDB
| MySQL
| Simple
deriving (Show, Eq, Data, Typeable)
data CabalNew = CabalNew
{ projectRootDir :: String
, projectName :: String
, projectGitLevel :: GitLevel
, privateProject :: Bool
, projectLicense :: String
, projectEmail :: String
, projectSynopsis :: String
, projectCategory :: String
, projectTarget :: CabalTarget
, projectBackend :: Maybe YesodBackend
, projectTmuxifier :: Bool
} deriving (Data, Typeable, Show)
|
erochest/cabal-new
|
CabalNew/Types.hs
|
apache-2.0
| 1,253
| 0
| 9
| 559
| 246
| 151
| 95
| 35
| 0
|
{-# LANGUAGE OverloadedStrings, FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Documentation.Haddock.ParserSpec (main, spec) where
import Data.String
import qualified Documentation.Haddock.Parser as Parse
import Documentation.Haddock.Types
import Documentation.Haddock.Doc (docAppend)
import Test.Hspec
import Test.QuickCheck
infixr 6 <>
(<>) :: Doc id -> Doc id -> Doc id
(<>) = docAppend
type Doc id = DocH () id
instance IsString (Doc String) where
fromString = DocString
instance IsString a => IsString (Maybe a) where
fromString = Just . fromString
parseParas :: String -> MetaDoc () String
parseParas = overDoc Parse.toRegular . Parse.parseParas
parseString :: String -> Doc String
parseString = Parse.toRegular . Parse.parseString
hyperlink :: String -> Maybe String -> Doc String
hyperlink url = DocHyperlink . Hyperlink url
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "parseString" $ do
let infix 1 `shouldParseTo`
shouldParseTo :: String -> Doc String -> Expectation
shouldParseTo input ast = parseString input `shouldBe` ast
it "is total" $ do
property $ \xs ->
(length . show . parseString) xs `shouldSatisfy` (> 0)
context "when parsing text" $ do
it "can handle unicode" $ do
"灼眼のシャナ" `shouldParseTo` "灼眼のシャナ"
it "accepts numeric character references" $ do
"foo bar baz λ" `shouldParseTo` "foo bar baz λ"
it "accepts hexadecimal character references" $ do
"e" `shouldParseTo` "e"
it "allows to backslash-escape characters except \\r" $ do
property $ \case
'\r' -> "\\\r" `shouldParseTo` DocString "\\"
x -> ['\\', x] `shouldParseTo` DocString [x]
context "when parsing strings contaning numeric character references" $ do
it "will implicitly convert digits to characters" $ do
"AAAA" `shouldParseTo` "AAAA"
"灼眼のシャナ"
`shouldParseTo` "灼眼のシャナ"
it "will implicitly convert hex encoded characters" $ do
"eeee" `shouldParseTo` "eeee"
context "when parsing identifiers" $ do
it "parses identifiers enclosed within single ticks" $ do
"'foo'" `shouldParseTo` DocIdentifier "foo"
it "parses identifiers enclosed within backticks" $ do
"`foo`" `shouldParseTo` DocIdentifier "foo"
it "parses a word with an one of the delimiters in it as DocString" $ do
"don't" `shouldParseTo` "don't"
it "doesn't pass pairs of delimiters with spaces between them" $ do
"hel'lo w'orld" `shouldParseTo` "hel'lo w'orld"
it "don't use apostrophe's in the wrong place's" $ do
" don't use apostrophe's in the wrong place's" `shouldParseTo`
"don't use apostrophe's in the wrong place's"
it "doesn't parse empty identifiers" $ do
"``" `shouldParseTo` "``"
it "can parse infix identifiers" $ do
"``infix``" `shouldParseTo` "`" <> DocIdentifier "infix" <> "`"
context "when parsing URLs" $ do
it "parses a URL" $ do
"<http://example.com/>" `shouldParseTo` hyperlink "http://example.com/" Nothing
it "accepts an optional label" $ do
"<http://example.com/ some link>" `shouldParseTo` hyperlink "http://example.com/" "some link"
it "does not accept newlines in label" $ do
"<foo bar\nbaz>" `shouldParseTo` "<foo bar\nbaz>"
-- new behaviour test, this will be now consistent with other markup
it "allows us to escape > inside the URL" $ do
"<http://examp\\>le.com>" `shouldParseTo`
hyperlink "http://examp>le.com" Nothing
"<http://exa\\>mp\\>le.com>" `shouldParseTo`
hyperlink "http://exa>mp>le.com" Nothing
-- Likewise in label
"<http://example.com f\\>oo>" `shouldParseTo`
hyperlink "http://example.com" "f>oo"
it "parses inline URLs" $ do
"foo <http://example.com/> bar" `shouldParseTo`
"foo " <> hyperlink "http://example.com/" Nothing <> " bar"
it "doesn't allow for multi-line link tags" $ do
"<ba\nz aar>" `shouldParseTo` "<ba\nz aar>"
context "when parsing markdown links" $ do
it "parses a simple link" $ do
"[some label](url)" `shouldParseTo`
hyperlink "url" "some label"
it "allows whitespace between label and URL" $ do
"[some label] \t (url)" `shouldParseTo`
hyperlink "url" "some label"
it "allows newlines in label" $ do
"[some\n\nlabel](url)" `shouldParseTo`
hyperlink "url" "some\n\nlabel"
it "allows escaping in label" $ do
"[some\\] label](url)" `shouldParseTo`
hyperlink "url" "some] label"
it "strips leading and trailing whitespace from label" $ do
"[ some label ](url)" `shouldParseTo`
hyperlink "url" "some label"
it "rejects whitespace in URL" $ do
"[some label]( url)" `shouldParseTo`
"[some label]( url)"
context "when URL is on a separate line" $ do
it "allows URL to be on a separate line" $ do
"[some label]\n(url)" `shouldParseTo`
hyperlink "url" "some label"
it "allows leading whitespace" $ do
"[some label]\n \t (url)" `shouldParseTo`
hyperlink "url" "some label"
it "rejects additional newlines" $ do
"[some label]\n\n(url)" `shouldParseTo`
"[some label]\n\n(url)"
context "when autolinking URLs" $ do
it "autolinks HTTP URLs" $ do
"http://example.com/" `shouldParseTo` hyperlink "http://example.com/" Nothing
it "autolinks HTTPS URLs" $ do
"https://www.example.com/" `shouldParseTo` hyperlink "https://www.example.com/" Nothing
it "autolinks FTP URLs" $ do
"ftp://example.com/" `shouldParseTo` hyperlink "ftp://example.com/" Nothing
it "does not include a trailing comma" $ do
"http://example.com/, Some other sentence." `shouldParseTo`
hyperlink "http://example.com/" Nothing <> ", Some other sentence."
it "does not include a trailing dot" $ do
"http://example.com/. Some other sentence." `shouldParseTo`
hyperlink "http://example.com/" Nothing <> ". Some other sentence."
it "does not include a trailing exclamation mark" $ do
"http://example.com/! Some other sentence." `shouldParseTo`
hyperlink "http://example.com/" Nothing <> "! Some other sentence."
it "does not include a trailing question mark" $ do
"http://example.com/? Some other sentence." `shouldParseTo`
hyperlink "http://example.com/" Nothing <> "? Some other sentence."
it "autolinks URLs occuring mid-sentence with multiple ‘/’s" $ do
"foo https://example.com/example bar" `shouldParseTo`
"foo " <> hyperlink "https://example.com/example" Nothing <> " bar"
context "when parsing images" $ do
let image :: String -> Maybe String -> Doc String
image uri = DocPic . Picture uri
it "accepts markdown syntax for images" $ do
"" `shouldParseTo` image "url" "label"
it "accepts Unicode" $ do
"" `shouldParseTo` image "url" "灼眼のシャナ"
it "supports deprecated picture syntax" $ do
"<<baz>>" `shouldParseTo` image "baz" Nothing
it "supports title for deprecated picture syntax" $ do
"<<b a z>>" `shouldParseTo` image "b" "a z"
context "when parsing anchors" $ do
it "parses a single word anchor" $ do
"#foo#" `shouldParseTo` DocAName "foo"
it "parses a multi word anchor" $ do
"#foo bar#" `shouldParseTo` DocAName "foo bar"
it "parses a unicode anchor" $ do
"#灼眼のシャナ#" `shouldParseTo` DocAName "灼眼のシャナ"
it "does not accept newlines in anchors" $ do
"#foo\nbar#" `shouldParseTo` "#foo\nbar#"
it "accepts anchors mid-paragraph" $ do
"Hello #someAnchor# world!"
`shouldParseTo` "Hello " <> DocAName "someAnchor" <> " world!"
it "does not accept empty anchors" $ do
"##" `shouldParseTo` "##"
context "when parsing emphasised text" $ do
it "emphasises a word on its own" $ do
"/foo/" `shouldParseTo` DocEmphasis "foo"
it "emphasises inline correctly" $ do
"foo /bar/ baz" `shouldParseTo` "foo " <> DocEmphasis "bar" <> " baz"
it "emphasises unicode" $ do
"/灼眼のシャナ/" `shouldParseTo` DocEmphasis "灼眼のシャナ"
it "does not emphasise multi-line strings" $ do
" /foo\nbar/" `shouldParseTo` "/foo\nbar/"
it "does not emphasise the empty string" $ do
"//" `shouldParseTo` "//"
it "parses escaped slashes literally" $ do
"/foo\\/bar/" `shouldParseTo` DocEmphasis "foo/bar"
it "recognizes other markup constructs within emphasised text" $ do
"/foo @bar@ baz/" `shouldParseTo`
DocEmphasis ("foo " <> DocMonospaced "bar" <> " baz")
it "allows other markup inside of emphasis" $ do
"/__inner bold__/" `shouldParseTo` DocEmphasis (DocBold "inner bold")
it "doesn't mangle inner markup unicode" $ do
"/__灼眼のシャナ A__/" `shouldParseTo` DocEmphasis (DocBold "灼眼のシャナ A")
it "properly converts HTML escape sequences" $ do
"/AAAA/" `shouldParseTo` DocEmphasis "AAAA"
it "allows to escape the emphasis delimiter inside of emphasis" $ do
"/empha\\/sis/" `shouldParseTo` DocEmphasis "empha/sis"
context "when parsing monospaced text" $ do
it "parses simple monospaced text" $ do
"@foo@" `shouldParseTo` DocMonospaced "foo"
it "parses inline monospaced text" $ do
"foo @bar@ baz" `shouldParseTo` "foo " <> DocMonospaced "bar" <> " baz"
it "allows to escape @" $ do
"@foo \\@ bar@" `shouldParseTo` DocMonospaced "foo @ bar"
it "accepts unicode" $ do
"@foo 灼眼のシャナ bar@" `shouldParseTo` DocMonospaced "foo 灼眼のシャナ bar"
it "accepts other markup in monospaced text" $ do
"@/foo/@" `shouldParseTo` DocMonospaced (DocEmphasis "foo")
it "requires the closing @" $ do
"@foo /bar/ baz" `shouldParseTo` "@foo " <> DocEmphasis "bar" <> " baz"
context "when parsing bold strings" $ do
it "allows for a bold string on its own" $ do
"__bold string__" `shouldParseTo`
DocBold "bold string"
it "bolds inline correctly" $ do
"hello __everyone__ there" `shouldParseTo`
"hello "
<> DocBold "everyone" <> " there"
it "bolds unicode" $ do
"__灼眼のシャナ__" `shouldParseTo`
DocBold "灼眼のシャナ"
it "does not do __multi-line\\n bold__" $ do
" __multi-line\n bold__" `shouldParseTo` "__multi-line\n bold__"
it "allows other markup inside of bold" $ do
"__/inner emphasis/__" `shouldParseTo`
(DocBold $ DocEmphasis "inner emphasis")
it "doesn't mangle inner markup unicode" $ do
"__/灼眼のシャナ A/__" `shouldParseTo`
(DocBold $ DocEmphasis "灼眼のシャナ A")
it "properly converts HTML escape sequences" $ do
"__AAAA__" `shouldParseTo`
DocBold "AAAA"
it "allows to escape the bold delimiter inside of bold" $ do
"__bo\\__ld__" `shouldParseTo`
DocBold "bo__ld"
it "doesn't allow for empty bold" $ do
"____" `shouldParseTo` "____"
context "when parsing module strings" $ do
it "should parse a module on its own" $ do
"\"Module\"" `shouldParseTo`
DocModule "Module"
it "should parse a module inline" $ do
"This is a \"Module\"." `shouldParseTo`
"This is a " <> DocModule "Module" <> "."
it "can accept a simple module name" $ do
"\"Hello\"" `shouldParseTo` DocModule "Hello"
it "can accept a module name with dots" $ do
"\"Hello.World\"" `shouldParseTo` DocModule "Hello.World"
it "can accept a module name with unicode" $ do
"\"Hello.Worldλ\"" `shouldParseTo` DocModule "Hello.Worldλ"
it "parses a module name with a trailing dot as regular quoted string" $ do
"\"Hello.\"" `shouldParseTo` "\"Hello.\""
it "parses a module name with a space as regular quoted string" $ do
"\"Hello World\"" `shouldParseTo` "\"Hello World\""
it "parses a module name with invalid characters as regular quoted string" $ do
"\"Hello&[{}(=*)+]!\"" `shouldParseTo` "\"Hello&[{}(=*)+]!\""
it "accepts a module name with unicode" $ do
"\"Foo.Barλ\"" `shouldParseTo` DocModule "Foo.Barλ"
it "treats empty module name as regular double quotes" $ do
"\"\"" `shouldParseTo` "\"\""
it "accepts anchor reference syntax as DocModule" $ do
"\"Foo#bar\"" `shouldParseTo` DocModule "Foo#bar"
it "accepts old anchor reference syntax as DocModule" $ do
"\"Foo\\#bar\"" `shouldParseTo` DocModule "Foo\\#bar"
describe "parseParas" $ do
let infix 1 `shouldParseTo`
shouldParseTo :: String -> Doc String -> Expectation
shouldParseTo input ast = _doc (parseParas input) `shouldBe` ast
it "is total" $ do
property $ \xs ->
(length . show . parseParas) xs `shouldSatisfy` (> 0)
context "when parsing @since" $ do
it "adds specified version to the result" $ do
parseParas "@since 0.5.0" `shouldBe`
MetaDoc { _meta = Meta { _version = Just [0,5,0] }
, _doc = DocEmpty }
it "ignores trailing whitespace" $ do
parseParas "@since 0.5.0 \t " `shouldBe`
MetaDoc { _meta = Meta { _version = Just [0,5,0] }
, _doc = DocEmpty }
it "does not allow trailing input" $ do
parseParas "@since 0.5.0 foo" `shouldBe`
MetaDoc { _meta = Meta { _version = Nothing }
, _doc = DocParagraph "@since 0.5.0 foo" }
context "when given multiple times" $ do
it "gives last occurrence precedence" $ do
(parseParas . unlines) [
"@since 0.5.0"
, "@since 0.6.0"
, "@since 0.7.0"
] `shouldBe` MetaDoc { _meta = Meta { _version = Just [0,7,0] }
, _doc = DocEmpty }
context "when parsing text paragraphs" $ do
let filterSpecial = filter (`notElem` (".(=#-[*`\v\f\n\t\r\\\"'_/@<> " :: String))
it "parses an empty paragraph" $ do
"" `shouldParseTo` DocEmpty
it "parses a simple text paragraph" $ do
"foo bar baz" `shouldParseTo` DocParagraph "foo bar baz"
it "accepts markup in text paragraphs" $ do
"foo /bar/ baz" `shouldParseTo` DocParagraph ("foo " <> DocEmphasis "bar" <> " baz")
it "preserve all regular characters" $ do
property $ \xs -> let input = filterSpecial xs in (not . null) input ==>
input `shouldParseTo` DocParagraph (DocString input)
it "separates paragraphs by empty lines" $ do
unlines [
"foo"
, " \t "
, "bar"
] `shouldParseTo` DocParagraph "foo" <> DocParagraph "bar"
context "when a pragraph only contains monospaced text" $ do
it "turns it into a code block" $ do
"@foo@" `shouldParseTo` DocCodeBlock "foo"
context "when a paragraph starts with a markdown link" $ do
it "correctly parses it as a text paragraph (not a definition list)" $ do
"[label](url)" `shouldParseTo`
DocParagraph (hyperlink "url" "label")
it "can be followed by an other paragraph" $ do
"[label](url)\n\nfoobar" `shouldParseTo`
DocParagraph (hyperlink "url" "label") <> DocParagraph "foobar"
context "when paragraph contains additional text" $ do
it "accepts more text after the link" $ do
"[label](url) foo bar baz" `shouldParseTo`
DocParagraph (hyperlink "url" "label" <> " foo bar baz")
it "accepts a newline right after the markdown link" $ do
"[label](url)\nfoo bar baz" `shouldParseTo`
DocParagraph (hyperlink "url" "label" <> " foo bar baz")
it "can be followed by an other paragraph" $ do
"[label](url)foo\n\nbar" `shouldParseTo`
DocParagraph (hyperlink "url" "label" <> "foo") <> DocParagraph "bar"
context "when parsing birdtracks" $ do
it "parses them as a code block" $ do
unlines [
">foo"
, ">bar"
, ">baz"
] `shouldParseTo` DocCodeBlock "foo\nbar\nbaz"
it "ignores leading whitespace" $ do
unlines [
" >foo"
, " \t >bar"
, " >baz"
]
`shouldParseTo` DocCodeBlock "foo\nbar\nbaz"
it "strips one leading space from each line of the block" $ do
unlines [
"> foo"
, "> bar"
, "> baz"
] `shouldParseTo` DocCodeBlock "foo\n bar\nbaz"
it "ignores empty lines when stripping spaces" $ do
unlines [
"> foo"
, ">"
, "> bar"
] `shouldParseTo` DocCodeBlock "foo\n\nbar"
context "when any non-empty line does not start with a space" $ do
it "does not strip any spaces" $ do
unlines [
">foo"
, "> bar"
] `shouldParseTo` DocCodeBlock "foo\n bar"
it "ignores nested markup" $ do
unlines [
">/foo/"
] `shouldParseTo` DocCodeBlock "/foo/"
it "treats them as regular text inside text paragraphs" $ do
unlines [
"foo"
, ">bar"
] `shouldParseTo` DocParagraph "foo\n>bar"
context "when parsing code blocks" $ do
it "accepts a simple code block" $ do
unlines [
"@"
, "foo"
, "bar"
, "baz"
, "@"
] `shouldParseTo` DocCodeBlock "foo\nbar\nbaz\n"
it "ignores trailing whitespace after the opening @" $ do
unlines [
"@ "
, "foo"
, "@"
] `shouldParseTo` DocCodeBlock "foo\n"
it "rejects code blocks that are not closed" $ do
unlines [
"@"
, "foo"
] `shouldParseTo` DocParagraph "@\nfoo"
it "accepts nested markup" $ do
unlines [
"@"
, "/foo/"
, "@"
] `shouldParseTo` DocCodeBlock (DocEmphasis "foo" <> "\n")
it "allows to escape the @" $ do
unlines [
"@"
, "foo"
, "\\@"
, "bar"
, "@"
] `shouldParseTo` DocCodeBlock "foo\n@\nbar\n"
it "accepts horizontal space before the @" $ do
unlines [ " @"
, "foo"
, ""
, "bar"
, "@"
] `shouldParseTo` DocCodeBlock "foo\n\nbar\n"
it "strips a leading space from a @ block if present" $ do
unlines [ " @"
, " hello"
, " world"
, " @"
] `shouldParseTo` DocCodeBlock "hello\nworld\n"
unlines [ " @"
, " hello"
, ""
, " world"
, " @"
] `shouldParseTo` DocCodeBlock "hello\n\nworld\n"
it "only drops whitespace if there's some before closing @" $ do
unlines [ "@"
, " Formatting"
, " matters."
, "@"
]
`shouldParseTo` DocCodeBlock " Formatting\n matters.\n"
it "accepts unicode" $ do
"@foo 灼眼のシャナ bar@" `shouldParseTo` DocCodeBlock "foo 灼眼のシャナ bar"
it "requires the closing @" $ do
"@foo /bar/ baz"
`shouldParseTo` DocParagraph ("@foo " <> DocEmphasis "bar" <> " baz")
context "when parsing examples" $ do
it "parses a simple example" $ do
">>> foo" `shouldParseTo` DocExamples [Example "foo" []]
it "parses an example with result" $ do
unlines [
">>> foo"
, "bar"
, "baz"
] `shouldParseTo` DocExamples [Example "foo" ["bar", "baz"]]
it "parses consecutive examples" $ do
unlines [
">>> fib 5"
, "5"
, ">>> fib 10"
, "55"
] `shouldParseTo` DocExamples [
Example "fib 5" ["5"]
, Example "fib 10" ["55"]
]
it ("requires an example to be separated"
++ " from a previous paragraph by an empty line") $ do
"foobar\n\n>>> fib 10\n55" `shouldParseTo`
DocParagraph "foobar"
<> DocExamples [Example "fib 10" ["55"]]
it "parses bird-tracks inside of paragraphs as plain strings" $ do
let xs = "foo\n>>> bar"
xs `shouldParseTo` DocParagraph (DocString xs)
it "skips empty lines in front of an example" $ do
"\n \n\n>>> foo" `shouldParseTo` DocExamples [Example "foo" []]
it "terminates example on empty line" $ do
unlines [
">>> foo"
, "bar"
, " "
, "baz"
]
`shouldParseTo`
DocExamples [Example "foo" ["bar"]] <> DocParagraph "baz"
it "parses a <BLANKLINE> result as an empty result" $ do
unlines [
">>> foo"
, "bar"
, "<BLANKLINE>"
, "baz"
]
`shouldParseTo` DocExamples [Example "foo" ["bar", "", "baz"]]
it "accepts unicode in examples" $ do
">>> 灼眼\nシャナ" `shouldParseTo` DocExamples [Example "灼眼" ["シャナ"]]
context "when prompt is prefixed by whitespace" $ do
it "strips the exact same amount of whitespace from result lines" $ do
unlines [
" >>> foo"
, " bar"
, " baz"
] `shouldParseTo` DocExamples [Example "foo" ["bar", "baz"]]
it "preserves additional whitespace" $ do
unlines [
" >>> foo"
, " bar"
] `shouldParseTo` DocExamples [Example "foo" [" bar"]]
it "keeps original if stripping is not possible" $ do
unlines [
" >>> foo"
, " bar"
] `shouldParseTo` DocExamples [Example "foo" [" bar"]]
context "when parsing paragraphs nested in lists" $ do
it "can nest the same type of list" $ do
"* foo\n\n * bar" `shouldParseTo`
DocUnorderedList [ DocParagraph "foo"
<> DocUnorderedList [DocParagraph "bar"]]
it "can nest another type of list inside" $ do
"* foo\n\n 1. bar" `shouldParseTo`
DocUnorderedList [ DocParagraph "foo"
<> DocOrderedList [DocParagraph "bar"]]
it "can nest a code block inside" $ do
"* foo\n\n @foo bar baz@" `shouldParseTo`
DocUnorderedList [ DocParagraph "foo"
<> DocCodeBlock "foo bar baz"]
"* foo\n\n @\n foo bar baz\n @" `shouldParseTo`
DocUnorderedList [ DocParagraph "foo"
<> DocCodeBlock "foo bar baz\n"]
it "can nest more than one level" $ do
"* foo\n\n * bar\n\n * baz\n qux" `shouldParseTo`
DocUnorderedList [ DocParagraph "foo"
<> DocUnorderedList [ DocParagraph "bar"
<> DocUnorderedList [DocParagraph "baz\nqux"]
]
]
it "won't fail on not fully indented paragraph" $ do
"* foo\n\n * bar\n\n * qux\nquux" `shouldParseTo`
DocUnorderedList [ DocParagraph "foo"
<> DocUnorderedList [ DocParagraph "bar" ]
, DocParagraph "qux\nquux"]
it "can nest definition lists" $ do
"[a]: foo\n\n [b]: bar\n\n [c]: baz\n qux" `shouldParseTo`
DocDefList [ ("a", "foo"
<> DocDefList [ ("b", "bar"
<> DocDefList [("c", "baz\nqux")])
])
]
it "can come back to top level with a different list" $ do
"* foo\n\n * bar\n\n1. baz" `shouldParseTo`
DocUnorderedList [ DocParagraph "foo"
<> DocUnorderedList [ DocParagraph "bar" ]
]
<> DocOrderedList [ DocParagraph "baz" ]
it "definition lists can come back to top level with a different list" $ do
"[foo]: foov\n\n [bar]: barv\n\n1. baz" `shouldParseTo`
DocDefList [ ("foo", "foov"
<> DocDefList [ ("bar", "barv") ])
]
<> DocOrderedList [ DocParagraph "baz" ]
it "list order is preserved in presence of nesting + extra text" $ do
"1. Foo\n\n > Some code\n\n2. Bar\n\nSome text"
`shouldParseTo`
DocOrderedList [ DocParagraph "Foo" <> DocCodeBlock "Some code"
, DocParagraph "Bar"
]
<> DocParagraph (DocString "Some text")
"1. Foo\n\n2. Bar\n\nSome text"
`shouldParseTo`
DocOrderedList [ DocParagraph "Foo"
, DocParagraph "Bar"
]
<> DocParagraph (DocString "Some text")
context "when parsing properties" $ do
it "can parse a single property" $ do
"prop> 23 == 23" `shouldParseTo` DocProperty "23 == 23"
it "can parse multiple subsequent properties" $ do
unlines [
"prop> 23 == 23"
, "prop> 42 == 42"
]
`shouldParseTo`
DocProperty "23 == 23" <> DocProperty "42 == 42"
it "accepts unicode in properties" $ do
"prop> 灼眼のシャナ ≡ 愛" `shouldParseTo`
DocProperty "灼眼のシャナ ≡ 愛"
it "can deal with whitespace before and after the prop> prompt" $ do
" prop> xs == (reverse $ reverse xs) " `shouldParseTo`
DocProperty "xs == (reverse $ reverse xs)"
context "when parsing unordered lists" $ do
it "parses a simple list" $ do
unlines [
" * one"
, " * two"
, " * three"
]
`shouldParseTo` DocUnorderedList [
DocParagraph "one"
, DocParagraph "two"
, DocParagraph "three"
]
it "ignores empty lines between list items" $ do
unlines [
"* one"
, ""
, "* two"
]
`shouldParseTo` DocUnorderedList [
DocParagraph "one"
, DocParagraph "two"
]
it "accepts an empty list item" $ do
"*" `shouldParseTo` DocUnorderedList [DocParagraph DocEmpty]
it "accepts multi-line list items" $ do
unlines [
"* point one"
, " more one"
, "* point two"
, "more two"
]
`shouldParseTo` DocUnorderedList [
DocParagraph "point one\n more one"
, DocParagraph "point two\nmore two"
]
it "accepts markup in list items" $ do
"* /foo/" `shouldParseTo` DocUnorderedList [DocParagraph (DocEmphasis "foo")]
it "requires empty lines between list and other paragraphs" $ do
unlines [
"foo"
, ""
, "* bar"
, ""
, "baz"
]
`shouldParseTo` DocParagraph "foo" <> DocUnorderedList [DocParagraph "bar"] <> DocParagraph "baz"
context "when parsing ordered lists" $ do
it "parses a simple list" $ do
unlines [
" 1. one"
, " (1) two"
, " 3. three"
]
`shouldParseTo` DocOrderedList [
DocParagraph "one"
, DocParagraph "two"
, DocParagraph "three"
]
it "ignores empty lines between list items" $ do
unlines [
"1. one"
, ""
, "2. two"
]
`shouldParseTo` DocOrderedList [
DocParagraph "one"
, DocParagraph "two"
]
it "accepts an empty list item" $ do
"1." `shouldParseTo` DocOrderedList [DocParagraph DocEmpty]
it "accepts multi-line list items" $ do
unlines [
"1. point one"
, " more one"
, "1. point two"
, "more two"
]
`shouldParseTo` DocOrderedList [
DocParagraph "point one\n more one"
, DocParagraph "point two\nmore two"
]
it "accepts markup in list items" $ do
"1. /foo/" `shouldParseTo` DocOrderedList [DocParagraph (DocEmphasis "foo")]
it "requires empty lines between list and other paragraphs" $ do
unlines [
"foo"
, ""
, "1. bar"
, ""
, "baz"
]
`shouldParseTo` DocParagraph "foo" <> DocOrderedList [DocParagraph "bar"] <> DocParagraph "baz"
context "when parsing definition lists" $ do
it "parses a simple list" $ do
unlines [
" [foo]: one"
, " [bar]: two"
, " [baz]: three"
]
`shouldParseTo` DocDefList [
("foo", "one")
, ("bar", "two")
, ("baz", "three")
]
it "ignores empty lines between list items" $ do
unlines [
"[foo]: one"
, ""
, "[bar]: two"
]
`shouldParseTo` DocDefList [
("foo", "one")
, ("bar", "two")
]
it "accepts an empty list item" $ do
"[foo]:" `shouldParseTo` DocDefList [("foo", DocEmpty)]
it "accepts multi-line list items" $ do
unlines [
"[foo]: point one"
, " more one"
, "[bar]: point two"
, "more two"
]
`shouldParseTo` DocDefList [
("foo", "point one\n more one")
, ("bar", "point two\nmore two")
]
it "accepts markup in list items" $ do
"[foo]: /foo/" `shouldParseTo` DocDefList [("foo", DocEmphasis "foo")]
it "accepts markup for the label" $ do
"[/foo/]: bar" `shouldParseTo` DocDefList [(DocEmphasis "foo", "bar")]
it "requires empty lines between list and other paragraphs" $ do
unlines [
"foo"
, ""
, "[foo]: bar"
, ""
, "baz"
]
`shouldParseTo` DocParagraph "foo" <> DocDefList [("foo", "bar")] <> DocParagraph "baz"
it "dose not require the colon (deprecated - this will be removed in a future release)" $ do
unlines [
" [foo] one"
, " [bar] two"
, " [baz] three"
]
`shouldParseTo` DocDefList [
("foo", "one")
, ("bar", "two")
, ("baz", "three")
]
context "when parsing consecutive paragraphs" $ do
it "will not capture irrelevant consecutive lists" $ do
unlines [ " * bullet"
, ""
, ""
, " - different bullet"
, ""
, ""
, " (1) ordered"
, " "
, " 2. different bullet"
, " "
, " [cat]: kitten"
, " "
, " [pineapple]: fruit"
] `shouldParseTo`
DocUnorderedList [ DocParagraph "bullet"
, DocParagraph "different bullet"]
<> DocOrderedList [ DocParagraph "ordered"
, DocParagraph "different bullet"
]
<> DocDefList [ ("cat", "kitten")
, ("pineapple", "fruit")
]
context "when parsing function documentation headers" $ do
it "can parse a simple header" $ do
"= Header 1\nHello." `shouldParseTo`
(DocHeader (Header 1 "Header 1"))
<> DocParagraph "Hello."
it "allow consecutive headers" $ do
"= Header 1\n== Header 2" `shouldParseTo`
DocHeader (Header 1 "Header 1")
<> DocHeader (Header 2 "Header 2")
it "accepts markup in the header" $ do
"= /Header/ __1__\nFoo" `shouldParseTo`
DocHeader (Header 1 (DocEmphasis "Header" <> " " <> DocBold "1"))
<> DocParagraph "Foo"
|
JPMoresmau/haddock
|
haddock-library/test/Documentation/Haddock/ParserSpec.hs
|
bsd-2-clause
| 33,142
| 0
| 27
| 11,404
| 6,454
| 3,152
| 3,302
| 716
| 2
|
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, UndecidableInstances #-}
{-|
Tools for extracting unique variables from various types that contain them. -}
module BRC.Solver.VariablesIn where
import Data.List (nub)
import qualified Data.Set as DS
import BRC.Constraint
-- | A class for types that contain variables, and can say what those
-- variables are.
class VariablesIn v t | t -> v where
variablesIn :: t -> [v]
-- ^ The list of unique variables in the input.
instance VariablesIn v (Relatee v e) where
variablesIn (Variable v) = [v]
variablesIn (Constant _) = []
instance (Eq v) => VariablesIn v (Constraint v e) where
variablesIn (Related a b) = nub (variablesIn a ++ variablesIn b)
instance (Ord v, VariablesIn v t) => VariablesIn v [t] where
variablesIn = unique . concatMap variablesIn
instance (Ord v, VariablesIn v a, VariablesIn v b) => VariablesIn v (a,b) where
variablesIn (a,b) = unique (variablesIn a ++ variablesIn b)
unique :: (Ord v) => [v] -> [v]
unique = DS.toList . DS.fromList
|
kcharter/brc-solver
|
BRC/Solver/VariablesIn.hs
|
bsd-2-clause
| 1,128
| 0
| 9
| 260
| 324
| 176
| 148
| 18
| 1
|
{-# LANGUAGE Haskell2010 #-}
{-# LANGUAGE TypeFamilies #-}
module Types where
data Quux = Bar | Baz
newtype Foo = Foo ()
type FooQuux = (Foo, Quux)
type QuuxFoo = (Quux, Foo)
data family Norf a b
data instance Norf Foo Quux = NFQ Foo Quux
data instance Norf Quux Foo = NQF Quux Foo
type family Norf' a b
type instance Norf' Foo Quux = (Foo, Quux)
type instance Norf' Quux Foo = (Quux, Foo)
norf1 :: Norf Foo Quux -> Int
norf1 (NFQ (Foo ()) Bar) = 0
norf1 (NFQ (Foo ()) Baz) = 1
norf2 :: Norf Quux Foo -> Int
norf2 (NQF Bar (Foo ())) = 0
norf2 (NQF Baz (Foo ())) = 1
norf1' :: Norf' Foo Quux -> Int
norf1' (Foo (), Bar) = 0
norf1' (Foo (), Baz) = 1
norf2' :: Norf' Quux Foo -> Int
norf2' (Bar, Foo ()) = 0
norf2' (Baz, Foo ()) = 1
|
haskell/haddock
|
hypsrc-test/src/Types.hs
|
bsd-2-clause
| 748
| 0
| 10
| 174
| 363
| 199
| 164
| 25
| 1
|
{-# LANGUAGE BangPatterns,CPP #-}
#if __GLASGOW_HASKELL__ >= 702
{-# LANGUAGE Trustworthy #-}
#endif
-- |
-- Module : Data.Text.Lazy.Encoding
-- Copyright : (c) 2009, 2010 Bryan O'Sullivan
--
-- License : BSD-style
-- Maintainer : bos@serpentine.com
-- Stability : experimental
-- Portability : portable
--
-- Functions for converting lazy 'Text' values to and from lazy
-- 'ByteString', using several standard encodings.
--
-- To gain access to a much larger variety of encodings, use the
-- @text-icu@ package: <http://hackage.haskell.org/package/text-icu>
module Data.Text.Lazy.Encoding
(
-- * Decoding ByteStrings to Text
-- $strict
decodeASCII
, decodeLatin1
, decodeUtf8
, decodeUtf16LE
, decodeUtf16BE
, decodeUtf32LE
, decodeUtf32BE
-- ** Catchable failure
, decodeUtf8'
-- ** Controllable error handling
, decodeUtf8With
, decodeUtf16LEWith
, decodeUtf16BEWith
, decodeUtf32LEWith
, decodeUtf32BEWith
-- * Encoding Text to ByteStrings
, encodeUtf8
, encodeUtf16LE
, encodeUtf16BE
, encodeUtf32LE
, encodeUtf32BE
-- * Encoding Text using ByteString Builders
, encodeUtf8Builder
, encodeUtf8BuilderEscaped
) where
import Control.Exception (evaluate, try)
import Data.Monoid (Monoid(..))
import Data.Text.Encoding.Error (OnDecodeError, UnicodeException, strictDecode)
import Data.Text.Internal.Lazy (Text(..), chunk, empty, foldrChunks)
import Data.Word (Word8)
import qualified Data.ByteString as S
import qualified Data.ByteString.Builder as B
import qualified Data.ByteString.Builder.Extra as B (safeStrategy, toLazyByteStringWith)
import qualified Data.ByteString.Builder.Prim as BP
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString.Lazy.Internal as B
import qualified Data.ByteString.Unsafe as B
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.Text.Internal.Lazy.Encoding.Fusion as E
import qualified Data.Text.Internal.Lazy.Fusion as F
import Data.Text.Unsafe (unsafeDupablePerformIO)
-- $strict
--
-- All of the single-parameter functions for decoding bytestrings
-- encoded in one of the Unicode Transformation Formats (UTF) operate
-- in a /strict/ mode: each will throw an exception if given invalid
-- input.
--
-- Each function has a variant, whose name is suffixed with -'With',
-- that gives greater control over the handling of decoding errors.
-- For instance, 'decodeUtf8' will throw an exception, but
-- 'decodeUtf8With' allows the programmer to determine what to do on a
-- decoding error.
-- | /Deprecated/. Decode a 'ByteString' containing 7-bit ASCII
-- encoded text.
decodeASCII :: B.ByteString -> Text
decodeASCII = decodeUtf8
{-# DEPRECATED decodeASCII "Use decodeUtf8 instead" #-}
-- | Decode a 'ByteString' containing Latin-1 (aka ISO-8859-1) encoded text.
decodeLatin1 :: B.ByteString -> Text
decodeLatin1 = foldr (chunk . TE.decodeLatin1) empty . B.toChunks
-- | Decode a 'ByteString' containing UTF-8 encoded text.
decodeUtf8With :: OnDecodeError -> B.ByteString -> Text
decodeUtf8With onErr (B.Chunk b0 bs0) =
case TE.streamDecodeUtf8With onErr b0 of
TE.Some t l f -> chunk t (go f l bs0)
where
go f0 _ (B.Chunk b bs) =
case f0 b of
TE.Some t l f -> chunk t (go f l bs)
go _ l _
| S.null l = empty
| otherwise = case onErr desc (Just (B.unsafeHead l)) of
Nothing -> empty
Just c -> Chunk (T.singleton c) Empty
desc = "Data.Text.Lazy.Encoding.decodeUtf8With: Invalid UTF-8 stream"
decodeUtf8With _ _ = empty
-- | Decode a 'ByteString' containing UTF-8 encoded text that is known
-- to be valid.
--
-- If the input contains any invalid UTF-8 data, an exception will be
-- thrown that cannot be caught in pure code. For more control over
-- the handling of invalid data, use 'decodeUtf8'' or
-- 'decodeUtf8With'.
decodeUtf8 :: B.ByteString -> Text
decodeUtf8 = decodeUtf8With strictDecode
{-# INLINE[0] decodeUtf8 #-}
-- This rule seems to cause performance loss.
{- RULES "LAZY STREAM stream/decodeUtf8' fusion" [1]
forall bs. F.stream (decodeUtf8' bs) = E.streamUtf8 strictDecode bs #-}
-- | Decode a 'ByteString' containing UTF-8 encoded text..
--
-- If the input contains any invalid UTF-8 data, the relevant
-- exception will be returned, otherwise the decoded text.
--
-- /Note/: this function is /not/ lazy, as it must decode its entire
-- input before it can return a result. If you need lazy (streaming)
-- decoding, use 'decodeUtf8With' in lenient mode.
decodeUtf8' :: B.ByteString -> Either UnicodeException Text
decodeUtf8' bs = unsafeDupablePerformIO $ do
let t = decodeUtf8 bs
try (evaluate (rnf t `seq` t))
where
rnf Empty = ()
rnf (Chunk _ ts) = rnf ts
{-# INLINE decodeUtf8' #-}
encodeUtf8 :: Text -> B.ByteString
encodeUtf8 Empty = B.empty
encodeUtf8 lt@(Chunk t _) =
B.toLazyByteStringWith strategy B.empty $ encodeUtf8Builder lt
where
-- To improve our small string performance, we use a strategy that
-- allocates a buffer that is guaranteed to be large enough for the
-- encoding of the first chunk, but not larger than the default
-- B.smallChunkSize. We clamp the firstChunkSize to ensure that we don't
-- generate too large buffers which hamper streaming.
firstChunkSize = min B.smallChunkSize (4 * (T.length t + 1))
strategy = B.safeStrategy firstChunkSize B.defaultChunkSize
encodeUtf8Builder :: Text -> B.Builder
encodeUtf8Builder =
foldrChunks (\c b -> TE.encodeUtf8Builder c `mappend` b) Data.Monoid.mempty
{-# INLINE encodeUtf8BuilderEscaped #-}
encodeUtf8BuilderEscaped :: BP.BoundedPrim Word8 -> Text -> B.Builder
encodeUtf8BuilderEscaped prim =
foldrChunks (\c b -> TE.encodeUtf8BuilderEscaped prim c `mappend` b) mempty
-- | Decode text from little endian UTF-16 encoding.
decodeUtf16LEWith :: OnDecodeError -> B.ByteString -> Text
decodeUtf16LEWith onErr bs = F.unstream (E.streamUtf16LE onErr bs)
{-# INLINE decodeUtf16LEWith #-}
-- | Decode text from little endian UTF-16 encoding.
--
-- If the input contains any invalid little endian UTF-16 data, an
-- exception will be thrown. For more control over the handling of
-- invalid data, use 'decodeUtf16LEWith'.
decodeUtf16LE :: B.ByteString -> Text
decodeUtf16LE = decodeUtf16LEWith strictDecode
{-# INLINE decodeUtf16LE #-}
-- | Decode text from big endian UTF-16 encoding.
decodeUtf16BEWith :: OnDecodeError -> B.ByteString -> Text
decodeUtf16BEWith onErr bs = F.unstream (E.streamUtf16BE onErr bs)
{-# INLINE decodeUtf16BEWith #-}
-- | Decode text from big endian UTF-16 encoding.
--
-- If the input contains any invalid big endian UTF-16 data, an
-- exception will be thrown. For more control over the handling of
-- invalid data, use 'decodeUtf16BEWith'.
decodeUtf16BE :: B.ByteString -> Text
decodeUtf16BE = decodeUtf16BEWith strictDecode
{-# INLINE decodeUtf16BE #-}
-- | Encode text using little endian UTF-16 encoding.
encodeUtf16LE :: Text -> B.ByteString
encodeUtf16LE txt = B.fromChunks (foldrChunks ((:) . TE.encodeUtf16LE) [] txt)
{-# INLINE encodeUtf16LE #-}
-- | Encode text using big endian UTF-16 encoding.
encodeUtf16BE :: Text -> B.ByteString
encodeUtf16BE txt = B.fromChunks (foldrChunks ((:) . TE.encodeUtf16BE) [] txt)
{-# INLINE encodeUtf16BE #-}
-- | Decode text from little endian UTF-32 encoding.
decodeUtf32LEWith :: OnDecodeError -> B.ByteString -> Text
decodeUtf32LEWith onErr bs = F.unstream (E.streamUtf32LE onErr bs)
{-# INLINE decodeUtf32LEWith #-}
-- | Decode text from little endian UTF-32 encoding.
--
-- If the input contains any invalid little endian UTF-32 data, an
-- exception will be thrown. For more control over the handling of
-- invalid data, use 'decodeUtf32LEWith'.
decodeUtf32LE :: B.ByteString -> Text
decodeUtf32LE = decodeUtf32LEWith strictDecode
{-# INLINE decodeUtf32LE #-}
-- | Decode text from big endian UTF-32 encoding.
decodeUtf32BEWith :: OnDecodeError -> B.ByteString -> Text
decodeUtf32BEWith onErr bs = F.unstream (E.streamUtf32BE onErr bs)
{-# INLINE decodeUtf32BEWith #-}
-- | Decode text from big endian UTF-32 encoding.
--
-- If the input contains any invalid big endian UTF-32 data, an
-- exception will be thrown. For more control over the handling of
-- invalid data, use 'decodeUtf32BEWith'.
decodeUtf32BE :: B.ByteString -> Text
decodeUtf32BE = decodeUtf32BEWith strictDecode
{-# INLINE decodeUtf32BE #-}
-- | Encode text using little endian UTF-32 encoding.
encodeUtf32LE :: Text -> B.ByteString
encodeUtf32LE txt = B.fromChunks (foldrChunks ((:) . TE.encodeUtf32LE) [] txt)
{-# INLINE encodeUtf32LE #-}
-- | Encode text using big endian UTF-32 encoding.
encodeUtf32BE :: Text -> B.ByteString
encodeUtf32BE txt = B.fromChunks (foldrChunks ((:) . TE.encodeUtf32BE) [] txt)
{-# INLINE encodeUtf32BE #-}
|
hvr/text
|
Data/Text/Lazy/Encoding.hs
|
bsd-2-clause
| 8,947
| 0
| 14
| 1,611
| 1,409
| 822
| 587
| 118
| 3
|
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.HP.OcclusionTest
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.HP.OcclusionTest (
-- * Extension Support
glGetHPOcclusionTest,
gl_HP_occlusion_test,
-- * Enums
pattern GL_OCCLUSION_TEST_HP,
pattern GL_OCCLUSION_TEST_RESULT_HP
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/HP/OcclusionTest.hs
|
bsd-3-clause
| 686
| 0
| 5
| 95
| 52
| 39
| 13
| 8
| 0
|
{-# LANGUAGE TypeFamilies, TupleSections, OverloadedStrings #-}
module File.Binary.Classes (Field(..), Binary(..), pop, push) where
import Data.ByteString.Lazy (ByteString, unpack, singleton, cons')
import qualified Data.ByteString.Lazy.Char8 as BSLC ()
import Data.Bits ((.&.), (.|.), shiftL, shiftR)
import Data.Monoid (Monoid, mappend, mempty)
import Data.Word
import Control.Arrow (first, second)
import Control.Applicative
import Control.Monad
type AddBits b = ([Bool], b)
class Field f where
type FieldArgument f
fromBinary :: (Binary b, Applicative m, Monad m) => FieldArgument f -> b -> m (f, b)
toBinary :: (Binary b, Applicative m, Monad m) => FieldArgument f -> f -> m b
fromBits :: (Binary b, Applicative m, Monad m) =>
FieldArgument f -> AddBits b -> m (f, AddBits b)
consToBits :: (Binary b, Applicative m, Monad m) =>
FieldArgument f -> f -> AddBits b -> m (AddBits b)
fromBits a ([], b) = second ([] ,) `liftM` fromBinary a b
fromBits _ _ = error "fromBits: not bytes (1 byte = 8 bits)"
consToBits a f ([], b) = do
ret <- (`mappend` b) <$> toBinary a f
return ([], ret)
consToBits _ _ (bits, _) =
fail $ "consToBits: not bytes (1 byte = 8 bits) " ++ show bits
fromBinary a b = do
ret <- fromBits a ([], b)
case ret of
(f, ([], rest)) -> return (f, rest)
_ -> fail "fromBinary: not bytes (1 byte = 8 bits)"
toBinary a f = do
ret <- consToBits a f ([], mempty)
case ret of
([], bin) -> return bin
(bits, _) -> fail $
"toBinary: not bytes (1 byte = 8 bits) " ++ show bits
pop :: Binary b => b -> AddBits b
pop = first (wtbs (8 :: Int) . head . unpack) . getBytes 1
where
wtbs 0 _ = []
wtbs n w = toEnum (fromIntegral $ 1 .&. w) : wtbs (n - 1) (w `shiftR` 1)
push :: Binary b => AddBits b -> b
push = uncurry $ mappend . makeBinary . singleton . bstw
where
bstw = foldr (\b w -> w `shiftL` 1 .|. fromIntegral (fromEnum b)) 0
class (Eq b, Monoid b) => Binary b where
getBytes :: Int -> b -> (ByteString, b)
spanBytes :: (Word8 -> Bool) -> b -> (ByteString, b)
unconsByte :: b -> (Word8, b)
makeBinary :: ByteString -> b
getBytes 0 b = ("", b)
getBytes n b = let
(h, t) = unconsByte b
(r, b') = getBytes (n - 1) t in
(h `cons'` r, b')
spanBytes p b
| b == makeBinary "" = ("", b)
| p h = let (ret, rest) = spanBytes p t in (h `cons'` ret, rest)
| otherwise = ("", b)
where
(h, t) = unconsByte b
|
YoshikuniJujo/binary-file
|
src/File/Binary/Classes.hs
|
bsd-3-clause
| 2,389
| 10
| 14
| 534
| 1,132
| 611
| 521
| 59
| 2
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DuplicateRecordFields #-}
module Mapnik.ImageFilter (
ImageFilter(..)
, ColorStop (..)
, parse
, parseMany
, toText
, toTextMany
, imageFilterParser
) where
import Mapnik.Imports
import Mapnik.Util
import Mapnik.Color (Color, colorParser)
import qualified Mapnik.Color as Color
import Control.Applicative (optional)
import Data.Monoid
import Data.List
import Data.Text (Text)
import qualified Data.Text as T
import Data.Attoparsec.Text hiding (parse)
import Data.Text.Lazy (toStrict)
import Data.Text.Lazy.Builder
import qualified Data.Text.Lazy.Builder as B
import qualified Data.Text.Lazy.Builder.Int as B
import qualified Data.Text.Lazy.Builder.RealFloat as B
data ColorStop = ColorStop
{ color :: Color
, value :: Maybe Double
} deriving (Eq, Show, Generic)
deriveMapnikJSON ''ColorStop
data ImageFilter
= Blur
| Emboss
| Sharpen
| EdgeDetect
| Sobel
| Gray
| XGradient
| YGradient
| Invert
| ColorBlindProtanope
| ColorBlindDeuteranope
| ColorBlindTritanope
| AggStackBlur Int Int
| ColorToAlpha Color
| ScaleHsla Double Double Double Double Double Double Double Double
| ColorizeAlpha [ColorStop]
deriving (Eq, Show, Generic)
deriveMapnikJSON ''ImageFilter
parseMany :: Text -> Either String [ImageFilter]
parseMany = parseOnly (imageFilterParser `sepBy` (optional space) <* endOfInput)
parse :: Text -> Either String ImageFilter
parse = parseOnly (imageFilterParser <* endOfInput)
imageFilterParser :: Parser ImageFilter
imageFilterParser = choice [
"blur" *> pure Blur
, "emboss" *> pure Emboss
, "sharpen" *> pure Sharpen
, "edge-detect" *> pure EdgeDetect
, "sobel" *> pure Sobel
, "gray" *> pure Gray
, "x-gradient" *> pure XGradient
, "y-gradient" *> pure YGradient
, "invert" *> pure Invert
, "color-blind-protanope" *> pure ColorBlindProtanope
, "color-blind-deuteranope" *> pure ColorBlindDeuteranope
, "color-blind-tritanope" *> pure ColorBlindTritanope
, "agg-stack-blur" *> bracketed (do
[rx,ry] <- sepByCommas (signed decimal)
pure (AggStackBlur rx ry)
)
, "scale-hsla" *> bracketed (do
[a,b,c,d,e,f,g,h] <- sepByCommas (signed cppDouble)
pure (ScaleHsla a b c d e f g h)
)
, "color-to-alpha" *> (ColorToAlpha <$> bracketed (stripWs colorParser))
, "colorize-alpha" *> (ColorizeAlpha <$> bracketed (sepByCommas stopParser))
]
where
stopParser = ColorStop <$> colorParser <*> optional (skipSpace *> signed cppDouble)
toText :: ImageFilter -> Text
toText Blur = "blur"
toText Emboss = "emboss"
toText Sharpen = "sharpen"
toText EdgeDetect = "edge-detect"
toText Sobel = "sobel"
toText Gray = "gray"
toText XGradient = "x-gradient"
toText YGradient = "y-gradient"
toText Invert = "invert"
toText ColorBlindProtanope = "color-blind-protanope"
toText ColorBlindDeuteranope = "color-blind-deuteranope"
toText ColorBlindTritanope = "color-blind-tritanope"
toText (AggStackBlur a b) = toStrict $ toLazyText $
"agg-stack-blur(" <> B.decimal a <> ", " <> B.decimal b <> ")"
toText (ColorToAlpha a) = toStrict $ toLazyText $
"color-to-alpha(" <> B.fromText (Color.toText a) <> ")"
toText (ScaleHsla a b c d e f g h) = toStrict $ toLazyText $ (mconcat $
"scale-hsla(" : intersperse ", " nums) <> ")"
where nums = map (B.formatRealFloat B.Fixed Nothing) [a,b,c,d,e,f,g,h]
toText (ColorizeAlpha stops) = toStrict $ toLazyText $ (mconcat $
"colorize-alpha(" : intersperse ", " (map strStop stops)) <> ")"
where
strStop (ColorStop c o) =
B.fromText (Color.toText c)
<> maybe "" ((" " <>) . B.formatRealFloat B.Fixed Nothing) o
toTextMany :: [ImageFilter] -> Text
toTextMany = T.intercalate " " . map toText
|
albertov/hs-mapnik
|
pure/src/Mapnik/ImageFilter.hs
|
bsd-3-clause
| 3,785
| 0
| 15
| 658
| 1,175
| 639
| 536
| 105
| 1
|
module Distribution.Solver.Modular.Index
( Index
, PInfo(..)
, defaultQualifyOptions
, mkIndex
) where
import Data.List as L
import Data.Map as M
import Prelude hiding (pi)
import Distribution.Solver.Modular.Dependency
import Distribution.Solver.Modular.Flag
import Distribution.Solver.Modular.Package
import Distribution.Solver.Modular.Tree
import Distribution.Solver.Types.ComponentDeps (Component)
-- | An index contains information about package instances. This is a nested
-- dictionary. Package names are mapped to instances, which in turn is mapped
-- to info.
type Index = Map PN (Map I PInfo)
-- | Info associated with a package instance.
-- Currently, dependencies, flags and failure reasons.
-- Packages that have a failure reason recorded for them are disabled
-- globally, for reasons external to the solver. We currently use this
-- for shadowing which essentially is a GHC limitation, and for
-- installed packages that are broken.
data PInfo = PInfo (FlaggedDeps Component PN) FlagInfo (Maybe FailReason)
deriving (Show)
mkIndex :: [(PN, I, PInfo)] -> Index
mkIndex xs = M.map M.fromList (groupMap (L.map (\ (pn, i, pi) -> (pn, (i, pi))) xs))
groupMap :: Ord a => [(a, b)] -> Map a [b]
groupMap xs = M.fromListWith (flip (++)) (L.map (\ (x, y) -> (x, [y])) xs)
defaultQualifyOptions :: Index -> QualifyOptions
defaultQualifyOptions idx = QO {
qoBaseShim = or [ dep == base
| -- Find all versions of base ..
Just is <- [M.lookup base idx]
-- .. which are installed ..
, (I _ver (Inst _), PInfo deps _flagNfo _fr) <- M.toList is
-- .. and flatten all their dependencies ..
, (Dep _is_exe dep _ci, _comp) <- flattenFlaggedDeps deps
]
, qoSetupIndependent = True
}
where
base = PackageName "base"
|
sopvop/cabal
|
cabal-install/Distribution/Solver/Modular/Index.hs
|
bsd-3-clause
| 1,983
| 0
| 14
| 539
| 459
| 268
| 191
| 28
| 1
|
{-# LANGUAGE BangPatterns, CPP, OverloadedStrings #-}
import Control.Exception
import Control.Monad
import Data.Aeson
import Data.Attoparsec
import Data.Time.Clock
import System.Environment (getArgs)
import System.IO
import qualified Data.ByteString as B
import Control.DeepSeq
#if !MIN_VERSION_bytestring(0,10,0)
import qualified Data.ByteString.Lazy.Internal as L
instance NFData L.ByteString where
rnf = go
where go (L.Chunk _ cs) = go cs
go L.Empty = ()
{-# INLINE rnf #-}
#endif
main :: IO ()
main = do
(cnt:args) <- getArgs
let count = read cnt :: Int
forM_ args $ \arg -> bracket (openFile arg ReadMode) hClose $ \h -> do
putStrLn $ arg ++ ":"
let refill = B.hGet h 16384
result0 <- parseWith refill json =<< refill
r0 <- case result0 of
Done _ r -> return r
_ -> fail $ "failed to read " ++ show arg
start <- getCurrentTime
let loop !n r
| n >= count = return ()
| otherwise = {-# SCC "loop" #-} do
rnf (encode r) `seq` loop (n+1) r
loop 0 r0
delta <- flip diffUTCTime start `fmap` getCurrentTime
let rate = fromIntegral count / realToFrac delta :: Double
putStrLn $ " " ++ show delta
putStrLn $ " " ++ show (round rate :: Int) ++ " per second"
|
moonKimura/aeson-0.6.2.1
|
benchmarks/AesonEncode.hs
|
bsd-3-clause
| 1,307
| 0
| 22
| 354
| 451
| 225
| 226
| 37
| 2
|
{-# LANGUAGE OverloadedStrings #-}
module LayoutHUnit
( layoutTestCases )
where
import Prelude hiding (lex, filter, map)
import qualified Data.Text as T
import qualified Data.Set as S
import Data.MonadicStream hiding (concat, concatMap)
import Language.Forvie.Lexing.Spec
import Language.Forvie.Lexing.Text
import Language.Forvie.Layout
import Text.Lexeme
import Test.HUnit
--------------------------------------------------------------------------------
data Token
= Atom
| Semicolon
| LBrace
| RBrace
| Block
deriving (Show, Eq, Ord)
instance Layout Token where
semicolon = Semicolon
lbrace = LBrace
rbrace = RBrace
blockOpener = S.fromList [Block]
lexicalSpec :: CompiledLexSpec (Action (NewlineOr Token))
lexicalSpec =
compileLexicalSpecification $
[ "x" :==> Emit (Token Atom)
, ";" :==> Emit (Token Semicolon)
, "{" :==> Emit (Token LBrace)
, "}" :==> Emit (Token RBrace)
, "block" :==> Emit (Token Block)
, "\n" :==> Emit Newline
, oneOrMore " " :==> Ignore Whitespace
]
-- FIXME: why isn't this part of Forvie?
exceptIgnorable :: Monad m => Processor (Lexeme (Action tok)) m (Lexeme tok)
exceptIgnorable = filter f
where f (Lexeme (Ignore _) _ _) = Nothing
f (Lexeme (Emit t) p s) = Just (Lexeme t p s)
lexer :: Monad m => T.Text -> Stream m (Lexeme (Action (NewlineOr Token)))
lexer = lex lexicalSpec (OnError $ \x -> fail (show x)) "<test input>"
doLayout :: Processor (Lexeme (Action (NewlineOr Token))) Maybe (Lexeme Token)
doLayout = exceptIgnorable >>> layout (OnLayoutError $ const Nothing)
--------------------------------------------------------------------------------
testCases :: [(T.Text, Maybe [Token])]
testCases =
[ ( "x x"
, Just [LBrace, Atom, Atom, RBrace])
, ( "x\nx"
, Just [LBrace, Atom, Semicolon, Atom, RBrace])
, ( "x\n x"
, Just [LBrace, Atom, Atom, RBrace])
, ( "block\n x\n x"
, Just [LBrace, Block, LBrace, Atom, Semicolon, Atom, RBrace, RBrace])
, ( "block\n x\nx"
, Just [LBrace, Block, LBrace, Atom, RBrace, Semicolon, Atom, RBrace])
, ( "block\n block\n x"
, Just [LBrace, Block, LBrace, Block, LBrace, RBrace, Semicolon, Atom, RBrace, RBrace])
, ( "block\n x\n x"
, Just [LBrace, Block, LBrace, Atom, Atom, RBrace, RBrace])
{-
, ( " block\n x\n x\nx"
, Just [LBrace, Block, LBrace, Atom, Semicolon, Atom, RBrace, RBrace])
-}
]
checkTestCase :: (T.Text, Maybe [Token]) -> Assertion
checkTestCase (input, expectedOutput) =
assertEqual "layout test case"
(lexer input |>> doLayout |>> map lexemeTok |>| toList)
expectedOutput
layoutTestCases :: Assertion
layoutTestCases = Prelude.mapM_ checkTestCase testCases
|
bobatkey/Forvie
|
tests/LayoutHUnit.hs
|
bsd-3-clause
| 2,927
| 0
| 13
| 745
| 862
| 487
| 375
| 65
| 2
|
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE StandaloneDeriving#-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
-- 2016-05-15
module LSystem where
data LSysF a = A a
| B a
| X
deriving (Show, Functor)
newtype Fix f = In (f (Fix f))
instance Show (f (Fix f)) => Show (Fix f) where
show (In x) = show x
out :: Fix f -> f (Fix f)
out (In x) = x
testVal1 :: Fix LSysF
testVal1 = In $ A $ In $ B $ In X
cata :: (Functor f) => (f a -> a) -> Fix f -> a
cata alg = alg . fmap (cata alg) . out
ana :: (Functor f) => (a -> f a) -> a -> Fix f
ana coalg = In . fmap (ana coalg) . coalg
fooLSys :: a -> LSysF a
fooLSys x = A x
barLSys :: LSysF (Fix (LSysF)) -> Fix (LSysF)
barLSys (A x) = In $ A $ In $ B x
barLSys (B x) = In $ A x
barLSys X = In $ X
-- plain old
data Alphabet = C
| D
deriving (Show)
rewrite :: [Alphabet] -> [Alphabet]
rewrite [] = []
rewrite (C:xs) = C:D:rewrite xs
rewrite (D:xs) = C:rewrite xs
fooV :: [Alphabet]
fooV = [C]
data RewriteF a = Rewrite [Alphabet] a
| Y
deriving (Show, Functor)
fooRewriteF :: Fix RewriteF -> RewriteF (Fix RewriteF)
fooRewriteF (In ( Rewrite [] x)) = Rewrite [] x
fooRewriteF (In ( Rewrite (C:xs) x)) = Rewrite (C:D:xs) x
fooRewriteF (In ( Rewrite (D:xs) x)) = Rewrite (C:xs) x
testRewriteF :: Fix (RewriteF)
testRewriteF = In $ Rewrite [C] (In Y)
|
sleexyz/haskell-fun
|
LSystem.hs
|
bsd-3-clause
| 1,476
| 0
| 11
| 407
| 719
| 374
| 345
| 45
| 1
|
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FlexibleContexts, ScopedTypeVariables #-}
module Control.Monad.Push.Class where
class Monad m => MonadPush a m where
-- | Push an item onto the stack
push :: a -> m ()
|
wyager/FastPush
|
src/Control/Monad/Push/Class.hs
|
bsd-3-clause
| 233
| 0
| 9
| 42
| 42
| 23
| 19
| 4
| 0
|
module Main where
import Lib
main :: IO ()
main = startGame
|
gtrogers/maybe-hero
|
app/Main.hs
|
bsd-3-clause
| 62
| 0
| 6
| 14
| 22
| 13
| 9
| 4
| 1
|
module TechnicalIndicators.Core
( dup
, dup3
, dup4
, dup5
, pair
, pair3
, pair4
, pair5
, cross
, cross3
, cross4
, cross5
, single
, para
, para3
, para4
, para5
) where
import Control.Arrow ((***))
import Control.Applicative (Applicative, (<$>), (<*>), liftA, liftA2, pure)
import Data.List (tails, unfoldr, unzip4, unzip5)
-- | special DSL which only use in this module
-- The argument `x` is supplied to only function `g`.
(~>) :: (a -> b) -> (t -> b -> c) -> t -> a -> c
f ~> g = (.) <$> g <*> const f
dup a = (a, a)
dup3 a = (a, a, a)
dup4 a = (a, a, a, a)
dup5 a = (a, a, a, a, a)
pair :: (a -> b) -> (a, a) -> (b, b)
pair f (a, b) = (f a, f b)
pair3 :: (a -> b) -> (a, a, a) -> (b, b, b)
pair3 f (a, b, c) = (f a, f b, f c)
pair4 :: (a -> b) -> (a, a, a, a) -> (b, b, b, b)
pair4 f (a, b, c, d) = (f a, f b, f c, f d)
pair5 :: (a -> b) -> (a, a, a, a, a) -> (b, b, b, b, b)
pair5 f (a, b, c, d, e) = (f a, f b, f c, f d, f e)
cross :: (a -> x, b -> y) -> (a, b) -> (x, y)
cross (f, g) (a, b) = (f a, g b)
cross3 :: (a -> x, b -> y, c -> z) -> (a, b, c) -> (x, y, z)
cross3 (f, g, h) (a, b, c) = (f a, g b, h c)
cross4 :: (a -> x, b -> y, c -> z, d -> w) -> (a, b, c, d) -> (x, y, z, w)
cross4 (f, g, h, j) (a, b, c, d) = (f a, g b, h c, j d)
cross5 :: (a -> x, b -> y, c -> z, d -> w, e -> v) -> (a, b, c, d, e) -> (x, y, z, w, v)
cross5 (f, g, h, j, k) (a, b, c, d, e) = (f a, g b, h c, j d, k e)
prepare :: [(k, Maybe v)] -> ([k], [[Maybe v]])
prepare = (id *** tails . cleansing) . unzip
cleansing :: [Maybe a] -> [Maybe a]
cleansing xs = unfoldr f (Nothing, xs)
where
f (old, []) = Nothing
f (old, x:xs) = Just $ maybe nothing just x
where
nothing = (old, (old, xs))
just x' = let new = Just x' in (new, (new, xs))
from :: [a] -> Int -> [a]
from xs n = tails xs !! (n-1)
single :: ((a -> a) -> Int -> [Maybe v] -> b)
-> Int -> [(k, Maybe v)] -> [(k, b)]
single average = prepare ~> accum
where
accum n = uncurry zip . (flip from n *** map (average id n))
-- | general utility function for para#
paraN _pair _zip _unzip _average ps (ks, vss)
= (ks `_from` ps) `_zip` (_unzip $ map (_average ps) vss)
where
_from = _pair . from
para :: (((a1 -> b1) -> (a1, a1) -> (b1, b1))
-> (Int, Int) -> [Maybe v] -> (b, b))
-> (Int, Int) -> [(a, Maybe v)] -> ([(a, b)], [(a, b)])
para average = prepare ~> paraN pair (cross . pair zip) unzip (average pair)
para3 :: (((a1 -> b1) -> (a1, a1, a1) -> (b1, b1, b1))
-> (Int, Int, Int) -> [Maybe v] -> (b, b, b))
-> (Int, Int, Int)
-> [(a, Maybe v)]
-> ([(a, b)], [(a, b)], [(a, b)])
para3 average = prepare ~> paraN pair3 (cross3 . pair3 zip) unzip3 (average pair3)
para4 :: (((a -> b1) -> (a, a, a, a) -> (b1, b1, b1, b1))
-> (Int, Int, Int, Int) -> [Maybe v] -> (b, b, b, b))
-> (Int, Int, Int, Int)
-> [(k, Maybe v)]
-> ([(k, b)], [(k, b)], [(k, b)], [(k, b)])
para4 average = prepare ~> paraN pair4 (cross4 . pair4 zip) unzip4 (average pair4)
para5 :: (((a -> b1) -> (a, a, a, a, a) -> (b1, b1, b1, b1, b1))
-> (Int, Int, Int, Int, Int) -> [Maybe v] -> (b, b, b, b, b))
-> (Int, Int, Int, Int, Int)
-> [(k, Maybe v)]
-> ([(k, b)], [(k, b)], [(k, b)], [(k, b)], [(k, b)])
para5 average = prepare ~> paraN pair5 (cross5 . pair5 zip) unzip5 (average pair5)
instance Num v => Num (Maybe v) where
(+) = liftA2 (+)
(*) = liftA2 (*)
(-) = liftA2 (-)
negate = liftA negate
abs = liftA abs
signum = liftA signum
fromInteger = pure . fromInteger
instance Fractional v => Fractional (Maybe v) where
(/) = liftA2 (/)
recip = liftA recip
fromRational = pure . fromRational
|
cutsea110/sig
|
sig-api/TechnicalIndicators/Core.hs
|
bsd-3-clause
| 3,857
| 0
| 13
| 1,174
| 2,399
| 1,392
| 1,007
| -1
| -1
|
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
module Duckling.Numeral.HU.Tests
( tests ) where
import Data.String
import Prelude
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Numeral.HU.Corpus
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "HU Tests"
[ makeCorpusTest [Seal Numeral] corpus
]
|
facebookincubator/duckling
|
tests/Duckling/Numeral/HU/Tests.hs
|
bsd-3-clause
| 503
| 0
| 9
| 77
| 79
| 50
| 29
| 11
| 1
|
import Test.QuickCheck
import qualified Foreign.C.Math.Double as C
main = sequence_
[ quickCheck $ \x -> C.acos x == acos x
, quickCheck $ \x -> C.asin x == asin x
, quickCheck $ \x -> C.atan x == atan x
-- note:
, quickCheck $ \x y -> C.atan2 x y == atan2 x y
, quickCheck $ \x -> C.cos x == cos x
, quickCheck $ \x -> C.sin x == sin x
, quickCheck $ \x -> C.tan x == tan x
, quickCheck $ \x -> C.cosh x == cosh x
, quickCheck $ \x -> C.sinh x == sinh x
, quickCheck $ \x -> C.tanh x == tanh x
, quickCheck $ \x -> C.exp x == exp x
, quickCheck $ \x -> C.log x == log x
, quickCheck $ \x y -> x >= 0 ==> C.pow x y == x ** y
, quickCheck $ \x -> x >= 0 ==> C.sqrt x == sqrt x
, quickCheck $ \x -> C.log10 x == (log x / log 10 )
]
|
barak/haskell-cmath
|
tests/QC.hs
|
bsd-3-clause
| 948
| 0
| 13
| 399
| 422
| 215
| 207
| -1
| -1
|
---------------------------------------------------------------------------------------------------
{-# LANGUAGE QuasiQuotes #-}
{-# OPTIONS_GHC -F -pgmF htfpp #-}
{-# LANGUAGE OverloadedStrings #-}
module ParserTest where
import Test.Framework
import Text.RawString.QQ
import qualified Data.Text as T
import Compiler
import Language
prop_simpleMain :: Bool
prop_simpleMain = parse "SimpleMain" "main = 1" == Right [ScDefn "main" [] (ENum 1)]
strSimpleLet :: String
strSimpleLet = [r|
main =
let
x = 1
in
x
|]
exprSimpleLet :: Program
exprSimpleLet =
[
ScDefn "main" []
(
ELet [("x", (ENum 1))] (EVar "x")
)
]
prop_simpleLet :: Bool
prop_simpleLet = parse "SimpleLet" (T.pack strSimpleLet) == Right exprSimpleLet
strMultiLet :: String
strMultiLet = [r|
main =
let
x = 1
y = 2
in
x
|]
exprMultiLet :: Program
exprMultiLet =
[
ScDefn "main" []
(
ELet [("x", (ENum 1)), ("y", (ENum 2))] (EVar "x")
)
]
prop_multiLet :: Bool
prop_multiLet = parse "MultiLet" (T.pack strMultiLet) == Right exprMultiLet
---------------------------------------------------------------------------------------------------
|
thomkoehler/FunLang
|
test/ParserTest.hs
|
bsd-3-clause
| 1,225
| 0
| 12
| 272
| 279
| 160
| 119
| 31
| 1
|
module FileSystems where
import System.IO
import Control.Monad.IO.Class
import Control.Monad
import qualified Data.ByteString as B
import qualified Data.Map as M
import Data.Word
import qualified Data.ByteString.Internal as BS (c2w, w2c)
import Data.Bits
import Numeric
data VHandle = HHandle Handle | BHandle Int B.ByteString
-- load. execute.
data BBCFile = BBCFile Word32 Word32 B.ByteString
|
dpiponi/Bine
|
src/FileSystems.hs
|
bsd-3-clause
| 398
| 0
| 7
| 54
| 101
| 65
| 36
| 12
| 0
|
module Main
( main,
)
where
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
import qualified Instrument.Tests.CloudWatch
import Test.Tasty
-------------------------------------------------------------------------------
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests =
testGroup
"instrument-cloudwatch"
[ Instrument.Tests.CloudWatch.tests
]
|
Soostone/instrument
|
instrument-cloudwatch/test/Main.hs
|
bsd-3-clause
| 491
| 0
| 7
| 55
| 65
| 40
| 25
| 11
| 1
|
-- extensions {{{
{-# LANGUAGE
DeriveFunctor, FlexibleContexts, FlexibleInstances, FunctionalDependencies,
GeneralizedNewtypeDeriving, MultiParamTypeClasses, OverloadedStrings,
RankNTypes, UndecidableInstances
#-}
-- }}}
-- exports {{{
module Database.AODB.Storage
-- types.
( ChunkID(..)
-- monad.
, Storage()
, MonadStorage(..)
, StorageWhere(..)
, runStorage
-- operations.
, lastChunk
, storeChunk
, recallChunk
) where
-- }}}
-- imports {{{
import Control.Applicative
import Control.Concurrent.MVar
import Control.Exception
import Control.Monad
import Control.Monad.Reader
import Data.Digest.CRC32 (crc32)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Word (Word8, Word32)
import Foreign.Marshal
import Foreign.Ptr
import Foreign.Storable
import GHC.IO.Device hiding (close)
import System.Posix
-- }}}
-- handles {{{
-- the format {{{
{-
A file is a sequence of chunks, with no padding or alignment.
Each chunk has the following layout:
+0:u32le self offset
+4:u32le content size
+8:u32le crc32 of content
+12:u8[size] content
-4:u32le self offset
There are 16 bytes of overhead per chunk.
-}
-- }}}
-- types {{{
data Handle db = Handle
{ handlePath :: FilePath
, handleState :: !(MVar (HandleState db))
}
data HandleState db = HS
{ hsFd :: Fd
, hsLast :: ChunkID db
}
newtype ChunkID db = ChunkID { unChunkID :: Word32 }
deriving (Eq, Ord, Enum)
-- }}}
-- creating {{{
dbCreate :: FilePath -> FileMode -> IO (Handle db)
dbCreate fn fm = do
-- open the file.
let flags = defaultFileFlags { append = True, exclusive = True }
fd <- openFd fn ReadWrite (Just fm) flags
-- initialize the handle state.
mhs <- newMVar $ HS
{ hsFd = fd
, hsLast = ChunkID 0
}
let h = Handle
{ handlePath = fn
, handleState = mhs
}
dbAppend h "aodb"
return h
-- }}}
-- opening {{{
dbOpen :: FilePath -> IO (Handle db)
dbOpen fn = do
-- open the file.
let flags = defaultFileFlags { append = True }
fd <- openFd fn ReadWrite Nothing flags
-- determine the last chunk.
blah <- fdSeek fd SeekFromEnd (-4)
last <- alloca $ \buf -> do
let _ = buf :: Ptr Word32
fdReadBuf fd (castPtr buf) 4
peekElemOff buf 0
-- initialize the handle state.
mhs <- newMVar $ HS
{ hsFd = fd
, hsLast = ChunkID last
}
return $ Handle
{ handlePath = fn
, handleState = mhs
}
-- }}}
-- closing {{{
dbClose :: Handle db -> IO ()
dbClose h = do
hs <- takeMVar $ handleState h
closeFd $ hsFd hs
putMVar (handleState h) hs
-- }}}
-- appending {{{
dbAppend :: Handle db -> ByteString -> IO (ChunkID db)
dbAppend h bs = do
hs <- takeMVar $ handleState h
-- prefix part.
offs <- fromIntegral `fmap` fdSeek (hsFd hs) SeekFromEnd 0
allocaBytes 12 $ \buf -> do
let _ = buf :: Ptr Word32
pokeElemOff buf 0 offs
pokeElemOff buf 1 . fromIntegral $ B.length bs
pokeElemOff buf 2 $ crc32 bs
fdWriteBuf (hsFd hs) (castPtr buf) 12
-- the content.
B.useAsCStringLen bs $ \(buf, len) -> do
fdWriteBuf (hsFd hs) (castPtr buf) $ fromIntegral len
-- suffix part.
alloca $ \buf -> do
let _ = buf :: Ptr Word32
pokeElemOff buf 0 offs
fdWriteBuf (hsFd hs) (castPtr buf) 4
putMVar (handleState h) hs
return . ChunkID $ fromIntegral offs
-- }}}
-- reading {{{
dbRead :: Handle db -> ChunkID db -> IO ByteString
dbRead h (ChunkID offs) = do
hs <- takeMVar $ handleState h
fdSeek (hsFd hs) AbsoluteSeek $ fromIntegral offs
(len, checksum) <- allocaBytes 12 $ \buf -> do
let _ = buf :: Ptr Word32
fdReadBuf (hsFd hs) (castPtr buf) 12
offs' <- peekElemOff buf 0
len <- fromIntegral `fmap` peekElemOff buf 1
checksum <- peekElemOff buf 2
assert (offs == offs') $ return (len, checksum)
bs <- allocaBytes len $ \buf -> do
let _ = buf :: Ptr Word8
fdReadBuf (hsFd hs) (castPtr buf) $ fromIntegral len
B.packCStringLen (castPtr buf, len)
putMVar (handleState h) hs
assert (checksum == crc32 bs) $ return bs
-- }}}
-- }}}
-- the storage monad {{{
newtype Storage db a = Storage { unStorage :: ReaderT (Handle db) IO a }
deriving (Functor, Applicative, Monad, MonadIO)
class (Monad m, MonadIO m) => MonadStorage db m | m -> db where
askHandle :: m (Handle db)
instance MonadStorage db (Storage db) where
askHandle = Storage ask
instance (MonadStorage db m, Monad (t m), MonadIO (t m), MonadTrans t) => MonadStorage db (t m) where
askHandle = lift $ askHandle
-- running {{{
data StorageWhere
= Existing FilePath
| NewFile FilePath
runStorage :: StorageWhere -> (forall db. Storage db a) -> IO a
runStorage wh action = do
h <- case wh of
Existing fn -> dbOpen fn
NewFile fn -> dbCreate fn $ ownerReadMode `unionFileModes` ownerWriteMode
runReaderT (unStorage action) h `finally` dbClose h
-- }}}
-- operations {{{
lastChunk :: (MonadStorage db m) => m (ChunkID db)
lastChunk = do
mv <- handleState `liftM` askHandle
hs <- liftIO $ takeMVar mv
liftIO $ putMVar mv hs
return $ hsLast hs
storeChunk :: (MonadStorage db m) => ByteString -> m (ChunkID db)
storeChunk bs = do
h <- askHandle
liftIO $ dbAppend h bs
recallChunk :: (MonadStorage db m) => ChunkID db -> m ByteString
recallChunk ch = do
h <- askHandle
liftIO $ dbRead h ch
-- }}}
-- }}}
-- vim:fdm=marker:
|
fperleta/aodb
|
src/Database/AODB/Storage.hs
|
bsd-3-clause
| 5,886
| 0
| 15
| 1,742
| 1,792
| 918
| 874
| 138
| 2
|
module Vandelay.App.Cmd.Init
( initTemplate
, SortOptions(..)
, SourceFileReferences(..)
) where
import Control.Monad.Trans.RWS (RWST, runRWST, tell)
import System.FilePath
import Vandelay.DSL.Core
import qualified Data.Map as M
-- Initialize template
initTemplate ∷ [FilePath] -- ^ Estimation results filepaths
→ Maybe FilePath -- ^ Optional output file (stdout if nothing)
→ SortOptions
→ SourceFileReferences -- ^ Use abbreviated model names
→ EIO ErrorMsg () -- ^ Error message or ()
initTemplate estPaths textOutFile sos sfr = do
globs <- globPaths estPaths
estFile <- mapM safeReadFile globs
(_,_,text) <- runRWST (writeConf >> writeTable >> writeSub ) (InitSetup estPaths estFile sos sfr) ()
unsafeWriteFile textOutFile text
-- -- | Internal data types
type InitMonad = RWST InitSetup Text () (EIO ErrorMsg)
data InitSetup = InitSetup
{ dataFilePaths ∷ [FilePath]
, dataFileContents ∷ [FileContent]
, sortOptions ∷ SortOptions
, sourceFileReferences ∷ SourceFileReferences
}
type FileContent = Text
type FileRefs = Text
data SortOptions = SortOptions
{ -- | Output models in order of appearance in estimates file if false
sortModels ∷ Bool
-- | Output variables in order of appearance in estimates file if false
, sortVars ∷ Bool
}
deriving (Show)
data SourceFileReferences =
NoSFR
| FullPath
| Abbreviation
deriving (Show, Read, Eq)
-- | Write the template's configuration section
writeConf ∷ InitMonad ()
writeConf = do
dfp <- askPath
baseFile <- maybe (throwError "No file paths specified")
(return . takeFileName . head)
(fromNullable dfp)
let texFile = replaceExtension baseFile ".tex"
tellLn "configuration:"
writeDataFiles
tellLn " models: # List models separated by columns as (FILENAME:)MODELNAME where FILENAME is optional"
tellLn $ " tex: " ++ pack texFile
tellLn ""
tellLn " # Models are:"
writeModels
tellLn ""
-- | Write the template's table section
writeTable ∷ InitMonad ()
writeTable = do
tellLn "table:"
tellLn " template: header.tex # Subject to substitutions"
tellLn " name: Print Name; code: coded_name; index: 0; surround: (,); format: %03.2f; scale: 1.0; empty: -; zeroReformat: BOOL"
tellLn " latex: \\addlinespace # Source latex code - add end lines if required"
tellLn ""
tellLn " # Note that specifying missing in the data row (beginning with name) will allow for a file to omit a variable. This differs from blank values in a file with a variable."
tellLn ""
tellLn " # Variables are:"
writeVars
tellLn ""
-- | Write the template's substitution section
writeSub ∷ InitMonad ()
writeSub = do
tellLn "substitutions:"
tellLn " CAPTION: Insert caption text which may"
tellLn " extends onto another line."
-- | Write the datafiles
writeDataFiles ∷ InitMonad ()
writeDataFiles = do
paths <- map pack <$> askPath
refs <- askFileReferences
sfr <- asks sourceFileReferences
if sfr /= Abbreviation
then tellLn . indent . dataStatement . intercalate ", " . map pack =<< askPath
else let out = map (indent . dataStatement *** refStatement) $ zip paths refs
in mapM_ tellLnWithDataSource =<< lengthenItemRefTuple out
-- | Write the models and variables
writeModels ∷ InitMonad ()
writeVars ∷ InitMonad ()
writeModels = writeItem askSortModels modelReferenceTuple
writeVars = writeItem askSortVars varReferenceTuple
writeItem ∷ InitMonad Bool -- | Sorting asker
→ (Text → Text → [(Text, [Text])]) -- | Item-reference tupling function
→ InitMonad ()
writeItem askSort tupler = do
conrefs <- askContentsRefs -- [(Content, Source File Reference)]
sortQ <- askSort
let sorter ∷ Ord a ⇒ [a] → [a]
sorter = if sortQ then id else sort
its = concatMap (uncurry tupler) conrefs -- [(Item, Source File Reference)]
is = sorter . M.toList . M.fromListWith (++) $ reverse its -- [(Item, [Source File Reference])] -- Group by item
out = map (indentAndComment *** dataSourceStatement) is -- Format each part of tuple using arrows
mapM_ tellLnWithDataSource =<< lengthenItemRefTuple out
-- | Model and variable from content
modelsFromContent ∷ Text -- | Content
→ [Text] -- | Model
modelsFromContent t =
maybe [] (stripFilter . splitOn tab . head) (fromNullable . lines $ t)
varsFromContent ∷ Text -- | Content
→ [Text] -- | [(Variable, Ref)]
varsFromContent =
stripFilter . mapMaybe (fmap head . fromNullable . splitOn tab) . lines
itemReferenceTuple ∷ (Text → [Text]) -- | Item Extraction function
→ Text -- | Content
→ Text -- | Refs
→ [(Text, [Text])] -- | [(Item, [Ref])]
itemReferenceTuple f c r = zip (f c) $ repeat [r]
varReferenceTuple = itemReferenceTuple varsFromContent
modelReferenceTuple = itemReferenceTuple modelsFromContent
-- | Reader ask utility functions
askPath ∷ InitMonad [FilePath]
askTPath ∷ InitMonad [FilePath]
askContents ∷ InitMonad [FileContent]
askContentsRefs ∷ InitMonad [(FileContent, FileRefs)]
askSortOptions ∷ InitMonad SortOptions
askSortModels ∷ InitMonad Bool
askSortVars ∷ InitMonad Bool
askSourceFileReferences ∷ InitMonad SourceFileReferences
askFileReferences ∷ InitMonad [FileRefs]
askPath = asks dataFilePaths
askTPath = map pack <$> askPath
askContents = asks dataFileContents
askContentsRefs = zip <$> askContents <*> askFileReferences
askSortOptions = asks sortOptions
askSortModels = sortModels <$> askSortOptions
askSortVars = sortVars <$> askSortOptions
askSourceFileReferences = asks sourceFileReferences
askFileReferences =
askSourceFileReferences >>= \case
Abbreviation → return abbreviations
_ → map pack <$> asks dataFilePaths
-- | WriterT utility functions
tellLn s = tell $ s ++ "\n"
tellLnWithDataSource (s,ds) =
askSourceFileReferences >>= \case
NoSFR → tellLn s
_ → tellLn (s ++ ds)
-- | Statement creation
dataStatement ∷ Text → Text
dataStatement = (++) "data: "
dataSourceStatement ∷ [Text] → Text
dataSourceStatement rs = unwords [" # In", unwordEnglishList rs]
refStatement ∷ Text → Text
refStatement s = unwords [" #", s]
-- | Text utility functions
stripFilter∷ [Text] → [Text] -- | Remove spaces, drop blanks
stripFilter = filter (not . null) . map strip
tab = "\t"
indent∷ Text → Text
indent = (++) " "
indentAndComment ∷ Text → Text
indentAndComment = indent . (++) "# "
abbreviations ∷ [Text]
abbreviations = map (\c → "(" <> singleton c <> ")") ['A'..'Z']
extendText ∷ Int → Text → Text
extendText i s | length s > i = s
| otherwise = s ++ replicate (i - length s) ' '
lengthenItemRefTuple ∷ [(Text, Text)]
→ InitMonad [(Text,Text)]
lengthenItemRefTuple ts =
asks sourceFileReferences >>= \case
NoSFR → return ts
_ → let maxlength ∷ Int
maxlength = maximum $ impureNonNull (0 : map getLength ts)
getLength ∷ (Text, Text) → Int
-- , unwordEnglishListString
getLength (t, _) = length t
in return $ map (first (extendText maxlength)) ts
|
tumarkin/vandelay
|
src/Vandelay/App/Cmd/Init.hs
|
bsd-3-clause
| 7,726
| 0
| 17
| 1,993
| 1,802
| 939
| 863
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
import qualified Data.Text as T
import Data.Text (Text)
import Data.ByteString (ByteString)
import Test.Hspec
import Test.HUnit (Assertion, assertBool, assertFailure,
(@=?), (@?=))
import Database.Disque
main :: IO ()
main = do
conn <- setupDisque
hspec (specs conn)
dq = runDisque
isRight (Right _) = True
isRight _ = False
specs c = do
describe "Database.Disque" $ do
it "Sanity Check" $ do
assertBool "Sanity Check" True
it "Adds Jobs" $ do
pendingWith "Implement disque-server manager."
-- res <- dq c $ do Right s <- addjob "test_queue" "" 0
-- getjob ["test_queue"]
-- assertBool "Sanity Check" $ isRight res
setupDisque = do
putStrLn "Starting Disque..."
conn <- connect $ disqueConnectInfo { connectHost = "192.168.1.104" }
return conn
|
creichert/disque.hs
|
test/Spec.hs
|
bsd-3-clause
| 922
| 0
| 13
| 262
| 218
| 114
| 104
| 25
| 1
|
module Mire.Reactive.Timer (
module Export,
makeTimer,
) where
import Mire.Prelude
import Reactive.Banana
import Reactive.Banana.Frameworks
import Control.Concurrent.Timer.Lifted
import Control.Concurrent.Suspend.Lifted as Export
timerAddHandler :: Delay -> MomentIO (AddHandler ())
timerAddHandler delay = liftIO $ do
(addHandler, fire) <- newAddHandler
timer <- repeatedTimer (fire ()) delay
return $ AddHandler $ \s -> do
t <- register addHandler s
return (t >> stopTimer timer)
makeTimer :: Delay -> MomentIO (Event ())
makeTimer delay = timerAddHandler delay >>= fromAddHandler
|
ellej/mire
|
src/Mire/Reactive/Timer.hs
|
bsd-3-clause
| 615
| 0
| 15
| 106
| 193
| 103
| 90
| 17
| 1
|
{-# LANGUAGE OverloadedStrings #-}
-- |
-- Module: MailchimpSimple
-- License: BSD3
-- Maintainer: Dananji Liyanage <dan9131@gmail.com>
-- Stability: experimental
--
-- Types and functions for working with Mailchimp JSON API Version 3.0
module MailchimpSimple
(
-- ** Working with Lists
-- $lists
listMailingLists
, listSubscribers
, listListActivity
, addSubscriber
, removeSubscriber
-- ** Retrieve Template related data
-- $templates
, getTemplates
-- ** Working with Campaigns
-- $campaigns
, getCampaigns
, createCampaign
, sendEmail
-- ** Batch Requests
-- $batches
, batchSubscribe
-- ** Search Members
-- $search
, searchMembersInList ) where
import Network.HTTP.Conduit
import Network.HTTP.Types ( methodPost, methodGet, methodDelete, Method(..), Status(..), http11, ResponseHeaders, hContentType )
import Control.Monad.IO.Class ( liftIO )
import Safe
import Control.Exception ( catch, IOException, Exception )
import Control.Lens.Getter ( (^.))
import System.Exit ( exitWith, ExitCode(..) )
import System.FilePath.Posix ( pathSeparator )
import qualified Data.ByteString.Lazy as BL
import Data.ByteString.Lazy ( ByteString )
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Base16 as B16
import qualified Data.Text as T
import Data.Aeson ( encode, decode, eitherDecode, Value, Array, ToJSON )
import Data.List ( transpose, intercalate )
import Data.Aeson.Lens ( key )
import Data.Time.Calendar
import Data.Maybe ( Maybe(..), fromJust )
import qualified Data.Vector as V
import Crypto.Hash.MD5 as MD5
-- App modules
import Utils.Types
import Utils.Logger
-- | Takes an @apiKey@ of a Mailchimp account, and gives all the mailing-lists in the account.
--
-- This function lists the mailing lists in a particular account
listMailingLists
:: String
-> IO [MailListResponse]
listMailingLists apiKey = do
let url = endPointUrl apiKey
let lUrl = url ++ "/lists?fields=lists.id,lists.name"
response <- processEmptyRequest lUrl apiKey methodGet
let resBody = decode (responseBody response) :: Maybe Value
let vArray = resBody ^. key "lists" :: Maybe Array
let listResponse = getValues vArray
return listResponse
where getValues ls
| ls /= (Just V.empty) = constructMLRes (fmap V.head ls) : getValues (fmap V.tail ls)
| otherwise = []
constructMLRes elem = do let lName = elem ^. key "name" :: Maybe String
let lID = elem ^. key "id" :: Maybe String
MailListResponse lName lID
-- | Takes an @apiKey@ of the Mailchimp account, and a @listName@.
-- Retrieves all the members in the given list.
--
-- Request URL specifies which data to be returned from the response. They are,
-- @email_address, unique_email_id, email_type, list_id@, and @status@ for each
-- member in the reponse.
--
-- This function lists subscribers in a mailing list
listSubscribers
:: String
-> String
-> IO [ListSubscribersResponse]
listSubscribers apiKey listName = do
let url = endPointUrl apiKey
listid <- getListID apiKey listName
let lUrl = url ++ "/lists/" ++ listid ++ "/members?fields=members.email_address,members.unique_email_id,members.email_type,members.list_id,members.status"
response <- processEmptyRequest lUrl apiKey methodGet
let resBody = decode (responseBody response) :: Maybe Value
let vArray = resBody ^. key "members" :: Maybe Array
let listSubResponse = getValues vArray
return listSubResponse
where getValues ls
| ls /= (Just V.empty) = constructLSRes (fmap V.head ls) : getValues (fmap V.tail ls)
| otherwise = []
constructLSRes elem = ListSubscribersResponse sName sEuid (Just listName) sEmailType sStatus
where sName = elem ^. key "email_address" :: Maybe String
sEuid = elem ^. key "unique_email_id" :: Maybe String
sEmailType = elem ^. key "email_type" :: Maybe String
sStatus = elem ^. key "status" :: Maybe String
-- | Takes an @apiKey@ of the Mailchimp account, and a @listName@.
-- Retrieves the activity summary in the given list.
--
-- Request URL specifies which data to be returned from the response. They are,
-- @day, emails_sent, unique_opens, recipient_clicks@, and @subs@ for the given list.
--
-- This function gives the summary of activities in a mailing list
listListActivity
:: String
-> String
-> IO [ListActivityResponse]
listListActivity apiKey listName = do
let url = endPointUrl apiKey
listid <- getListID apiKey listName
let aUrl = url ++ "/lists/" ++ listid ++ "/activity?fields=activity.day,activity.emails_sent,activity.unique_opens,activity.recipient_clicks,activity.subs"
response <- processEmptyRequest aUrl apiKey methodGet
let resBody = decode (responseBody response) :: Maybe Value
let vArray = resBody ^. key "activity" :: Maybe Array
let listActivityResponse = getValues vArray
return listActivityResponse
where getValues ls
| ls /= (Just V.empty) = constructALRes (fmap V.head ls) : getValues (fmap V.tail ls)
| otherwise = []
constructALRes elem = ListActivityResponse date mailSent uniqueOpen clicks subs
where date = elem ^. key "day" :: Maybe Day
mailSent = elem ^. key "emails_sent" :: Maybe Int
uniqueOpen = elem ^. key "unique_opens" :: Maybe Int
clicks = elem ^. key "recipient_clicks" :: Maybe Int
subs = elem ^. key "subs" :: Maybe Int
-- | Taking @apiKey,@ @listName,@ @emailAddress,@ @emailType,@ and @memberStatus@ as input
-- parameters in the given order, this function creates and add the member to the given list.
--
-- This function adds a new member to a given list
addSubscriber
:: String
-> String
-> String
-> String
-> String
-> IO SubscriptionResponse
addSubscriber apiKey listName email emailType status = do
let url = endPointUrl apiKey
let subscription = Subscription { s_email = email
, s_email_type = emailType
, s_status = status }
listid <- getListID apiKey listName
let sUrl = url ++ "/lists/" ++ listid ++ "/members"
response <- processRequest sUrl apiKey subscription methodPost
let resBody = decode (responseBody response) :: Maybe Value
let subscribers = constructSARes resBody
return subscribers
where constructSARes elem = do let email = elem ^. key "email_address" :: Maybe String
let euid = elem ^. key "unique_email_id" :: Maybe String
let status = elem ^. key "status" :: Maybe String
SubscriptionResponse email euid status (Just listName)
filterListID list = filter ((==(Just listName)) . l_name) list
-- | Giving an @apiKey,@ @emailAddress,@ and @listName@ which the member belongs to, this
-- function unsubscribe the member from the list. This function does not deletes the particular
-- user profile from the mailing-list.
--
-- This function removes a member from a given list
removeSubscriber
:: String
-> String
-> String
-> IO Bool
removeSubscriber apiKey email listName = do
let url = endPointUrl apiKey
listid <- getListID apiKey listName
let subhash = createHash email
let rUrl = url ++ "/lists/" ++ listid ++ "/members/" ++ subhash
response <- processEmptyRequest rUrl apiKey methodDelete
let status = statusCode $ responseStatus response
case status of
204 -> return True
_ -> return False
where createHash str = (B8.unpack (calculateHash (strToBS str)))
calculateHash str = (B16.encode (hash str))
strToBS str = B8.pack str
-- | Input parameters for this function is the @apiKey@ of the Mailchimp account.
--
-- This function retrieves all the templates in the account.
getTemplates
:: String
-> IO [TemplateResponse]
getTemplates apiKey = do
let url = endPointUrl apiKey
let tUrl = url ++ "/templates?fields=templates.id,templates.name"
response <- processEmptyRequest tUrl apiKey methodGet
let resBody = decode (responseBody response) :: Maybe Value
let galleryT = resBody ^. key "templates" :: Maybe Array
let templateList = getValues galleryT
return templateList
where getValues ls
| ls /= (Just V.empty) = constructTRes (fmap V.head ls) : getValues (fmap V.tail ls)
| otherwise = []
constructTRes elem = do let tName = elem ^. key "name" :: Maybe String
let tID = elem ^. key "id" :: Maybe Int
TemplateResponse tName tID
-- | Taking the @apiKey@ of a Mailchimp account, this function returns all the
-- stored unsent Campaigns.
--
-- This function returns all the Campaigns in the account.
getCampaigns :: String -> IO [(Maybe String, Maybe String)]
getCampaigns apiKey = do
let url = endPointUrl apiKey
let cUrl = url ++ "/campaigns?fields=campaigns.id,campaigns.settings"
response <- processEmptyRequest cUrl apiKey methodGet
let resBody = decode (responseBody response) :: Maybe Value
let rawcids = resBody ^. key "campaigns" :: Maybe Array
let cids = getValues rawcids
return cids
where getValues ls
| ls /= (Just V.empty) = constructCRes (fmap V.head ls) : getValues (fmap V.tail ls)
| otherwise = []
constructCRes elem = do let cid = elem ^. key "id" :: Maybe String
let settings = elem ^. key "settings" :: Maybe Value
let name = settings ^. key "subject_line" :: Maybe String
(cid, name)
-- | Usage of this function to create a new Campaign and save is as follows;
--
-- @createCampaign@ @apiKey listName replyTo fromName cType title subject -> campaignID@
--
-- This function creates a new campaign and save it
createCampaign
:: String
-> String
-> String
-> String
-> String
-> String
-> String
-> IO (Maybe String)
createCampaign apiKey
listName
replyTo
fromName
cType
title
subject = do
let url = endPointUrl apiKey
listid <- getListID apiKey listName
let campaign = Campaign { c_type = cType
, c_settings = Settings { s_subject = subject
, s_title = title
, s_from_name = fromName
, s_reply_to = replyTo }
, c_receipients = (ListID listid) }
let eUrl = url ++ "/campaigns"
response <- processRequest eUrl apiKey campaign methodPost
let resBody = decode (responseBody response) :: Maybe Value
let campaignid = resBody ^. key "id" :: Maybe String
return campaignid
-- | Input parameters for this function are @apiKey@ and the @campaignID@ of the
-- particular Campaign to be sent.
--
-- This function sends an email campaign
sendEmail
:: String
-> String
-> IO (Either String SendMailResponse)
sendEmail apiKey cid = do
let url = endPointUrl apiKey
let sUrl = url ++ "/campaigns/" ++ cid ++ "/actions/send"
response <- processEmptyRequest sUrl apiKey methodPost
let sendRes = eitherDecode (responseBody response) :: Either String SendMailResponse
return sendRes
-- | Efficiently processes a batch subscription requests for a given list
-- of @emailAddress@ and @subscriptionStatus@ combinations.
--
-- This function can be re-implemented to perform other batch requests by changing the
-- @body@ and @path@ properties of @Operation@ data structure.
--
-- This function adds a batch of subscribers
batchSubscribe
:: String
-> String
-> [(String, String)]
-> IO BatchSubscriptionResponse
batchSubscribe apiKey listName subs = do
let url = endPointUrl apiKey
listid <- getListID apiKey listName
let batchSubs = map constructSubs subs
let batchOps = map (constructBSRes listid) batchSubs
let batchSubscription = Batch { operations = batchOps }
let bUrl = url ++ "/batches"
response <- processRequest bUrl apiKey batchSubscription methodPost
let resBody = decode (responseBody response) :: Maybe Value
let batchResponse = BatchSubscriptionResponse (resBody ^. key "id" :: Maybe String) (resBody ^. key "status" :: Maybe String)
return batchResponse
where constructSubs (email, status) = Subscription { s_email = email
, s_email_type = "html"
, s_status = status }
constructBSRes listid sub = Operation { o_method = "POST"
, o_path = "/lists/" ++ listid ++ "/members"
, o_params = Params { params = [] }
, o_body = B8.unpack $ BL.toStrict $ encode sub }
-- | Search a specific list for members that match specified query terms.
--
-- Invoking this function with an empty @listName@ , we can get all
-- the memebers that match the specified query terms in the account.
searchMembersInList
:: String
-> String
-> String
-> IO SearchResultResponse
searchMembersInList apiKey listName query = do
let url = endPointUrl apiKey
listid <- getListID apiKey listName
let sUrl = if null listid
then url ++ "/search-members?query=" ++ query
else url ++ "/search-members?query=" ++ query ++ "&list_id=" ++ listid
response <- processEmptyRequest sUrl apiKey methodGet
if (statusCode $ responseStatus response) < 400
then do let resBody = decode (responseBody response) :: Maybe Value
let fullsearch = resBody ^. key "full_search" :: Maybe Value
let totalcount = fullsearch ^. key "total_items" :: Maybe Int
let members = fullsearch ^. key "members" :: Maybe Array
let parsedmembers = getValues members
let searchresults = SearchResultResponse (Just parsedmembers) totalcount
return searchresults
else error $ "Error in response: " ++ show response
where getValues ls
| ls /= (Just V.empty) = constructMembers (fmap V.head ls) : getValues (fmap V.tail ls)
| otherwise = []
constructMembers elem = ListSubscribersResponse sName sEuid sListID sEmailType sStatus
where sName = elem ^. key "email_address" :: Maybe String
sEuid = elem ^. key "unique_email_id" :: Maybe String
sListID = elem ^. key "list_id" :: Maybe String
sEmailType = elem ^. key "email_type" :: Maybe String
sStatus = elem ^. key "status" :: Maybe String
-------------------------------------------------------------------------------------------------------------------------------------
-- | Get the list_id when the listname is given
getListID :: String -> String -> IO String
getListID apiKey listName
| null listName = return ""
| otherwise = do mailinglists <- listMailingLists apiKey
let rawlistid = headMay $ filterListID mailinglists
case rawlistid of
Just mlist -> return $ fromJust $ l_id mlist
Nothing -> do putStrLn $ "Error: Invalid list name, " ++ listName
return ""
where filterListID list = filter ((==(Just listName)) . l_name) list
-- | Build the response from URL and JSON data
processRequest :: ToJSON a => String -> String -> a -> Method -> IO (Response ByteString)
processRequest url apiKey json httpmethod = do
let initReq = applyBasicAuth (B8.pack "anystring") (B8.pack apiKey) $ fromJust $ parseUrlThrow url
let req = initReq { requestBody = RequestBodyLBS $ encode json
, method = httpmethod }
catch (newManager tlsManagerSettings >>= (httpLbs req))
(\exception -> do writeLog ERROR "processRequest" url (show exception)
handleException exception)
-- | Build the response from URL and JSON data
processEmptyRequest :: String -> String -> Method -> IO (Response ByteString)
processEmptyRequest url apiKey httpmethod = do
let initReq = applyBasicAuth (B8.pack "anystring") (B8.pack apiKey) $ fromJust $ parseUrlThrow url
let req = initReq { method = httpmethod }
catch (newManager tlsManagerSettings >>= (httpLbs req))
(\exception -> do writeLog ERROR "processEmptyRequest" url (show exception)
handleException exception)
-- | Exception handling in making the HTTP requests
handleException :: HttpException -> IO (Response ByteString)
handleException (HttpExceptionRequest req exception) = do
case exception of
StatusCodeException res _ -> do let errorres = res { responseVersion = http11
, responseBody = "" }
return errorres
ConnectionTimeout -> error "Connection timed out."
ResponseTimeout -> error "Response timed out."
_ -> error "Unidentified HTTP exception."
-- | Construct the end-point URL
endPointUrl :: String -> String
endPointUrl apiKey
| null splitted= error "Empty apiKey input into the function"
| otherwise = "https://" ++ (last splitted) ++ ".api.mailchimp.com/3.0"
where splitted = splitString '-' apiKey
-- | Utility function to split strings
splitString :: Char -> String -> [String]
splitString d [] = []
splitString d s = x : splitString d (drop 1 y) where (x,y) = span (/= d) s
|
Dananji/MailchimpSimple
|
src/MailchimpSimple.hs
|
bsd-3-clause
| 18,460
| 0
| 16
| 5,379
| 4,208
| 2,097
| 2,111
| 304
| 4
|
module Lambda.DataType.Error.Compile where
import DeepControl.Monad.Except
import Lambda.DataType.Common
--------------------------------------------------
-- Data
--------------------------------------------------
data CompileError = DESUGAR String
| RESTORE String
| TYPEOF String
| OTHER String
instance Error CompileError where
strMsg s = OTHER s
instance Show CompileError where
show (DESUGAR mes) = "Desugar error: "++ mes
show (RESTORE mes) = "Restore error: "++ mes
show (TYPEOF mes) = "Typeof error: "++ mes
show (OTHER mes) = mes
|
ocean0yohsuke/Simply-Typed-Lambda
|
src/Lambda/DataType/Error/Compile.hs
|
bsd-3-clause
| 626
| 0
| 8
| 153
| 142
| 78
| 64
| 14
| 0
|
x = 4
y = 5
|
roberth/uu-helium
|
test/parser/LayoutOk9.hs
|
gpl-3.0
| 12
| 0
| 4
| 6
| 11
| 6
| 5
| 2
| 1
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="sr-CS">
<title>TLS Debug | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
veggiespam/zap-extensions
|
addOns/tlsdebug/src/main/javahelp/org/zaproxy/zap/extension/tlsdebug/resources/help_sr_CS/helpset_sr_CS.hs
|
apache-2.0
| 971
| 80
| 66
| 160
| 415
| 210
| 205
| -1
| -1
|
{-# LANGUAGE NoMonomorphismRestriction, ScopedTypeVariables, BangPatterns #-}
module Main where
import MandelObs as O
import MandelAcc as A
import Criterion.Main
import Criterion.Types
import System.Environment
import Prelude as P
import qualified Prelude as P hiding (zipWith,sum,take,drop,iterate)
import Obsidian.Run.CUDA.Exec(captureIO,initialise,props)
import Obsidian(fromDyn,toDyn,splitUp,Pull,DPush,EWord32,Grid)
import Data.Array.Accelerate as A hiding ((++))
import Data.Array.Accelerate.CUDA as A
import qualified Foreign.CUDA.Driver as CUDA
import Data.Word
benchmarks ctx kern threads runMandelAcc view size =
defaultMainWith benchConfig
[ bgroup ("Mandel ")
[
bench "Accelerate" $ whnf runMandelAcc view,
bench "Obsidian" $ whnfIO (runMandelObs ctx kern threads size)
]
]
-- This configuration enables garbage collection between benchmarks. It is a
-- good idea to do so. Otherwise GC might distort your results
benchConfig :: Config
benchConfig = defaultConfig { forceGC = True}
main = do
user configuration
args <- getArgs
let wht = read (args P.!! 0 ) :: Int
let depth = 512
Obsidian configuration
ctx <- initialise
!kern <- captureIO "kernel" (props ctx) (P.fromIntegral wht) (mandel (P.fromIntegral wht) (P.fromIntegral wht))
Accelerate configuration
let
view :: (Float,Float,Float,Float)
view = (-2.23, -1.15, 0.83, 1.15)
view' = A.fromList A.Z [view]
runCUDA = A.run1 (mandelbrot wht wht wht)
withArgs (P.tail args) $ benchmarks ctx kern wht runCUDA view' (wht*wht)
|
aesadde/AccObsBenchmarks
|
Mandel/src/Main.hs
|
bsd-3-clause
| 1,702
| 0
| 13
| 410
| 478
| 268
| 210
| 38
| 1
|
module Graphics.Gnuplot.Terminal.PNG (
T, cons,
transparent, noTransparent,
interlace, noInterlace,
trueColor, noTrueColor,
fontTiny, fontSmall, fontMedium, fontLarge, fontGiant,
) where
import qualified Graphics.Gnuplot.Private.Terminal as Terminal
import Data.Maybe (catMaybes, )
import Graphics.Gnuplot.Utility (quote, formatBool, )
data T =
Cons {
filename_ :: FilePath,
transparent_ :: Maybe Bool,
interlace_ :: Maybe Bool,
trueColor_ :: Maybe Bool,
fontSize_ :: Maybe FontSize
}
cons :: FilePath -> T
cons path =
Cons {
filename_ = path,
transparent_ = Nothing,
interlace_ = Nothing,
trueColor_ = Nothing,
fontSize_ = Nothing
}
transparent, noTransparent :: T -> T
transparent term = term{transparent_ = Just True}
noTransparent term = term{transparent_ = Just False}
interlace, noInterlace :: T -> T
interlace term = term{interlace_ = Just True}
noInterlace term = term{interlace_ = Just False}
trueColor, noTrueColor :: T -> T
trueColor term = term{trueColor_ = Just True}
noTrueColor term = term{trueColor_ = Just False}
fontTiny, fontSmall, fontMedium, fontLarge, fontGiant :: T -> T
fontTiny = setFontSize FontTiny
fontSmall = setFontSize FontSmall
fontMedium = setFontSize FontMedium
fontLarge = setFontSize FontLarge
fontGiant = setFontSize FontGiant
-- private functions
data FontSize =
FontTiny | FontSmall | FontMedium | FontLarge | FontGiant
formatFontSize :: FontSize -> String
formatFontSize size =
case size of
FontTiny -> "tiny"
FontSmall -> "small"
FontMedium -> "medium"
FontLarge -> "large"
FontGiant -> "giant"
setFontSize :: FontSize -> T -> T
setFontSize size term =
term{fontSize_ = Just size}
instance Terminal.C T where
canonical term =
Terminal.Cons {
Terminal.options =
"png" :
catMaybes (
(fmap (formatBool "transparent") $ transparent_ term) :
(fmap (formatBool "interlace") $ interlace_ term) :
(fmap (formatBool "truecolor") $ trueColor_ term) :
(fmap formatFontSize $ fontSize_ term) :
[]),
Terminal.commands =
["set output " ++ (quote $ filename_ term)],
Terminal.interactive = False
}
|
wavewave/gnuplot
|
src/Graphics/Gnuplot/Terminal/PNG.hs
|
bsd-3-clause
| 2,342
| 0
| 19
| 603
| 656
| 371
| 285
| 66
| 5
|
module Bead.Domain.Entity.Notification where
import Data.Text
-- The notifications can come from different sources
data NotifType
= Comment
| Feedback
| System
deriving (Eq, Show)
notifType
comment
feedback
system
n = case n of
Comment -> comment
Feedback -> feedback
System -> system
-- The notification is rendered for the user on some informational
-- page or send via email.
data Notification = Notification {
notifMessage :: Text
} deriving (Eq, Show)
notification f (Notification msg) = f msg
|
pgj/bead
|
src/Bead/Domain/Entity/Notification.hs
|
bsd-3-clause
| 542
| 0
| 8
| 121
| 121
| 68
| 53
| 19
| 3
|
-- -*- mode: haskell -*-
module Control.XmlTime where
data XmlTime = XmlTime String
|
Erdwolf/autotool-bonn
|
src/Control/XmlTime.hs
|
gpl-2.0
| 86
| 0
| 6
| 15
| 16
| 10
| 6
| 2
| 0
|
{-# LANGUAGE TupleSections, TemplateHaskell, CPP, UndecidableInstances,
MultiParamTypeClasses, TypeFamilies, GeneralizedNewtypeDeriving #-}
{-| Functions of the metadata daemon exported for RPC
-}
{-
Copyright (C) 2014 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Metad.ConfigCore where
import Control.Applicative
import Control.Concurrent.MVar.Lifted
import Control.Monad.Base
import Control.Monad.IO.Class
import Control.Monad.Reader
import Control.Monad.Trans.Control
import Language.Haskell.TH (Name)
import qualified Text.JSON as J
import Ganeti.BasicTypes
import Ganeti.Errors
import qualified Ganeti.JSON as J
import Ganeti.Logging as L
import Ganeti.Metad.Config as Config
import Ganeti.Metad.Types (InstanceParams)
-- * The monad in which all the Metad functions execute
data MetadHandle = MetadHandle
{ mhInstParams :: MVar InstanceParams
}
-- | A type alias for easier referring to the actual content of the monad
-- when implementing its instances.
type MetadMonadIntType = ReaderT MetadHandle IO
-- | The internal part of the monad without error handling.
newtype MetadMonadInt a = MetadMonadInt
{ getMetadMonadInt :: MetadMonadIntType a }
deriving ( Functor, Applicative, Monad, MonadIO, MonadBase IO
, L.MonadLog )
instance MonadBaseControl IO MetadMonadInt where
#if MIN_VERSION_monad_control(1,0,0)
-- Needs Undecidable instances
type StM MetadMonadInt b = StM MetadMonadIntType b
liftBaseWith f = MetadMonadInt . liftBaseWith
$ \r -> f (r . getMetadMonadInt)
restoreM = MetadMonadInt . restoreM
#else
newtype StM MetadMonadInt b = StMMetadMonadInt
{ runStMMetadMonadInt :: StM MetadMonadIntType b }
liftBaseWith f = MetadMonadInt . liftBaseWith
$ \r -> f (liftM StMMetadMonadInt . r . getMetadMonadInt)
restoreM = MetadMonadInt . restoreM . runStMMetadMonadInt
#endif
-- | Runs the internal part of the MetadMonad monad on a given daemon
-- handle.
runMetadMonadInt :: MetadMonadInt a -> MetadHandle -> IO a
runMetadMonadInt (MetadMonadInt k) = runReaderT k
-- | The complete monad with error handling.
type MetadMonad = ResultT GanetiException MetadMonadInt
-- * Basic functions in the monad
metadHandle :: MetadMonad MetadHandle
metadHandle = lift . MetadMonadInt $ ask
instParams :: MetadMonad InstanceParams
instParams = readMVar . mhInstParams =<< metadHandle
modifyInstParams :: (InstanceParams -> MetadMonad (InstanceParams, a))
-> MetadMonad a
modifyInstParams f = do
h <- metadHandle
modifyMVar (mhInstParams h) f
-- * Functions available to the RPC module
-- Just a debugging function
echo :: String -> MetadMonad String
echo = return
-- | Update the configuration with the received instance parameters.
updateConfig :: J.JSValue -> MetadMonad ()
updateConfig input = do
(name, instanceParams) <- J.fromJResultE "Could not get instance parameters"
$ Config.getInstanceParams input
cfg' <- modifyInstParams $ \cfg ->
let cfg' = mergeConfig cfg instanceParams
in return (cfg', cfg')
L.logInfo $
"Updated instance " ++ show name ++ " configuration"
L.logDebug $ "Instance configuration: " ++ show cfg'
-- * The list of all functions exported to RPC.
exportedFunctions :: [Name]
exportedFunctions = [ 'echo
, 'updateConfig
]
|
dimara/ganeti
|
src/Ganeti/Metad/ConfigCore.hs
|
bsd-2-clause
| 4,600
| 0
| 14
| 830
| 582
| 327
| 255
| 57
| 1
|
{-
Module : CSH.Eval.Frontend.Members
Description : The route handler for the members page
Copyright : Stephen Demos, Matt Gambogi, Travis Whitaker, Computer Science House 2015
License : MIT
Maintainer : pvals@csh.rit.edu
Stability : Provisional
Portability : POSIX
DOCUMENT THIS!
-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ViewPatterns #-}
module CSH.Eval.Frontend.Members (
getMembersR
, getMemberR
) where
import qualified Data.ByteString.Char8 as B
import CSH.Eval.Cacheable.Fetch
import CSH.Eval.Model
import CSH.Eval.Frontend.Data
import qualified Data.Text as T
import System.Log.Logger
import Yesod
import Network.HTTP.Types
-- | The handler for the members listing page
getMembersR :: Handler Html
getMembersR = defaultLayout $(whamletFile "frontend/templates/members/index.hamlet")
dummyMembers :: [(String, String, Int, Bool, Bool)]
dummyMembers = take 100 . cycle $
[("harlan", "Harlan Haskins", 4, True, True)
,("dag10", "Drew Gottlieb", 4, True, False)
,("tmobile", "Travis Whitaker", 8, True, False)
]
charFor :: Bool -> T.Text
charFor True = "✅"
charFor False = "❌"
-- | The handler for a single member's page
getMemberR :: String -> Handler Html
getMemberR username = do
y <- getYesod
let cache = getCache y
let logger = getFrontendLogger y
eitherUsr <- execCacheable cache (getMemberUsername (T.pack username))
let attendance = [("Evals", "Committee", "10/13/2015"), ("Financial", "Committee", "10/13/2015")]
case eitherUsr of
(Left _) -> sendResponseStatus internalServerError500 ("Could not find " ++ username)
(Right usr) -> defaultLayout $(whamletFile "frontend/templates/index.hamlet")
widgetEval :: Evaluation -> Widget
widgetEval eval = do
y <- getYesod
$(whamletFile "frontend/templates/member/widgets/evaluation.hamlet")
|
robgssp/csh-eval
|
src/CSH/Eval/Frontend/Members.hs
|
mit
| 2,094
| 0
| 13
| 448
| 417
| 237
| 180
| 41
| 2
|
import Test.Cabal.Prelude
-- The one local package, pkg, has a setup dependency on setup-dep-2.0, which is
-- in the repository.
main = cabalTest $ do
skipUnless =<< hasNewBuildCompatBootCabal
withRepo "repo" $ do
r <- recordMode DoNotRecord $ cabal' "new-build" ["pkg"]
-- pkg's setup script should print out a message that it imported from
-- setup-dep:
assertOutputContains "pkg Setup.hs: setup-dep-2.0" r
|
mydaum/cabal
|
cabal-testsuite/PackageTests/NewBuild/CustomSetup/LocalPackageWithCustomSetup/build-local-package-with-custom-setup.test.hs
|
bsd-3-clause
| 430
| 0
| 14
| 81
| 67
| 33
| 34
| 6
| 1
|
module LocalSettingsCabal where
import Paths_HaRe
import GHC.Paths ( libdir )
--GHC.Paths is available via cabal install ghc-paths
-- rELEASE_ROOT =
hare_version = version
-- release_root= showNoQuotes "${RELEASE_ROOT}"
--release_root = getDataFileName "."
release_root = "."
{-
refactorer = showNoQuotes "${REFACTORER}"
refactorer_client = showNoQuotes "${REFACTORER_CLIENT}"
preludePath = "${PRELUDE}"
-}
reportFilePath = release_root ++ "/refactorer/duplicate/report.txt"
answerFilePath = release_root ++ "/refactorer/duplicate/answers.txt"
{-
positionFilePath = "${RELEASE_ROOT}/refactorer/duplicate/positions.txt"
-}
transFilePath = release_root ++ "/refactorer/duplicate/transforms.txt"
classAnswerPath = release_root ++ "/refactorer/duplicate/classAnswer.txt"
classTransformPath = release_root ++ "/refactorer/duplicate/classTransform.txt"
mergeFilePath = release_root ++ "/refactorer/merging/mergeCache.txt"
ghcPath = libdir
evalFilePath = release_root ++ "/refactorer/evalMon/evalCache.txt"
-- ++AZ++: this is an executable, need, to see if it can become a straight function call
evaluate = release_root ++ "/refactorer/evaluate"
evaluate_result = release_root ++ "/refactorer/evaluate_result"
genFoldPath = release_root ++ "/refactorer/genFoldCache.txt"
{-
(refactor_prg:refactor_args) = words refactorer -- for emacs
-}
showNoQuotes x = init $ tail $ show x
|
RefactoringTools/HaRe
|
old/editors/LocalSettingsCabal.hs
|
bsd-3-clause
| 1,392
| 0
| 6
| 163
| 149
| 87
| 62
| 17
| 1
|
{-# LANGUAGE PartialTypeSignatures #-}
module PatBind3 where
-- Oddly GHC 8.0 accepted this, but it should obvoiusly fail!
foo :: (Bool, _) -> Char
Just foo = Just id
|
snoyberg/ghc
|
testsuite/tests/partial-sigs/should_fail/PatBind3.hs
|
bsd-3-clause
| 168
| 0
| 6
| 30
| 33
| 19
| 14
| 4
| 1
|
{-# LANGUAGE TypeFamilies #-}
module Class3 where
class C a where
foo :: a -> a
instance C ()
bar :: (a ~ ()) => a -> a
bar = foo
|
ryantm/ghc
|
testsuite/tests/indexed-types/should_compile/Class3.hs
|
bsd-3-clause
| 136
| 0
| 8
| 37
| 59
| 32
| 27
| 7
| 1
|
module Y2016.M09.D23.Exercise where
-- below imports available from 1HaskellADay git repository
import Data.BlockChain.Block.Blocks
import Data.BlockChain.Block.Summary
import Data.BlockChain.Block.Transactions
import Data.BlockChain.Block.Types
import Data.Monetary.BitCoin
import Data.Relation
import Graph.Query
import Graph.JSON.Cypher
{--
Okay, we can get the addresses from the transactions, now let's get the
bitcoins from the transaction.
In each output of each transaction there is a field called 'value.' Let's
take a look at that:
*Y2016.M09.D23.Exercise> latestSummary
Summary {blockHash = "000000000000000002f56611a761f70493a1293dadec577cd04dbd7c9a4b4477",
time = 1474579944, blockIndex = 1148714, height = 431032,
txIndices = [176864461,176863406,176863432,176863441,176861799,...]}
Now if we go to blockchain.info and look up this blockHash, we see:
... Transactions ...
<hash> 2016-09-22 21:32:24
from-to hashes 13.02390887 BTC
total: 13.02390887 BTC
<hash> 2016-09-22 21:26:33
from-to hashes 0.08284317 BTC
0.07408666 BTC
total: 0.15691983 BTC
... etc ...
Now, let's look at the values of the first two transactions of this block:
*Y2016.M09.D23.Exercise> mapM_ (print . value) (concatMap out (take 2 (tx (head blk))))
1302390887
8284317
7407666
HUH! ... HUH! ... and again I say ... HUH!
Today's Haskell exercise. Distill the transaction to the inputs, and the
outputs with a BTC (BitCoin) value for each output. Use the transactions from
the latestSummary.
--}
data Trade = Trd { tradeHash :: Hash, executed :: String,
ins :: [Maybe Hash], outs :: [(Hash, BitCoin)] }
deriving (Eq, Ord, Show)
-- What was the biggest trade, BitCoin-value-wise, from the latestSummary?
-- What was the biggest trade, most addresses (ins and outs)?
{-- BONUS -----------------------------------------------------------------
Represent Trade as a set of relations. Upload those relations to a graph
database for your viewing pleasure. Share an image of some of the transactions.
--}
trade2relations :: Trade -> [Relation a b c]
trade2relations = undefined
-- now: coming up with what types a, b, and c are will be fun ... for you.
|
geophf/1HaskellADay
|
exercises/HAD/Y2016/M09/D23/Exercise.hs
|
mit
| 2,234
| 0
| 10
| 396
| 151
| 97
| 54
| 14
| 1
|
module Solidran.FastaSpec (spec) where
import Test.Hspec
import Solidran.Fasta
import qualified Data.Map as Map
spec :: Spec
spec = do
describe "Solidran.Fasta" $ do
describe "parse" $ do
it "should give an empty map on empty string" $ do
parse "" `shouldBe` Map.empty
it "should parse a single record" $ do
parse $ unlines
[ ">label1"
, "content1" ]
`shouldBe`
Map.fromList [("label1", "content1")]
it "should parse multiple records" $ do
parse $ unlines
[ ">label1"
, "content1"
, ">label2"
, "content2" ]
`shouldBe`
Map.fromList
[ ("label1", "content1")
, ("label2", "content2") ]
it "should parse empty contents" $ do
parse $ unlines
[ ">label1"
, ">label2" ]
`shouldBe`
Map.fromList
[ ("label1", "")
, ("label2", "") ]
it "should parse empty and non-empty" $ do
parse $ unlines
[ ">label1"
, "content1"
, ">label2" ]
`shouldBe`
Map.fromList
[ ("label1", "content1")
, ("label2", "") ]
|
Jefffrey/Solidran
|
test/Solidran/FastaSpec.hs
|
mit
| 1,553
| 0
| 19
| 804
| 303
| 164
| 139
| 43
| 1
|
module STSpec
( main
, spec
) where
import Numeric.LinearAlgebra.Easy
import Test.Hspec
spec :: Spec
spec = do
describe "withSTMatrix" $ do
it "should create expected matrix" $ do
let m = withSTMatrix 9 3 3 $ \m -> do
writeMatrix m 0 0 10.0
writeMatrix m 1 1 20.0
writeMatrix m 2 2 30.0
m `atIndex` (0, 0) `shouldBe` 10.0
m `atIndex` (0, 1) `shouldBe` 9.0
m `atIndex` (0, 2) `shouldBe` 9.0
m `atIndex` (1, 0) `shouldBe` 9.0
m `atIndex` (1, 1) `shouldBe` 20.0
m `atIndex` (1, 2) `shouldBe` 9.0
m `atIndex` (2, 0) `shouldBe` 9.0
m `atIndex` (2, 1) `shouldBe` 9.0
m `atIndex` (2, 2) `shouldBe` 30.0
main :: IO ()
main = hspec spec
|
rcook/mlutil
|
easyla/spec/STSpec.hs
|
mit
| 867
| 0
| 20
| 356
| 321
| 182
| 139
| 24
| 1
|
{-# LANGUAGE NamedFieldPuns, RecordWildCards #-}
--------------------------------------------------------------------------------
-- Haskell asteroid game
--------------------------------------------------------------------------------
module Main where
import Data.IORef
import Data.List
import Data.Time
import Data.Fixed
import Control.Monad
import Control.Applicative
import System.Random
import Graphics.UI.GLUT
--------------------------------------------------------------------------------
-- Game state & objects
--------------------------------------------------------------------------------
type Asteroids = [ Asteroid ]
type Bullets = [ Bullet ]
type Vec2f = ( GLfloat, GLfloat )
type Collision = ( Asteroid, Bullet )
data Bullet = Bullet { bPos :: Vec2f
, bRot :: GLfloat
}
deriving (Eq, Show)
data Asteroid = Asteroid { aSize :: GLfloat
, aRot :: GLfloat
, aPos :: Vec2f
, aVel :: Vec2f
}
deriving (Eq, Show)
data State = State { sSize :: IORef Vec2f
, sPos :: IORef Vec2f
, sMoving :: IORef Bool
, sRot :: IORef GLfloat
, sRotLeft :: IORef Bool
, sRotRight :: IORef Bool
, sAsteroids :: IORef [ Asteroid ]
, sBullets :: IORef [ Bullet ]
, sCount :: IORef Int
, sLastFrame :: IORef UTCTime
, sScore :: IORef GLfloat
, sLives :: IORef Int
}
--------------------------------------------------------------------------------
-- Helper functions
--------------------------------------------------------------------------------
color3f :: GLfloat -> GLfloat -> GLfloat -> IO ()
color3f r g b
= color $ Color3 r g b
vertex2f :: GLfloat -> GLfloat -> IO ()
vertex2f x y
= vertex $ Vertex2 x y
rasterPos2f :: GLfloat -> GLfloat -> IO ()
rasterPos2f x y
= rasterPos $ Vertex2 x y
clamp ::GLfloat -> GLfloat -> GLfloat -> GLfloat
clamp x a b
= max a (min x b)
--------------------------------------------------------------------------------
-- Rendering
--------------------------------------------------------------------------------
render :: State -> IO ()
render State {..} = do
( w, h ) <- get sSize
( x, y ) <- get sPos
rot <- get sRot
asteroids <- get sAsteroids
bullets <- get sBullets
score <- get sScore
lives <- get sLives
clear [ ColorBuffer ]
-- Set up matrices
matrixMode $= Projection
loadIdentity
ortho 0.0 (realToFrac w) (realToFrac h) 0.0 (-1.0) 1.0
matrixMode $= Modelview 0
loadIdentity
-- Render stuff
mapM_ renderAsteroid asteroids
mapM_ renderBullet bullets
-- Render the player
preservingMatrix $ do
translate $ Vector3 x y 0.0
rotate rot $ Vector3 0 0 1
color3f 1 1 1
renderPrimitive LineLoop $ do
vertex2f (-5) (-5)
vertex2f (10) ( 0)
vertex2f (-5) ( 5)
-- Score
rasterPos2f 5 15
renderString Fixed8By13 $ show (floor score)
-- Game over message
when (lives <= 0) $ do
rasterPos2f (w / 2 - 25) (h / 2 - 20)
renderString Fixed8By13 $ "Score: " ++ show score
rasterPos2f (w / 2 - 100) (h / 2)
renderString Fixed8By13 $ "Game over! Press X to restart"
-- Health
mapM_ (renderHealth . fromIntegral) [1..lives]
flush
renderAsteroid :: Asteroid -> IO ()
renderAsteroid Asteroid { aSize, aRot, aPos = ( x, y )}
= preservingMatrix $ do
translate $ Vector3 x y 0
rotate aRot $ Vector3 0 0 1
scale aSize aSize aSize
color3f 1 1 1
renderPrimitive LineLoop $ do
vertex2f 1.0 1.0
vertex2f 0.1 (-0.4)
vertex2f 1.0 (-0.5)
vertex2f (-0.4) (-1.0)
vertex2f (-1.0) (-0.2)
vertex2f (-0.8) 0.2
vertex2f (-0.4) 0.1
vertex2f (-0.1) 1.0
renderBullet :: Bullet -> IO ()
renderBullet Bullet { bPos = ( x, y ), bRot}
= preservingMatrix $ do
translate $ Vector3 x y 0
rotate bRot $ Vector3 0 0 1
color3f 1 0 0
renderPrimitive LineLoop $ do
vertex2f (-2) (-2)
vertex2f ( 2) ( 0)
vertex2f (-2) ( 2)
renderHealth :: GLfloat -> IO ()
renderHealth count
= preservingMatrix $ do
translate $ Vector3 (50 + count * 10) 10 0
renderPrimitive Quads $ do
vertex2f 0 0
vertex2f 0 5
vertex2f 5 5
vertex2f 5 0
--------------------------------------------------------------------------------
-- Update
--------------------------------------------------------------------------------
idle :: State -> IO ()
idle state@State {..} = do
-- Retrieve stuff from the state
( w, h ) <- get sSize
( x, y ) <- get sPos
rotLeft <- get sRotLeft
rotRight <- get sRotRight
asteroids <- get sAsteroids
bullets <- get sBullets
count <- get sCount
moving <- get sMoving
lives <- get sLives
-- Don't do anything if we're not playing
when (lives > 0) $ do
-- Compute the time elapsed since the last frame
thisFrame <- getCurrentTime
lastFrame <- get sLastFrame
sLastFrame $= thisFrame
let dt = 500 * (realToFrac $ diffUTCTime thisFrame lastFrame)
-- Update entites
let ( asteroids', bullets' ) = update w h dt asteroids bullets
sBullets $= bullets'
sAsteroids $= map (moveAsteroid w h dt) asteroids'
-- Cound the score
sScore $~! (+) (foldl (\a x-> a + score x) 0 (asteroids \\ asteroids'))
-- Check if player was hit
when (any (hit x y) asteroids') $ do
sLives $~! (+(-1))
sPos $= ( w / 2, h / 2 )
sAsteroids $= [ ]
sBullets $= [ ]
-- Generate new asteroids
let asteroidCount = length asteroids'
when (asteroidCount < count) $
replicateM_ (count - asteroidCount) (genAsteroid state)
-- Update rotation
when rotLeft $ sRot $~! (+ dt)
when rotRight $ sRot $~! (+ (-dt))
rot <- get sRot
-- Update movement
when moving $ do
let [ dx, dy ] = [ cos, sin ] <*> pure (rot * pi / 180)
sPos $= ( (x + dx * dt * 0.5) `mod'` w, (y + dy * dt * 0.5) `mod'` h )
postRedisplay Nothing
hit :: GLfloat -> GLfloat -> Asteroid -> Bool
hit x y Asteroid { aSize, aPos = ( x', y' )}
= abs (x - x') < aSize && abs (y - y') < aSize
-- Computes the score given for destroying an asteroid
score :: Asteroid -> GLfloat
score (Asteroid s r ( x, y ) ( vx, vy ))
= vel * 100
where
vel = sqrt (vx * vx + vy * vy)
-- Updates the position of an asteroid
moveAsteroid :: GLfloat -> GLfloat -> GLfloat ->Asteroid -> Asteroid
moveAsteroid w h dt a@(Asteroid s r ( x, y ) ( vx, vy ))
= a { aPos = ( (x + vx * dt) `mod'` w, (y + vy * dt) `mod'` h ) }
update :: GLfloat
-> GLfloat
-> GLfloat
-> Asteroids
-> Bullets
-> ( Asteroids, Bullets )
update w h dt as
= foldr check ( as, [ ] )
where
-- Check for collisions between bullets and asteroids
check (Bullet ( x, y ) r ) ( as, bs )
| outside || any hitA as = ( concatMap split as, bs )
| otherwise = ( as, newBullet : bs )
where
-- Check if the bullet is outside the screen
outside
= x < -w || w < x || y < -h || h < y
-- Bullet with updated position
newBullet
= Bullet ( x + dx * dt, y + dy * dt ) r
where
[ dx, dy ] = [ cos, sin ] <*> pure (r * pi / 180)
-- Check if the bullet hit an asteroid
hitA Asteroid { aSize, aPos = ( x', y' ) }
= abs (x - x') <= aSize && abs (y - y') <= aSize
-- Splits an asteroid in two
split a@(Asteroid s r ( x', y' ) ( vx, vy ))
| hit x y a && s < 10 = [ ]
| hit x y a && s > 10 = [ shard 0.2, shard (-0.2) ]
| otherwise = [ a ]
where
angle = atan2 vy vx
speed = sqrt (vx * vx + vy * vy) * 1.5
shard f
= Asteroid (s / 2) r ( x', y') ( vx', vy' )
where
vx' = speed * cos (angle + f)
vy' = speed * sin (angle + f)
genAsteroid :: State -> IO ()
genAsteroid State { sSize, sAsteroids } = do
( w, h ) <- get sSize
asteroids <- get sAsteroids
size <- randomIO :: IO GLfloat
angle <- randomIO :: IO GLfloat
rot <- randomIO :: IO GLfloat
let vx = cos (angle * 2 * pi)
vy = sin (angle * 2 * pi)
x = 100
y = 100
a = Asteroid (10.0 + 30.0 * size)
rot
( clamp x 0 w, clamp y 0 h )
( -vx / 10.0, -vy / 10.0 )
sAsteroids $= a : asteroids
reshape :: State -> Size -> IO ()
reshape State { sSize, sPos } (Size w h) = do
let w' = fromIntegral w
h' = fromIntegral h
sSize $= ( w', h' )
sPos $= ( w' / 2, h' / 2 )
viewport $= (Position 0 0, Size w h)
postRedisplay Nothing
keyboardDown :: State -> Char -> Position -> IO ()
keyboardDown State { sMoving } 'w' _pos
= sMoving $= True
keyboardDown State { sRotRight } 'd' _pos
= sRotRight $= True
keyboardDown State { sRotLeft } 'a' _pos
= sRotLeft $= True
keyboardDown _state _char _pos
= postRedisplay Nothing
keyboardUp :: State -> Char -> Position -> IO ()
keyboardUp State { sMoving } 'w' _pos
= sMoving $= False
keyboardUp State { sRotRight } 'd' _pos
= sRotRight $= False
keyboardUp State { sRotLeft } 'a' _pos
= sRotLeft $= False
keyboardUp State { sBullets, sRot, sPos } ' ' _pos = do
bullets <- get sBullets
rot <- get sRot
( x, y ) <- get sPos
sBullets $= (Bullet ( x, y ) rot : bullets)
keyboardUp State {..} 'x' _pos = do
lives <- get sLives
when (lives <= 0) $ do
sLives $= 3
sScore $= 0
keyboardUp _state _char _pos
= postRedisplay Nothing
--------------------------------------------------------------------------------
-- Setup
--------------------------------------------------------------------------------
main :: IO ()
main = do
( _pname, _args ) <- getArgsAndInitialize
_window <- createWindow "Haskell Asteroids"
globalKeyRepeat $= GlobalKeyRepeatOff
state <- State <$> newIORef ( 800, 600 )
<*> newIORef ( 400, 300 )
<*> newIORef False
<*> newIORef 0
<*> newIORef False
<*> newIORef False
<*> newIORef [ ]
<*> newIORef [ ]
<*> newIORef 5
<*> (getCurrentTime >>= newIORef)
<*> newIORef 0
<*> newIORef 3
displayCallback $= render state
idleCallback $= Just (idle state)
reshapeCallback $= Just (reshape state)
keyboardCallback $= Just (keyboardDown state)
keyboardUpCallback $= Just (keyboardUp state)
mainLoop
|
nandor/hasteroid
|
Main.hs
|
mit
| 11,011
| 0
| 21
| 3,524
| 3,699
| 1,862
| 1,837
| 263
| 1
|
--Find the last but one element of a list.
module Problem02 where
lst = [1,2,3,4,5]
myButLast :: [a] -> a
myButLast (x:y:[]) = x
myButLast (_:xs) = myButLast xs
myButLast' :: [a] -> a
myButLast' [x,_] = x
myButLast' (x:xs) = myButLast' xs
|
Matt-Renfro/haskell
|
H-99/Problem2.hs
|
mit
| 252
| 0
| 9
| 56
| 120
| 68
| 52
| 8
| 1
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
module Buchhaltung.Uniques
where
import Buchhaltung.Common
import Control.Arrow hiding (loop)
import Control.Monad.RWS.Strict
import Control.Monad.Trans.Cont
import Data.Function
import Data.List
import qualified Data.ListLike as L
import qualified Data.ListLike.String as L
import qualified Data.Map as M
import Data.Ord
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Lazy as TL
import Data.Time.Calendar
import Debug.Trace
import Formatting as F
import qualified Formatting.ShortFormatters as F
import Hledger.Data
import System.IO
import Text.EditDistance
import qualified Text.PrettyPrint.Boxes as P
import Text.Printf
-- | The monad stack
type M r m = ContT r (RWST () () (M.Map KeyIx (Aged Entry)) m)
data Aged a = Aged { getAge :: Age
, unAged :: a
}
deriving Show
data Age = Old | New
deriving (Show, Eq)
-- | the key that is used to compare transactions. The Int is a
-- counter, to ensure there are no actual duplicates in the
-- map and to be able to update entries.
--
-- Duplicates are then found by extraction of a key range using
-- 'M.split'. See 'findDuplicates'.
type Key = ([(CommoditySymbol,Quantity)], AccountName, Day)
type KeyIx = (Key, Int)
-- | Takes a list of new entries, removes duplicates or updates
-- existing transactions and adds new entries.
addNewEntriesToJournal :: (MonadIO m, MonadReader (Options user Config env) m)
=> [FilledEntry]
-- ^ new candidates including entries already existing in
-- journal possible duplicates
-> Journal
-> m [Entry]
addNewEntriesToJournal newTxs journal = do
tag <- askTag
let toKeyVal i tx = ((deriveKey tx, i)
, Aged Old $ ImportedEntry tx () $
wSource <$> extractSource tag tx)
fmap (fmap unAged . M.elems . fst)
<$> execRWST (evalContT $ callCC $ \exit -> zipWithM_
(loop exit $ length newTxs) [1..] newTxs)
() $ M.fromList $ zipWith toKeyVal [1..] $ jtxns journal
-- | Derive a key from a transaction and an index
deriveKey :: Transaction -> Key
deriveKey tx = (compAmount $ pamount p, paccount p, tdate tx)
where compAmount (Mixed am) = sort $ fmap (acommodity &&& aquantity) am
p = head $ tpostings tx
-- | loop through all existing possible duplicates of a new
-- transaction
loop :: (MonadIO m, MonadReader (Options user Config env) m)
=> (() -> M r m ())
-> Int -> Int -> FilledEntry -> M r m ()
loop exit totalTx iTx new = do
let msg = format ("Transaction: "%F.d%" of "%F.d%" new\n") iTx totalTx
dups <- findFuzzy $ ieT new
checkOrAsk exit new msg
$ sortBy (flip $ comparing snd) $ (id &&& distance) <$> dups
where distance (_, y) =
-- careful: the negate is fmapped over the Maybe value
-- which changes the relative order between Nothing and
-- Justs.
negate . on
(restrictedDamerauLevenshteinDistance defaultEditCosts)
(TL.unpack . json) (ieSource new)
<$> (eitherToMaybe $ ieSource $ unAged y)
eitherToMaybe :: Either b a -> Maybe a
eitherToMaybe = either (const Nothing) Just
-- | Find all duplicates for a given key
findDuplicates :: Monad m => Key -> M r m [(KeyIx,Aged Entry)]
findDuplicates key@(ams,acc,day) = lift $ gets $ \old ->
let later = snd $ M.split (key,0) old in
M.toList $ fst $ M.split ((ams,acc,addDays 1 day),0) later
findFuzzy :: Monad m => Transaction -> M r m [(KeyIx,Aged Entry)]
findFuzzy = fmap concat . mapM (findDuplicates . deriveKey) . alternatives
where alternatives x = [x] ++ conditionalDateShift x
conditionalDateShift tx = if paccount (head (tpostings tx)) == "Aktiva:Konten:Comdirect:Visa"
then map (\s -> tx { tdate = addDays s $ tdate tx }) [-1,1]
else []
-- | check single new entry against a list of conflict
-- candidates, and insert new entry (if list is empty), or keep old
-- entry (if identical to new one), or ask weither to modify old entry
-- or insert new entry.
checkOrAsk :: (MonadIO m, MonadReader (Options user Config env) m)
=> (() -> M r m ())
-> FilledEntry
-> TL.Text -- ^ message
-> [((KeyIx, Aged Entry), Maybe Int)] -> M r m ()
checkOrAsk _ new _ [] = do
newIx <- gets $ \old -> M.size old + 1
modify $ uncurry M.insert $ ((deriveKey $ ieT new, newIx), Aged New $ fromFilled new)
liftIO $ T.putStrLn "\nSaved new transaction.\n"
checkOrAsk exit new msg (( (oldKey, oldEntry), cost):remaining) = do
if getAge oldEntry == Old && cost == Just 0
then return () -- do nothing, i.e. use old unchanged
else if False && cost > Just ( - 98)
&& on (==) (tdate.ieT) (unAged oldEntry) (fromFilled new)
then do
-- liftIO $ do print (fst new) >> print (oldKey)
-- print (tdate.ieT.snd $ new) >> print (tdate.ieT $ oldEntry)
-- print (ieSource.snd $ new) >> print (ieSource $ oldEntry)
overwriteOldSource
else do
let question = (answer =<<) . liftIO $ do
L.putStr $ L.unlines
[ prettyPrint cost new oldEntry msg $ length remaining
, "Yes, they are duplicates. Update the source [y]"
, "No, " <> (if null remaining then "Save as new transaction"
else "Show next duplicate") <> " [n]"
, "Skip this new transaction [q]"
, "Skip this and all remaining transactions [Q]"
, "Your answer:" ]
hSetBuffering stdin NoBuffering
getChar <* putStrLn ""
answer 'y' = overwriteOldSource
answer 'n' = checkOrAsk exit new msg remaining
answer 'q' = return ()
answer 'Q' = exit ()
answer _ = question
question
where
overwriteOldSource = lift $ do
tag <- lift $ askTag
modify $ M.adjust (applyChanges tag new (deriveKey $ ieT new) $ fst oldKey) oldKey
liftIO $ T.putStrLn "\nUpdated duplicate's source.\n"
prettyPrint :: Maybe Int -> FilledEntry -> Aged Entry -> TL.Text -- ^ Message
-> Int -- ^ Remaining
-> T.Text
prettyPrint cost new (Aged age old) msg remain =
let union2 = f . second unzip . unzip . M.toList $ M.mergeWithKey g
(fmap $ flip (,) "<empty>") (fmap $ (,) "<empty>")
(either (const mempty) sourceToMap $ oldSource)
$ sourceToMap $ ieSource new
g _ x y | x == y = Just $ (x, "")
| True = Just $ (x, y)
f (k,(old,new)) = T.pack $ P.render
$ table [20, 25, 25] header [k, old, new]
oldName Old = "Old"
oldName New = "Imported earlier"
header = ["Field", oldName age, "New"]
oldSource = ieSource old
showError (Left x) = [""
,"Error retrieving old transaction's source:"
, T.pack x]
showError (Right _) = []
def _ Nothing = "n.a."
def f (Just x) = f x
in
L.unlines $
[ union2 ]
++ [ sformat
("changes: "%F.s%"/"%F.s%"\n"%F.t%"Remaining existing duplicates: "%F.d)
(def (show . negate) cost)
(def (show . TL.length . json) $ eitherToMaybe $ ieSource old)
msg
remain
]
++ showError oldSource
applyChanges :: ImportTag -> FilledEntry -> Key -- ^ new key
-> Key -- ^ old key
-> Aged Entry -> Aged Entry
applyChanges tag newEntry (ams2,acc2,day2) (ams1, acc1, _) oldEntry =
if (ams2,acc2) /= (ams1,acc1) then
error $ unlines ["Change not supported: "
, show newEntry
, show oldEntry]
else Aged New $ (unAged oldEntry){
ieT= (injectSource tag (ieSource newEntry)
$ ieT $ unAged oldEntry){tdate = day2} }
|
johannesgerer/buchhaltung
|
src/Buchhaltung/Uniques.hs
|
mit
| 8,223
| 0
| 24
| 2,468
| 2,424
| 1,289
| 1,135
| 157
| 8
|
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.UIEvent
(js_initUIEvent, initUIEvent, js_getView, getView, js_getDetail,
getDetail, js_getKeyCode, getKeyCode, js_getCharCode, getCharCode,
js_getLayerX, getLayerX, js_getLayerY, getLayerY, js_getPageX,
getPageX, js_getPageY, getPageY, js_getWhich, getWhich, UIEvent,
castToUIEvent, gTypeUIEvent, IsUIEvent, toUIEvent)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe
"$1[\"initUIEvent\"]($2, $3, $4,\n$5, $6)" js_initUIEvent ::
UIEvent ->
JSString -> Bool -> Bool -> Nullable Window -> Int -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/UIEvent.initUIEvent Mozilla UIEvent.initUIEvent documentation>
initUIEvent ::
(MonadIO m, IsUIEvent self, ToJSString type') =>
self -> type' -> Bool -> Bool -> Maybe Window -> Int -> m ()
initUIEvent self type' canBubble cancelable view detail
= liftIO
(js_initUIEvent (toUIEvent self) (toJSString type') canBubble
cancelable
(maybeToNullable view)
detail)
foreign import javascript unsafe "$1[\"view\"]" js_getView ::
UIEvent -> IO (Nullable Window)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/UIEvent.view Mozilla UIEvent.view documentation>
getView :: (MonadIO m, IsUIEvent self) => self -> m (Maybe Window)
getView self
= liftIO (nullableToMaybe <$> (js_getView (toUIEvent self)))
foreign import javascript unsafe "$1[\"detail\"]" js_getDetail ::
UIEvent -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/UIEvent.detail Mozilla UIEvent.detail documentation>
getDetail :: (MonadIO m, IsUIEvent self) => self -> m Int
getDetail self = liftIO (js_getDetail (toUIEvent self))
foreign import javascript unsafe "$1[\"keyCode\"]" js_getKeyCode ::
UIEvent -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/UIEvent.keyCode Mozilla UIEvent.keyCode documentation>
getKeyCode :: (MonadIO m, IsUIEvent self) => self -> m Int
getKeyCode self = liftIO (js_getKeyCode (toUIEvent self))
foreign import javascript unsafe "$1[\"charCode\"]" js_getCharCode
:: UIEvent -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/UIEvent.charCode Mozilla UIEvent.charCode documentation>
getCharCode :: (MonadIO m, IsUIEvent self) => self -> m Int
getCharCode self = liftIO (js_getCharCode (toUIEvent self))
foreign import javascript unsafe "$1[\"layerX\"]" js_getLayerX ::
UIEvent -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/UIEvent.layerX Mozilla UIEvent.layerX documentation>
getLayerX :: (MonadIO m, IsUIEvent self) => self -> m Int
getLayerX self = liftIO (js_getLayerX (toUIEvent self))
foreign import javascript unsafe "$1[\"layerY\"]" js_getLayerY ::
UIEvent -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/UIEvent.layerY Mozilla UIEvent.layerY documentation>
getLayerY :: (MonadIO m, IsUIEvent self) => self -> m Int
getLayerY self = liftIO (js_getLayerY (toUIEvent self))
foreign import javascript unsafe "$1[\"pageX\"]" js_getPageX ::
UIEvent -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/UIEvent.pageX Mozilla UIEvent.pageX documentation>
getPageX :: (MonadIO m, IsUIEvent self) => self -> m Int
getPageX self = liftIO (js_getPageX (toUIEvent self))
foreign import javascript unsafe "$1[\"pageY\"]" js_getPageY ::
UIEvent -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/UIEvent.pageY Mozilla UIEvent.pageY documentation>
getPageY :: (MonadIO m, IsUIEvent self) => self -> m Int
getPageY self = liftIO (js_getPageY (toUIEvent self))
foreign import javascript unsafe "$1[\"which\"]" js_getWhich ::
UIEvent -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/UIEvent.which Mozilla UIEvent.which documentation>
getWhich :: (MonadIO m, IsUIEvent self) => self -> m Int
getWhich self = liftIO (js_getWhich (toUIEvent self))
|
manyoo/ghcjs-dom
|
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/UIEvent.hs
|
mit
| 4,724
| 70
| 11
| 737
| 1,169
| 647
| 522
| 70
| 1
|
-- Get all possible products of two lists of numbers
-- https://www.codewars.com/kata/57da6a507691c30926000042
module AllProducts where
import Control.Applicative(liftA2)
getProducts :: [Integer] -> [Integer] -> [Integer]
getProducts = flip $ liftA2 (*)
|
gafiatulin/codewars
|
src/Beta/AllProducts.hs
|
mit
| 257
| 0
| 7
| 33
| 52
| 32
| 20
| 4
| 1
|
module Graph.SparseSet (
module Graph.Type.SparseSet
, bronKerboschLai
) where
import Graph.Type.SparseSet
import Data.Set hiding (map)
import Prelude hiding (null)
--------------------------------------------------------------------------------
-- Utilities
vertices :: Graph -> Vertices
vertices (Graph list) = fromList [0 .. length list - 1]
neighbor :: Graph -> Vertex -> Vertices
neighbor (Graph list) v = list !! v
--------------------------------------------------------------------------------
-- Bron-Kerbosch-Lai Algorithm
-- finds the size of the biggest maximal cliques in an undirected graph
bronKerboschLai :: Graph -> Int
bronKerboschLai g = go g empty (vertices g) empty
-- with pivoting, without vertex degeneracy ordering
go :: Graph -> Vertices -> Vertices -> Vertices -> Int
go g r p x
| null p && null x = size r -- found a clique
| null p = 0 -- backtracks
| otherwise = maximum (map next (toList vs))
where pivot = findMin (p `union` x)
vs = p `difference` neighbor g pivot
next v = go g
(v `insert` r)
(p `intersection` neighbor g v)
(x `intersection` neighbor g v)
|
banacorn/Graphentheoretische-Paralleler-Algorithmus
|
src/Graph/SparseSet.hs
|
mit
| 1,274
| 0
| 10
| 351
| 337
| 182
| 155
| 23
| 1
|
{-# OPTIONS_GHC -fno-warn-deprecations #-}
module Network.HTTP.Toolkit (
-- * Exceptions
-- |
-- * All functions that consume input fail with `UnexpectedEndOfInput` if the
-- input ends before the function can completely successfully.
--
-- * All cases where a function may fail with an exception other than
-- @UnexpectedEndOfInput@ are documented thoroughly on a per function level.
--
ToolkitError(..)
-- * Input handling
, InputStream
, makeInputStream
, inputStreamFromHandle
-- * Handling requests
, RequestPath
, Request(..)
, readRequestWithLimit
, readRequest
, sendRequest
-- * Handling responses
, Response(..)
, readResponseWithLimit
, readResponse
, sendResponse
, simpleResponse
-- * Handling message bodies
, BodyReader
, sendBody
, consumeBody
-- * Deprecated types and functions
, Connection
, makeConnection
, connectionFromHandle
) where
import Network.HTTP.Toolkit.Body
import Network.HTTP.Toolkit.InputStream
import Network.HTTP.Toolkit.Connection
import Network.HTTP.Toolkit.Request
import Network.HTTP.Toolkit.Response
import Network.HTTP.Toolkit.Error
|
zalora/http-kit
|
src/Network/HTTP/Toolkit.hs
|
mit
| 1,148
| 0
| 5
| 207
| 137
| 99
| 38
| 28
| 0
|
module Phocid ( phocid
, runWithPhocid
) where
------------------------------------------------------------------------------
import Data.List (sort)
import Options.Applicative
import System.Directory
import System.FilePath
import System.Exit
------------------------------------------------------------------------------
import Types (Phocid(..), Photo(..))
import Template
import Photo
------------------------------------------------------------------------------
phocid :: Parser Phocid
phocid = Phocid
<$> ( argument str
( metavar "INPUT_DIR"
<> help "Directory to scan for photos" ) )
<*> ( argument str
( metavar "OUTPUT_DIR"
<> help "Output directory for site files" ))
<*> ( switch
( long "verbose"
<> help "Verbose output" ))
<*> ( strOption
( long "title"
<> short 't'
<> help "Site title"
<> showDefault
<> value "Untitled"
<> metavar "TITLE" ))
runWithPhocid :: Phocid -> IO ()
runWithPhocid p = do
absInDir <- makeAbsolute $ inputDir p
photos <- sort <$> checkPhotos (verbose p) absInDir
outDirExists <- doesDirectoryExist out
if outDirExists
then die $ "Directory exists: " ++ out
else do
absOutDir <- makeAbsolute out
createDirectory absOutDir
let absImgDir = absOutDir </> "images"
photoPaths = map getPath photos
createDirectory absImgDir
mapM_ (\file -> (absInDir </> file) `copyFile` (absImgDir </> file)) photoPaths
let html = renderIndex photos (title p)
writeFile (absOutDir </> "index.html") html
where
out = outputPath p
|
mjhoy/phocid
|
src/Phocid.hs
|
gpl-2.0
| 1,720
| 0
| 15
| 462
| 417
| 211
| 206
| 45
| 2
|
x0 :: Double
x0 = 380.0
y0 :: Double
y0 = 370.0
vxmax = 6.0
grv = 0.21875
vymax = -6.5
p :: Double -> (Double,Double)
p t = (x0 + vxmax * t, grv/2.0 * t * t + vymax *t + y0)
yl = 310.0
intersection :: Double
intersection = (-1) * sqrt ( (2.0*(yl-y0))/grv + (vymax*vymax)/(grv*grv) ) - vymax/grv
|
pmiddend/jumpie
|
research/platform_math_proto.hs
|
gpl-3.0
| 303
| 0
| 16
| 70
| 177
| 98
| 79
| 12
| 1
|
{-# LANGUAGE TemplateHaskell, TypeApplications, ScopedTypeVariables, RankNTypes #-}
module Lamdu.Calc.Term.Utils
( Composite(..), tags, rest
, case_
, recExtend
, culledSubexprPayloads
) where
import qualified Control.Lens as Lens
import Hyper (Recursively(..), HFoldable(..), (#>), withDict)
import Hyper.Syntax.Row (RowExtend(..))
import Lamdu.Calc.Term (Val)
import qualified Lamdu.Calc.Term as V
import qualified Lamdu.Calc.Type as T
import Lamdu.Prelude
-- | Return all subexprs until the given cut-point
culledSubexprPayloads ::
forall t a r.
Recursively HFoldable t =>
(forall n. a # n -> Maybe r) -> Ann a # t -> [r]
culledSubexprPayloads f (Ann pl body) =
case f pl of
Nothing -> []
Just x ->
withDict (recursively (Proxy @(HFoldable t))) $
x : hfoldMap (Proxy @(Recursively HFoldable) #> culledSubexprPayloads f) body
data Composite a = Composite
{ _tags :: Map T.Tag a
, _rest :: Maybe a
} deriving (Functor, Foldable, Traversable)
Lens.makeLenses ''Composite
case_ :: RowExtend T.Tag V.Term V.Term # Annotated pl -> Composite (Val pl)
case_ (RowExtend tag handler r) =
caseVal r
& tags . Lens.at tag ?~ handler
where
caseVal v@(Ann _ body) =
case body of
V.BLeaf V.LAbsurd -> Composite mempty Nothing
V.BCase x -> case_ x
_ -> Composite mempty (Just v)
recExtend :: RowExtend T.Tag V.Term V.Term # Annotated pl -> Composite (Val pl)
recExtend (RowExtend tag field r) =
recExtendVal r
& tags . Lens.at tag ?~ field
where
recExtendVal v@(Ann _ body) =
case body of
V.BLeaf V.LRecEmpty -> Composite mempty Nothing
V.BRecExtend x -> recExtend x
_ -> Composite mempty (Just v)
|
Peaker/lamdu
|
src/Lamdu/Calc/Term/Utils.hs
|
gpl-3.0
| 1,839
| 0
| 17
| 502
| 632
| 333
| 299
| -1
| -1
|
{-
Copyright 2010 John Morrice
This source file is part of The Obelisk Programming Language and is distributed under the terms of the GNU General Public License
This file is part of The Obelisk Programming Language.
The Obelisk Programming Language is free software: you can
redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation,
either version 3 of the License, or any later version.
The Obelisk Programming Language 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 The Obelisk Programming Language.
If not, see <http://www.gnu.org/licenses/>
-}
import Prelude hiding (readFile)
import System.Environment
import Data.ByteString.Char8 hiding (putStrLn, unlines)
import System.IO hiding (readFile, hGetContents)
main = do
(cs:cf:as) <- getArgs
copy <- readFile "permission"
mapM (add_notice cs cf copy) as
add_notice comment_start comment_finish copy fp = do
putStrLn $ "Going to read " ++ fp
code <- readFile fp
src <- openFile fp WriteMode
mapM (hPut src) [pack comment_start, pack "\n\n", notice, copy, singleton '\n', pack comment_finish, pack "\n\n", code]
hClose src
notice = pack $ unlines
["Copyright 2010 John Morrice"
,""
,"This source file is part of The Obelisk Programming Language and is distributed under the terms of the GNU General Public License"
,""]
|
elginer/Obelisk
|
license_labeller.hs
|
gpl-3.0
| 1,697
| 0
| 10
| 352
| 226
| 117
| 109
| 19
| 1
|
module Turn (
Visibility (..)
,Turn
,never
,firstTurn
,nextTurn)
where
data Turn = Turn Integer | Never deriving (Eq, Ord)
newtype Visibility = Visibility { seenOn :: Turn }
instance Show Turn where
show Never = "Never"
show (Turn t) = "Turn " ++ show t
firstTurn :: Turn
firstTurn = Turn 0
never :: Turn
never = Never
nextTurn :: Turn -> Turn
nextTurn Never = Never
nextTurn (Turn t) = Turn (succ t)
|
bhickey/catamad
|
src/Turn.hs
|
gpl-3.0
| 420
| 0
| 8
| 94
| 161
| 90
| 71
| 18
| 1
|
module Semantics (
step,
reduce
) where
import AST
-- |Performs a single step of reduction
step :: AST -> AST
step (SUM (NUM n1) (NUM n2)) = NUM (n1 + n2)
step (SUM (NUM n1) m) = SUM (NUM n1) (step m)
step (SUM m n) = SUM (step m) n
step (SUB (NUM n1) (NUM n2)) = NUM (n1 - n2)
step (SUB (NUM n1) m) = SUB (NUM n1) (step m)
step (SUB m n) = SUB (step m) n
step (AST.LT (NUM n1) (NUM n2)) = BOOL (n1 < n2)
step (AST.LT (NUM n1) m) = SUB (NUM n1) (step m)
step (AST.LT m n) = SUB (step m) n
step (AST.EQ (NUM n1) (NUM n2)) = BOOL (n1 == n2)
step (AST.EQ (NUM n1) m) = SUB (NUM n1) (step m)
step (AST.EQ m n) = SUB (step m) n
step (IF (BOOL b) m n) = if b then m else n
step (IF m1 m2 m3) = IF (step m1) m2 m3
step (APP (FN x m) v) = if isGround v then sub m x v else APP (FN x m) (step v)
step (APP m n) = APP (step m) n
step m = m
-- |Reduces a term to a value
reduce :: AST -> AST
reduce m = if isGround m then m else reduce . step $ m
-- |Tells whether a term is a ground value
isGround :: AST -> Bool
isGround UNIT = True
isGround (ID _) = True
isGround (NUM _) = True
isGround (BOOL _) = True
isGround (FN _ _) = True
isGround _ = False
|
marco-zanella/minilambda
|
src/Semantics.hs
|
gpl-3.0
| 1,156
| 0
| 9
| 289
| 733
| 368
| 365
| 31
| 3
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Games.Achievements.Reveal
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Sets the state of the achievement with the given ID to \`REVEALED\` for
-- the currently authenticated player.
--
-- /See:/ <https://developers.google.com/games/ Google Play Game Services Reference> for @games.achievements.reveal@.
module Network.Google.Resource.Games.Achievements.Reveal
(
-- * REST Resource
AchievementsRevealResource
-- * Creating a Request
, achievementsReveal
, AchievementsReveal
-- * Request Lenses
, arXgafv
, arUploadProtocol
, arAchievementId
, arAccessToken
, arUploadType
, arCallback
) where
import Network.Google.Games.Types
import Network.Google.Prelude
-- | A resource alias for @games.achievements.reveal@ method which the
-- 'AchievementsReveal' request conforms to.
type AchievementsRevealResource =
"games" :>
"v1" :>
"achievements" :>
Capture "achievementId" Text :>
"reveal" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Post '[JSON] AchievementRevealResponse
-- | Sets the state of the achievement with the given ID to \`REVEALED\` for
-- the currently authenticated player.
--
-- /See:/ 'achievementsReveal' smart constructor.
data AchievementsReveal =
AchievementsReveal'
{ _arXgafv :: !(Maybe Xgafv)
, _arUploadProtocol :: !(Maybe Text)
, _arAchievementId :: !Text
, _arAccessToken :: !(Maybe Text)
, _arUploadType :: !(Maybe Text)
, _arCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AchievementsReveal' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'arXgafv'
--
-- * 'arUploadProtocol'
--
-- * 'arAchievementId'
--
-- * 'arAccessToken'
--
-- * 'arUploadType'
--
-- * 'arCallback'
achievementsReveal
:: Text -- ^ 'arAchievementId'
-> AchievementsReveal
achievementsReveal pArAchievementId_ =
AchievementsReveal'
{ _arXgafv = Nothing
, _arUploadProtocol = Nothing
, _arAchievementId = pArAchievementId_
, _arAccessToken = Nothing
, _arUploadType = Nothing
, _arCallback = Nothing
}
-- | V1 error format.
arXgafv :: Lens' AchievementsReveal (Maybe Xgafv)
arXgafv = lens _arXgafv (\ s a -> s{_arXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
arUploadProtocol :: Lens' AchievementsReveal (Maybe Text)
arUploadProtocol
= lens _arUploadProtocol
(\ s a -> s{_arUploadProtocol = a})
-- | The ID of the achievement used by this method.
arAchievementId :: Lens' AchievementsReveal Text
arAchievementId
= lens _arAchievementId
(\ s a -> s{_arAchievementId = a})
-- | OAuth access token.
arAccessToken :: Lens' AchievementsReveal (Maybe Text)
arAccessToken
= lens _arAccessToken
(\ s a -> s{_arAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
arUploadType :: Lens' AchievementsReveal (Maybe Text)
arUploadType
= lens _arUploadType (\ s a -> s{_arUploadType = a})
-- | JSONP
arCallback :: Lens' AchievementsReveal (Maybe Text)
arCallback
= lens _arCallback (\ s a -> s{_arCallback = a})
instance GoogleRequest AchievementsReveal where
type Rs AchievementsReveal =
AchievementRevealResponse
type Scopes AchievementsReveal =
'["https://www.googleapis.com/auth/games"]
requestClient AchievementsReveal'{..}
= go _arAchievementId _arXgafv _arUploadProtocol
_arAccessToken
_arUploadType
_arCallback
(Just AltJSON)
gamesService
where go
= buildClient
(Proxy :: Proxy AchievementsRevealResource)
mempty
|
brendanhay/gogol
|
gogol-games/gen/Network/Google/Resource/Games/Achievements/Reveal.hs
|
mpl-2.0
| 4,818
| 0
| 18
| 1,169
| 708
| 413
| 295
| 106
| 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.Gmail.Users.Threads.Modify
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Modifies the labels applied to the thread. This applies to all messages
-- in the thread.
--
-- /See:/ <https://developers.google.com/gmail/api/ Gmail API Reference> for @gmail.users.threads.modify@.
module Network.Google.Resource.Gmail.Users.Threads.Modify
(
-- * REST Resource
UsersThreadsModifyResource
-- * Creating a Request
, usersThreadsModify
, UsersThreadsModify
-- * Request Lenses
, utmPayload
, utmUserId
, utmId
) where
import Network.Google.Gmail.Types
import Network.Google.Prelude
-- | A resource alias for @gmail.users.threads.modify@ method which the
-- 'UsersThreadsModify' request conforms to.
type UsersThreadsModifyResource =
"gmail" :>
"v1" :>
"users" :>
Capture "userId" Text :>
"threads" :>
Capture "id" Text :>
"modify" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] ModifyThreadRequest :>
Post '[JSON] Thread
-- | Modifies the labels applied to the thread. This applies to all messages
-- in the thread.
--
-- /See:/ 'usersThreadsModify' smart constructor.
data UsersThreadsModify = UsersThreadsModify'
{ _utmPayload :: !ModifyThreadRequest
, _utmUserId :: !Text
, _utmId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'UsersThreadsModify' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'utmPayload'
--
-- * 'utmUserId'
--
-- * 'utmId'
usersThreadsModify
:: ModifyThreadRequest -- ^ 'utmPayload'
-> Text -- ^ 'utmId'
-> UsersThreadsModify
usersThreadsModify pUtmPayload_ pUtmId_ =
UsersThreadsModify'
{ _utmPayload = pUtmPayload_
, _utmUserId = "me"
, _utmId = pUtmId_
}
-- | Multipart request metadata.
utmPayload :: Lens' UsersThreadsModify ModifyThreadRequest
utmPayload
= lens _utmPayload (\ s a -> s{_utmPayload = a})
-- | The user\'s email address. The special value me can be used to indicate
-- the authenticated user.
utmUserId :: Lens' UsersThreadsModify Text
utmUserId
= lens _utmUserId (\ s a -> s{_utmUserId = a})
-- | The ID of the thread to modify.
utmId :: Lens' UsersThreadsModify Text
utmId = lens _utmId (\ s a -> s{_utmId = a})
instance GoogleRequest UsersThreadsModify where
type Rs UsersThreadsModify = Thread
type Scopes UsersThreadsModify =
'["https://mail.google.com/",
"https://www.googleapis.com/auth/gmail.modify"]
requestClient UsersThreadsModify'{..}
= go _utmUserId _utmId (Just AltJSON) _utmPayload
gmailService
where go
= buildClient
(Proxy :: Proxy UsersThreadsModifyResource)
mempty
|
rueshyna/gogol
|
gogol-gmail/gen/Network/Google/Resource/Gmail/Users/Threads/Modify.hs
|
mpl-2.0
| 3,657
| 0
| 16
| 900
| 465
| 279
| 186
| 73
| 1
|
module System.Delta.Base where
import System.IO.Error
import System.FilePath
import System.Directory
import Data.Time.Clock.POSIX
newtype FileInfo = FileInfo (FilePath,Integer,Bool)
deriving (Ord,Eq,Show)
fileInfoPath :: FileInfo -> FilePath
fileInfoPath (FileInfo (path,_,_)) = path
-- | File modification time in milliseconds
fileInfoTimestamp :: FileInfo -> Integer
fileInfoTimestamp (FileInfo (_,time,_)) = time
-- | Is the file a directory
fileInfoIsDir :: FileInfo -> Bool
fileInfoIsDir (FileInfo (_,_,dir)) = dir
mkFileInfo :: FilePath -> IO (FileInfo)
mkFileInfo path = do
isDir <- doesDirectoryExist path
isFile <- doesFileExist path
modTime <- getModificationTime path
let timeMillis = 1000 * (floor $ utcTimeToPOSIXSeconds modTime)
return $ FileInfo (path, timeMillis, isDir)
|
kryoxide/delta
|
src/main/delta/System/Delta/Base.hs
|
lgpl-3.0
| 822
| 0
| 13
| 134
| 255
| 140
| 115
| 20
| 1
|
module Main where
import System.Environment
import System.IO
import PLexceptGOTOdotNET
main = do
args <- getArgs
case args of
["parse", fileName] ->
workOnFile pa fileName
["labelloops", fileName] ->
workOnFile loopLabel fileName
["interpret", fileName] ->
workOnFile run fileName
["translate", fileName] ->
workOnFile compile fileName
_ ->
putStrLn "usage: PLexceptGOTOdotNET (parse|labelloops|interpret|translate) filename.pl-g"
workOnFile fn fileName = do
handle <- openFile fileName ReadMode
-- hSetEncoding handle utf8
contents <- hGetContents handle
outputText <- return $ fn contents
putStrLn outputText
|
catseye/PL-GOTO.NET
|
src/Main.hs
|
unlicense
| 742
| 0
| 10
| 206
| 166
| 83
| 83
| 22
| 5
|
{-# LANGUAGE BangPatterns #-}
module Kernel.CPU.FFT where
import Data.IORef
import Foreign.C
import Foreign.Ptr
import Data
import Vector
data FftPlanOpaque
type FftPlan = Ptr FftPlanOpaque
foreign import ccall unsafe fftInitThreading :: IO ()
foreign import ccall "fft_inplace_even" fftInplaceEven ::
FftPlan
-> CInt -- Sign: -1 direct C2C, 0 - R2C, +1 inverse C2C, +2 C2R
-> Ptr () -- Data ptr
-> CInt -- Size. Should be even!
-> CInt -- Pitch.
-> IO FftPlan
foreign import ccall "fftw_destroy_plan" fftDestroyPlan :: FftPlan -> IO ()
data DftPlans = DftPlans
{ dftPlan :: FftPlan
, dftIPlan :: FftPlan
}
dftPrepare :: IORef DftPlans -> GridPar -> IO ()
dftPrepare plans _gridp = writeIORef plans (DftPlans nullPtr nullPtr)
dftClean :: IORef DftPlans -> IO ()
dftClean plans = do
DftPlans plan iplan <- readIORef plans
fftDestroyPlan plan
fftDestroyPlan iplan
writeIORef plans (DftPlans nullPtr nullPtr)
type Proj = DftPlans -> FftPlan
type Inj = DftPlans -> FftPlan -> DftPlans
dftGeneral :: CInt -> Proj -> Inj -> IORef DftPlans -> GridPar -> Ptr () -> IO ()
dftGeneral sign prj inj plans gp datap = do
plns <- readIORef plans
plan' <- fftInplaceEven (prj plns) sign datap (fi height) (fi pitch)
writeIORef plans (inj plns plan')
where
fi = fromIntegral
height = gridHeight gp
pitch = gridPitch gp
fromVec :: Vector a -> Ptr ()
fromVec (CVector _ p) = castPtr p
fromVec _ = error "Wrong CPU FFT vector location."
dftKernel :: IORef DftPlans -> Image -> IO UVGrid
dftKernel pref (Image par pad d) = do
dftGeneral 0 dftPlan (\plns p -> plns {dftPlan = p}) pref par (fromVec d)
return (UVGrid par pad $ castVector d)
dftIKernel :: IORef DftPlans -> UVGrid -> IO Image
dftIKernel pref (UVGrid par pad d) = do
dftGeneral 2 dftIPlan (\plns p -> plns {dftIPlan = p}) pref par (fromVec d)
return (Image par pad $ castVector d)
|
SKA-ScienceDataProcessor/RC
|
MS4/dna-programs/Kernel/CPU/FFT.hs
|
apache-2.0
| 1,909
| 0
| 12
| 399
| 672
| 336
| 336
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.Map as M
import qualified Text.Show.Pretty as Pretty
import System.Environment(getArgs)
import Data.Maybe (mapMaybe)
import System.FilePath (splitExtension)
import Prelude
import Pcc
import Lst
import Fs
type PCCMap = M.Map String [String]
data Ruleset = Ruleset { config :: PCCMap
, links :: [Ruleset]} deriving Show
constructPCCMap :: PCCTags -> PCCMap
constructPCCMap pccTags =
M.fromListWith (++) tags where
tags = mapMaybe dataTags pccTags
dataTags (PCCDataTag x y) = Just (x, [y])
dataTags _ = Nothing
constructPCCLinks :: PCCTags -> IO [PCCTags]
constructPCCLinks pccTags =
mapM (>>= parsePCC) tags where
tags = mapMaybe linkTags pccTags
linkTags (PCCBodyTag l) = Just (getFullPath $ filename l)
linkTags _ = Nothing
constructPCC :: PCCTags -> IO Ruleset
constructPCC result = do
let pccConfig = constructPCCMap result
pccLinks <- constructPCCLinks result
rulesets <- mapM constructPCC pccLinks
return Ruleset { config = pccConfig
, links = rulesets }
-- testing, for now just print out what we have
main :: IO ()
main = do
args <- getArgs
inputFilename <- getFullPath $ head args
case snd $ splitExtension inputFilename of
d | d == ".lst" -> do
results <- parseLSTToString (args !! 1) inputFilename
putStrLn results
d | d == ".pcc" -> do
firstPcc <- parsePCC inputFilename
results <- constructPCC firstPcc
putStrLn $ Pretty.ppShow results
_ ->
error "Error: no valid filename supplied"
|
gamelost/pcgen-rules
|
src/Pcgen.hs
|
apache-2.0
| 1,609
| 0
| 16
| 364
| 483
| 249
| 234
| 47
| 3
|
{-# LANGUAGE TypeSynonymInstances #-}
module Model where
import Prelude
import Yesod
import Yesod.Auth.HashDB hiding (User, UserGeneric(..), UniqueUser)
import Data.Text (Text)
import Database.Persist.Quasi
import Database.Persist.MongoDB
import Language.Haskell.TH.Syntax
import GitUtils (UserName)
-- You can define all of your database entities in the entities file.
-- You can find more information on persistent and how to declare entities
-- at:
-- http://www.yesodweb.com/book/persistent/
share [mkPersist MkPersistSettings { mpsBackend = ConT ''Action }, mkMigrate "migrateAll"]
$(persistFileWith lowerCaseSettings "config/models")
instance HashDBUser User where
userPasswordHash = Just . userPassword
userPasswordSalt = userSalt
setSaltAndPasswordHash s h u = u { userSalt = Just s
, userPassword = h
}
|
konn/gitolist
|
Model.hs
|
bsd-2-clause
| 895
| 0
| 11
| 184
| 167
| 99
| 68
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DeriveDataTypeable #-}
-----------------------------------------------------------------------------
-- |
-- Module : HEP.Parser.LHE.Conduit
-- Copyright : (c) 2010-2014 Ian-Woo Kim
--
-- License : GPL-3
-- Maintainer : Ian-Woo Kim <ianwookim@gmail.com>
-- Stability : experimental
-- Portability : GHC
--
-- LHE parser using xml-conduit
--
-----------------------------------------------------------------------------
module HEP.Parser.LHE.Conduit where
import Control.Exception
import Control.Monad.Base (MonadBase)
import Control.Monad.Catch
import Control.Monad.IO.Class
import Control.Monad.Primitive (PrimMonad)
import Data.Conduit as C
import Data.Conduit.List as CL
import Data.Conduit.Util.Control as CU
import qualified Data.Text as T
import Data.Typeable
import Data.XML.Types
import Text.XML.Stream.Render -- (renderBuilder)
--
import HEP.Parser.LHE.Type
import HEP.Parser.LHE.Text
--
import Prelude hiding (dropWhile, takeWhile)
data ParseEventException = ParseEventException String
deriving (Show, Eq, Typeable)
instance Exception ParseEventException
-- | check event starting
isEventStart :: Event -> Bool
isEventStart (EventBeginElement name _) = nameLocalName name == "event"
isEventStart _ = False
-- | check event ending
isEventEnd :: Event -> Bool
isEventEnd (EventEndElement name) = nameLocalName name == "event"
isEventEnd _ = False
-- |
parseSingleEvent :: (MonadThrow m) => [Event] -> m LHEvent
parseSingleEvent ((EventContent content):_) =
case content of
ContentText txt -> return (getEvent txt)
_ -> throw (ParseEventException "cannot parse event")
parseSingleEvent _ = throw (ParseEventException "cannot parse event")
-- |
chunkLHEvent :: Monad m => Conduit Event m [Event]
chunkLHEvent = CU.sequence action
where action = do CU.dropWhile (not.isEventStart)
CL.drop 1
ev <- CU.takeWhileR (not.isEventEnd)
CL.drop 1
return ev
-- |
parseLHEvent :: (MonadThrow m) => Conduit [Event] m LHEvent
parseLHEvent = CL.mapM parseSingleEvent
-- |
parseEvent :: (MonadThrow m) => Conduit Event m LHEvent
parseEvent = chunkLHEvent =$= CL.filter (not.null) =$= parseLHEvent
-- |
parseLHEHeader :: (Monad m) => Conduit Event m Event
parseLHEHeader = CU.takeWhile (not.isEventStart)
-- |
textLHEHeader :: (MonadIO m, MonadThrow m, MonadBase base m, PrimMonad base) => Sink Event m [T.Text]
textLHEHeader = parseLHEHeader =$ renderText def =$ CL.consume
-- because xml-conduit is not compatible with very
|
wavewave/LHEParser
|
src/HEP/Parser/LHE/Conduit.hs
|
bsd-2-clause
| 2,839
| 0
| 12
| 614
| 630
| 354
| 276
| 50
| 2
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QCalendarWidget.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.QCalendarWidget (
QqCalendarWidget(..)
,dateEditAcceptDelay
,dateTextFormat
,firstDayOfWeek
,headerTextFormat
,horizontalHeaderFormat
,isDateEditEnabled
,isGridVisible
,isHeaderVisible
,isNavigationBarVisible
,monthShown
,QpaintCell(..), QqpaintCell(..)
,selectedDate
,setCurrentPage
,setDateEditAcceptDelay
,setDateEditEnabled
,setDateTextFormat
,setFirstDayOfWeek
,setGridVisible
,setHeaderTextFormat
,setHeaderVisible
,setHorizontalHeaderFormat
,setNavigationBarVisible
,setSelectedDate
,setVerticalHeaderFormat
,setWeekdayTextFormat
,showNextMonth
,showNextYear
,showPreviousMonth
,showPreviousYear
,showSelectedDate
,showToday
,verticalHeaderFormat
,weekdayTextFormat
,yearShown
,qCalendarWidget_delete
,qCalendarWidget_deleteLater
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Enums.Gui.QCalendarWidget
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
instance QuserMethod (QCalendarWidget ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QCalendarWidget_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QCalendarWidget_userMethod" qtc_QCalendarWidget_userMethod :: Ptr (TQCalendarWidget a) -> CInt -> IO ()
instance QuserMethod (QCalendarWidgetSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QCalendarWidget_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QCalendarWidget ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QCalendarWidget_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QCalendarWidget_userMethodVariant" qtc_QCalendarWidget_userMethodVariant :: Ptr (TQCalendarWidget a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QCalendarWidgetSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QCalendarWidget_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
class QqCalendarWidget x1 where
qCalendarWidget :: x1 -> IO (QCalendarWidget ())
instance QqCalendarWidget (()) where
qCalendarWidget ()
= withQCalendarWidgetResult $
qtc_QCalendarWidget
foreign import ccall "qtc_QCalendarWidget" qtc_QCalendarWidget :: IO (Ptr (TQCalendarWidget ()))
instance QqCalendarWidget ((QWidget t1)) where
qCalendarWidget (x1)
= withQCalendarWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget1 cobj_x1
foreign import ccall "qtc_QCalendarWidget1" qtc_QCalendarWidget1 :: Ptr (TQWidget t1) -> IO (Ptr (TQCalendarWidget ()))
dateEditAcceptDelay :: QCalendarWidget a -> (()) -> IO (Int)
dateEditAcceptDelay x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_dateEditAcceptDelay cobj_x0
foreign import ccall "qtc_QCalendarWidget_dateEditAcceptDelay" qtc_QCalendarWidget_dateEditAcceptDelay :: Ptr (TQCalendarWidget a) -> IO CInt
dateTextFormat :: QCalendarWidget a -> ((QDate t1)) -> IO (QTextCharFormat ())
dateTextFormat x0 (x1)
= withQTextCharFormatResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_dateTextFormat cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_dateTextFormat" qtc_QCalendarWidget_dateTextFormat :: Ptr (TQCalendarWidget a) -> Ptr (TQDate t1) -> IO (Ptr (TQTextCharFormat ()))
instance Qevent (QCalendarWidget ()) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_event_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_event_h" qtc_QCalendarWidget_event_h :: Ptr (TQCalendarWidget a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent (QCalendarWidgetSc a) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_event_h cobj_x0 cobj_x1
firstDayOfWeek :: QCalendarWidget a -> (()) -> IO (DayOfWeek)
firstDayOfWeek x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_firstDayOfWeek cobj_x0
foreign import ccall "qtc_QCalendarWidget_firstDayOfWeek" qtc_QCalendarWidget_firstDayOfWeek :: Ptr (TQCalendarWidget a) -> IO CLong
headerTextFormat :: QCalendarWidget a -> (()) -> IO (QTextCharFormat ())
headerTextFormat x0 ()
= withQTextCharFormatResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_headerTextFormat cobj_x0
foreign import ccall "qtc_QCalendarWidget_headerTextFormat" qtc_QCalendarWidget_headerTextFormat :: Ptr (TQCalendarWidget a) -> IO (Ptr (TQTextCharFormat ()))
horizontalHeaderFormat :: QCalendarWidget a -> (()) -> IO (HorizontalHeaderFormat)
horizontalHeaderFormat x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_horizontalHeaderFormat cobj_x0
foreign import ccall "qtc_QCalendarWidget_horizontalHeaderFormat" qtc_QCalendarWidget_horizontalHeaderFormat :: Ptr (TQCalendarWidget a) -> IO CLong
isDateEditEnabled :: QCalendarWidget a -> (()) -> IO (Bool)
isDateEditEnabled x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_isDateEditEnabled cobj_x0
foreign import ccall "qtc_QCalendarWidget_isDateEditEnabled" qtc_QCalendarWidget_isDateEditEnabled :: Ptr (TQCalendarWidget a) -> IO CBool
isGridVisible :: QCalendarWidget a -> (()) -> IO (Bool)
isGridVisible x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_isGridVisible cobj_x0
foreign import ccall "qtc_QCalendarWidget_isGridVisible" qtc_QCalendarWidget_isGridVisible :: Ptr (TQCalendarWidget a) -> IO CBool
isHeaderVisible :: QCalendarWidget a -> (()) -> IO (Bool)
isHeaderVisible x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_isHeaderVisible cobj_x0
foreign import ccall "qtc_QCalendarWidget_isHeaderVisible" qtc_QCalendarWidget_isHeaderVisible :: Ptr (TQCalendarWidget a) -> IO CBool
isNavigationBarVisible :: QCalendarWidget a -> (()) -> IO (Bool)
isNavigationBarVisible x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_isNavigationBarVisible cobj_x0
foreign import ccall "qtc_QCalendarWidget_isNavigationBarVisible" qtc_QCalendarWidget_isNavigationBarVisible :: Ptr (TQCalendarWidget a) -> IO CBool
instance QkeyPressEvent (QCalendarWidget ()) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_keyPressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_keyPressEvent_h" qtc_QCalendarWidget_keyPressEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent (QCalendarWidgetSc a) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_keyPressEvent_h cobj_x0 cobj_x1
instance QmaximumDate (QCalendarWidget a) (()) where
maximumDate x0 ()
= withQDateResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_maximumDate cobj_x0
foreign import ccall "qtc_QCalendarWidget_maximumDate" qtc_QCalendarWidget_maximumDate :: Ptr (TQCalendarWidget a) -> IO (Ptr (TQDate ()))
instance QminimumDate (QCalendarWidget a) (()) where
minimumDate x0 ()
= withQDateResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_minimumDate cobj_x0
foreign import ccall "qtc_QCalendarWidget_minimumDate" qtc_QCalendarWidget_minimumDate :: Ptr (TQCalendarWidget a) -> IO (Ptr (TQDate ()))
instance QqminimumSizeHint (QCalendarWidget ()) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_minimumSizeHint_h cobj_x0
foreign import ccall "qtc_QCalendarWidget_minimumSizeHint_h" qtc_QCalendarWidget_minimumSizeHint_h :: Ptr (TQCalendarWidget a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint (QCalendarWidgetSc a) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_minimumSizeHint_h cobj_x0
instance QminimumSizeHint (QCalendarWidget ()) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QCalendarWidget_minimumSizeHint_qth_h" qtc_QCalendarWidget_minimumSizeHint_qth_h :: Ptr (TQCalendarWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint (QCalendarWidgetSc a) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
monthShown :: QCalendarWidget a -> (()) -> IO (Int)
monthShown x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_monthShown cobj_x0
foreign import ccall "qtc_QCalendarWidget_monthShown" qtc_QCalendarWidget_monthShown :: Ptr (TQCalendarWidget a) -> IO CInt
instance QmousePressEvent (QCalendarWidget ()) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_mousePressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_mousePressEvent_h" qtc_QCalendarWidget_mousePressEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent (QCalendarWidgetSc a) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_mousePressEvent_h cobj_x0 cobj_x1
class QpaintCell x0 x1 where
paintCell :: x0 -> x1 -> IO ()
class QqpaintCell x0 x1 where
qpaintCell :: x0 -> x1 -> IO ()
instance QqpaintCell (QCalendarWidget ()) ((QPainter t1, QRect t2, QDate t3)) where
qpaintCell x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QCalendarWidget_paintCell_h cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QCalendarWidget_paintCell_h" qtc_QCalendarWidget_paintCell_h :: Ptr (TQCalendarWidget a) -> Ptr (TQPainter t1) -> Ptr (TQRect t2) -> Ptr (TQDate t3) -> IO ()
instance QqpaintCell (QCalendarWidgetSc a) ((QPainter t1, QRect t2, QDate t3)) where
qpaintCell x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QCalendarWidget_paintCell_h cobj_x0 cobj_x1 cobj_x2 cobj_x3
instance QpaintCell (QCalendarWidget ()) ((QPainter t1, Rect, QDate t3)) where
paintCell x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCRect x2 $ \crect_x2_x crect_x2_y crect_x2_w crect_x2_h ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QCalendarWidget_paintCell_qth_h cobj_x0 cobj_x1 crect_x2_x crect_x2_y crect_x2_w crect_x2_h cobj_x3
foreign import ccall "qtc_QCalendarWidget_paintCell_qth_h" qtc_QCalendarWidget_paintCell_qth_h :: Ptr (TQCalendarWidget a) -> Ptr (TQPainter t1) -> CInt -> CInt -> CInt -> CInt -> Ptr (TQDate t3) -> IO ()
instance QpaintCell (QCalendarWidgetSc a) ((QPainter t1, Rect, QDate t3)) where
paintCell x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCRect x2 $ \crect_x2_x crect_x2_y crect_x2_w crect_x2_h ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QCalendarWidget_paintCell_qth_h cobj_x0 cobj_x1 crect_x2_x crect_x2_y crect_x2_w crect_x2_h cobj_x3
instance QresizeEvent (QCalendarWidget ()) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_resizeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_resizeEvent_h" qtc_QCalendarWidget_resizeEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent (QCalendarWidgetSc a) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_resizeEvent_h cobj_x0 cobj_x1
selectedDate :: QCalendarWidget a -> (()) -> IO (QDate ())
selectedDate x0 ()
= withQDateResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_selectedDate cobj_x0
foreign import ccall "qtc_QCalendarWidget_selectedDate" qtc_QCalendarWidget_selectedDate :: Ptr (TQCalendarWidget a) -> IO (Ptr (TQDate ()))
instance QselectionMode (QCalendarWidget a) (()) (IO (QCalendarWidgetSelectionMode)) where
selectionMode x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_selectionMode cobj_x0
foreign import ccall "qtc_QCalendarWidget_selectionMode" qtc_QCalendarWidget_selectionMode :: Ptr (TQCalendarWidget a) -> IO CLong
setCurrentPage :: QCalendarWidget a -> ((Int, Int)) -> IO ()
setCurrentPage x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_setCurrentPage cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QCalendarWidget_setCurrentPage" qtc_QCalendarWidget_setCurrentPage :: Ptr (TQCalendarWidget a) -> CInt -> CInt -> IO ()
setDateEditAcceptDelay :: QCalendarWidget a -> ((Int)) -> IO ()
setDateEditAcceptDelay x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_setDateEditAcceptDelay cobj_x0 (toCInt x1)
foreign import ccall "qtc_QCalendarWidget_setDateEditAcceptDelay" qtc_QCalendarWidget_setDateEditAcceptDelay :: Ptr (TQCalendarWidget a) -> CInt -> IO ()
setDateEditEnabled :: QCalendarWidget a -> ((Bool)) -> IO ()
setDateEditEnabled x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_setDateEditEnabled cobj_x0 (toCBool x1)
foreign import ccall "qtc_QCalendarWidget_setDateEditEnabled" qtc_QCalendarWidget_setDateEditEnabled :: Ptr (TQCalendarWidget a) -> CBool -> IO ()
instance QsetDateRange (QCalendarWidget a) ((QDate t1, QDate t2)) where
setDateRange x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QCalendarWidget_setDateRange cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QCalendarWidget_setDateRange" qtc_QCalendarWidget_setDateRange :: Ptr (TQCalendarWidget a) -> Ptr (TQDate t1) -> Ptr (TQDate t2) -> IO ()
setDateTextFormat :: QCalendarWidget a -> ((QDate t1, QTextCharFormat t2)) -> IO ()
setDateTextFormat x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QCalendarWidget_setDateTextFormat cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QCalendarWidget_setDateTextFormat" qtc_QCalendarWidget_setDateTextFormat :: Ptr (TQCalendarWidget a) -> Ptr (TQDate t1) -> Ptr (TQTextCharFormat t2) -> IO ()
setFirstDayOfWeek :: QCalendarWidget a -> ((DayOfWeek)) -> IO ()
setFirstDayOfWeek x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_setFirstDayOfWeek cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QCalendarWidget_setFirstDayOfWeek" qtc_QCalendarWidget_setFirstDayOfWeek :: Ptr (TQCalendarWidget a) -> CLong -> IO ()
setGridVisible :: QCalendarWidget a -> ((Bool)) -> IO ()
setGridVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_setGridVisible cobj_x0 (toCBool x1)
foreign import ccall "qtc_QCalendarWidget_setGridVisible" qtc_QCalendarWidget_setGridVisible :: Ptr (TQCalendarWidget a) -> CBool -> IO ()
setHeaderTextFormat :: QCalendarWidget a -> ((QTextCharFormat t1)) -> IO ()
setHeaderTextFormat x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_setHeaderTextFormat cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_setHeaderTextFormat" qtc_QCalendarWidget_setHeaderTextFormat :: Ptr (TQCalendarWidget a) -> Ptr (TQTextCharFormat t1) -> IO ()
setHeaderVisible :: QCalendarWidget a -> ((Bool)) -> IO ()
setHeaderVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_setHeaderVisible cobj_x0 (toCBool x1)
foreign import ccall "qtc_QCalendarWidget_setHeaderVisible" qtc_QCalendarWidget_setHeaderVisible :: Ptr (TQCalendarWidget a) -> CBool -> IO ()
setHorizontalHeaderFormat :: QCalendarWidget a -> ((HorizontalHeaderFormat)) -> IO ()
setHorizontalHeaderFormat x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_setHorizontalHeaderFormat cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QCalendarWidget_setHorizontalHeaderFormat" qtc_QCalendarWidget_setHorizontalHeaderFormat :: Ptr (TQCalendarWidget a) -> CLong -> IO ()
instance QsetMaximumDate (QCalendarWidget a) ((QDate t1)) where
setMaximumDate x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_setMaximumDate cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_setMaximumDate" qtc_QCalendarWidget_setMaximumDate :: Ptr (TQCalendarWidget a) -> Ptr (TQDate t1) -> IO ()
instance QsetMinimumDate (QCalendarWidget a) ((QDate t1)) where
setMinimumDate x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_setMinimumDate cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_setMinimumDate" qtc_QCalendarWidget_setMinimumDate :: Ptr (TQCalendarWidget a) -> Ptr (TQDate t1) -> IO ()
setNavigationBarVisible :: QCalendarWidget a -> ((Bool)) -> IO ()
setNavigationBarVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_setNavigationBarVisible cobj_x0 (toCBool x1)
foreign import ccall "qtc_QCalendarWidget_setNavigationBarVisible" qtc_QCalendarWidget_setNavigationBarVisible :: Ptr (TQCalendarWidget a) -> CBool -> IO ()
setSelectedDate :: QCalendarWidget a -> ((QDate t1)) -> IO ()
setSelectedDate x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_setSelectedDate cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_setSelectedDate" qtc_QCalendarWidget_setSelectedDate :: Ptr (TQCalendarWidget a) -> Ptr (TQDate t1) -> IO ()
instance QsetSelectionMode (QCalendarWidget a) ((QCalendarWidgetSelectionMode)) where
setSelectionMode x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_setSelectionMode cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QCalendarWidget_setSelectionMode" qtc_QCalendarWidget_setSelectionMode :: Ptr (TQCalendarWidget a) -> CLong -> IO ()
setVerticalHeaderFormat :: QCalendarWidget a -> ((VerticalHeaderFormat)) -> IO ()
setVerticalHeaderFormat x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_setVerticalHeaderFormat cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QCalendarWidget_setVerticalHeaderFormat" qtc_QCalendarWidget_setVerticalHeaderFormat :: Ptr (TQCalendarWidget a) -> CLong -> IO ()
setWeekdayTextFormat :: QCalendarWidget a -> ((DayOfWeek, QTextCharFormat t2)) -> IO ()
setWeekdayTextFormat x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QCalendarWidget_setWeekdayTextFormat cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
foreign import ccall "qtc_QCalendarWidget_setWeekdayTextFormat" qtc_QCalendarWidget_setWeekdayTextFormat :: Ptr (TQCalendarWidget a) -> CLong -> Ptr (TQTextCharFormat t2) -> IO ()
showNextMonth :: QCalendarWidget a -> (()) -> IO ()
showNextMonth x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_showNextMonth cobj_x0
foreign import ccall "qtc_QCalendarWidget_showNextMonth" qtc_QCalendarWidget_showNextMonth :: Ptr (TQCalendarWidget a) -> IO ()
showNextYear :: QCalendarWidget a -> (()) -> IO ()
showNextYear x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_showNextYear cobj_x0
foreign import ccall "qtc_QCalendarWidget_showNextYear" qtc_QCalendarWidget_showNextYear :: Ptr (TQCalendarWidget a) -> IO ()
showPreviousMonth :: QCalendarWidget a -> (()) -> IO ()
showPreviousMonth x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_showPreviousMonth cobj_x0
foreign import ccall "qtc_QCalendarWidget_showPreviousMonth" qtc_QCalendarWidget_showPreviousMonth :: Ptr (TQCalendarWidget a) -> IO ()
showPreviousYear :: QCalendarWidget a -> (()) -> IO ()
showPreviousYear x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_showPreviousYear cobj_x0
foreign import ccall "qtc_QCalendarWidget_showPreviousYear" qtc_QCalendarWidget_showPreviousYear :: Ptr (TQCalendarWidget a) -> IO ()
showSelectedDate :: QCalendarWidget a -> (()) -> IO ()
showSelectedDate x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_showSelectedDate cobj_x0
foreign import ccall "qtc_QCalendarWidget_showSelectedDate" qtc_QCalendarWidget_showSelectedDate :: Ptr (TQCalendarWidget a) -> IO ()
showToday :: QCalendarWidget a -> (()) -> IO ()
showToday x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_showToday cobj_x0
foreign import ccall "qtc_QCalendarWidget_showToday" qtc_QCalendarWidget_showToday :: Ptr (TQCalendarWidget a) -> IO ()
instance QqsizeHint (QCalendarWidget ()) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_sizeHint_h cobj_x0
foreign import ccall "qtc_QCalendarWidget_sizeHint_h" qtc_QCalendarWidget_sizeHint_h :: Ptr (TQCalendarWidget a) -> IO (Ptr (TQSize ()))
instance QqsizeHint (QCalendarWidgetSc a) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_sizeHint_h cobj_x0
instance QsizeHint (QCalendarWidget ()) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QCalendarWidget_sizeHint_qth_h" qtc_QCalendarWidget_sizeHint_qth_h :: Ptr (TQCalendarWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint (QCalendarWidgetSc a) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
verticalHeaderFormat :: QCalendarWidget a -> (()) -> IO (VerticalHeaderFormat)
verticalHeaderFormat x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_verticalHeaderFormat cobj_x0
foreign import ccall "qtc_QCalendarWidget_verticalHeaderFormat" qtc_QCalendarWidget_verticalHeaderFormat :: Ptr (TQCalendarWidget a) -> IO CLong
weekdayTextFormat :: QCalendarWidget a -> ((DayOfWeek)) -> IO (QTextCharFormat ())
weekdayTextFormat x0 (x1)
= withQTextCharFormatResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_weekdayTextFormat cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QCalendarWidget_weekdayTextFormat" qtc_QCalendarWidget_weekdayTextFormat :: Ptr (TQCalendarWidget a) -> CLong -> IO (Ptr (TQTextCharFormat ()))
yearShown :: QCalendarWidget a -> (()) -> IO (Int)
yearShown x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_yearShown cobj_x0
foreign import ccall "qtc_QCalendarWidget_yearShown" qtc_QCalendarWidget_yearShown :: Ptr (TQCalendarWidget a) -> IO CInt
qCalendarWidget_delete :: QCalendarWidget a -> IO ()
qCalendarWidget_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_delete cobj_x0
foreign import ccall "qtc_QCalendarWidget_delete" qtc_QCalendarWidget_delete :: Ptr (TQCalendarWidget a) -> IO ()
qCalendarWidget_deleteLater :: QCalendarWidget a -> IO ()
qCalendarWidget_deleteLater x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_deleteLater cobj_x0
foreign import ccall "qtc_QCalendarWidget_deleteLater" qtc_QCalendarWidget_deleteLater :: Ptr (TQCalendarWidget a) -> IO ()
instance QactionEvent (QCalendarWidget ()) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_actionEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_actionEvent_h" qtc_QCalendarWidget_actionEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent (QCalendarWidgetSc a) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_actionEvent_h cobj_x0 cobj_x1
instance QaddAction (QCalendarWidget ()) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_addAction cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_addAction" qtc_QCalendarWidget_addAction :: Ptr (TQCalendarWidget a) -> Ptr (TQAction t1) -> IO ()
instance QaddAction (QCalendarWidgetSc a) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_addAction cobj_x0 cobj_x1
instance QchangeEvent (QCalendarWidget ()) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_changeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_changeEvent_h" qtc_QCalendarWidget_changeEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent (QCalendarWidgetSc a) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_changeEvent_h cobj_x0 cobj_x1
instance QcloseEvent (QCalendarWidget ()) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_closeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_closeEvent_h" qtc_QCalendarWidget_closeEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent (QCalendarWidgetSc a) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_closeEvent_h cobj_x0 cobj_x1
instance QcontextMenuEvent (QCalendarWidget ()) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_contextMenuEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_contextMenuEvent_h" qtc_QCalendarWidget_contextMenuEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent (QCalendarWidgetSc a) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_contextMenuEvent_h cobj_x0 cobj_x1
instance Qcreate (QCalendarWidget ()) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_create cobj_x0
foreign import ccall "qtc_QCalendarWidget_create" qtc_QCalendarWidget_create :: Ptr (TQCalendarWidget a) -> IO ()
instance Qcreate (QCalendarWidgetSc a) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_create cobj_x0
instance Qcreate (QCalendarWidget ()) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_create1 cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_create1" qtc_QCalendarWidget_create1 :: Ptr (TQCalendarWidget a) -> Ptr (TQVoid t1) -> IO ()
instance Qcreate (QCalendarWidgetSc a) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_create1 cobj_x0 cobj_x1
instance Qcreate (QCalendarWidget ()) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_create2 cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QCalendarWidget_create2" qtc_QCalendarWidget_create2 :: Ptr (TQCalendarWidget a) -> Ptr (TQVoid t1) -> CBool -> IO ()
instance Qcreate (QCalendarWidgetSc a) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_create2 cobj_x0 cobj_x1 (toCBool x2)
instance Qcreate (QCalendarWidget ()) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
foreign import ccall "qtc_QCalendarWidget_create3" qtc_QCalendarWidget_create3 :: Ptr (TQCalendarWidget a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO ()
instance Qcreate (QCalendarWidgetSc a) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
instance Qdestroy (QCalendarWidget ()) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_destroy cobj_x0
foreign import ccall "qtc_QCalendarWidget_destroy" qtc_QCalendarWidget_destroy :: Ptr (TQCalendarWidget a) -> IO ()
instance Qdestroy (QCalendarWidgetSc a) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_destroy cobj_x0
instance Qdestroy (QCalendarWidget ()) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_destroy1 cobj_x0 (toCBool x1)
foreign import ccall "qtc_QCalendarWidget_destroy1" qtc_QCalendarWidget_destroy1 :: Ptr (TQCalendarWidget a) -> CBool -> IO ()
instance Qdestroy (QCalendarWidgetSc a) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_destroy1 cobj_x0 (toCBool x1)
instance Qdestroy (QCalendarWidget ()) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
foreign import ccall "qtc_QCalendarWidget_destroy2" qtc_QCalendarWidget_destroy2 :: Ptr (TQCalendarWidget a) -> CBool -> CBool -> IO ()
instance Qdestroy (QCalendarWidgetSc a) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
instance QdevType (QCalendarWidget ()) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_devType_h cobj_x0
foreign import ccall "qtc_QCalendarWidget_devType_h" qtc_QCalendarWidget_devType_h :: Ptr (TQCalendarWidget a) -> IO CInt
instance QdevType (QCalendarWidgetSc a) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_devType_h cobj_x0
instance QdragEnterEvent (QCalendarWidget ()) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_dragEnterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_dragEnterEvent_h" qtc_QCalendarWidget_dragEnterEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent (QCalendarWidgetSc a) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_dragEnterEvent_h cobj_x0 cobj_x1
instance QdragLeaveEvent (QCalendarWidget ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_dragLeaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_dragLeaveEvent_h" qtc_QCalendarWidget_dragLeaveEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent (QCalendarWidgetSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_dragLeaveEvent_h cobj_x0 cobj_x1
instance QdragMoveEvent (QCalendarWidget ()) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_dragMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_dragMoveEvent_h" qtc_QCalendarWidget_dragMoveEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent (QCalendarWidgetSc a) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_dragMoveEvent_h cobj_x0 cobj_x1
instance QdropEvent (QCalendarWidget ()) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_dropEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_dropEvent_h" qtc_QCalendarWidget_dropEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent (QCalendarWidgetSc a) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_dropEvent_h cobj_x0 cobj_x1
instance QenabledChange (QCalendarWidget ()) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_enabledChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QCalendarWidget_enabledChange" qtc_QCalendarWidget_enabledChange :: Ptr (TQCalendarWidget a) -> CBool -> IO ()
instance QenabledChange (QCalendarWidgetSc a) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_enabledChange cobj_x0 (toCBool x1)
instance QenterEvent (QCalendarWidget ()) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_enterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_enterEvent_h" qtc_QCalendarWidget_enterEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent (QCalendarWidgetSc a) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_enterEvent_h cobj_x0 cobj_x1
instance QfocusInEvent (QCalendarWidget ()) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_focusInEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_focusInEvent_h" qtc_QCalendarWidget_focusInEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent (QCalendarWidgetSc a) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_focusInEvent_h cobj_x0 cobj_x1
instance QfocusNextChild (QCalendarWidget ()) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_focusNextChild cobj_x0
foreign import ccall "qtc_QCalendarWidget_focusNextChild" qtc_QCalendarWidget_focusNextChild :: Ptr (TQCalendarWidget a) -> IO CBool
instance QfocusNextChild (QCalendarWidgetSc a) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_focusNextChild cobj_x0
instance QfocusNextPrevChild (QCalendarWidget ()) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_focusNextPrevChild cobj_x0 (toCBool x1)
foreign import ccall "qtc_QCalendarWidget_focusNextPrevChild" qtc_QCalendarWidget_focusNextPrevChild :: Ptr (TQCalendarWidget a) -> CBool -> IO CBool
instance QfocusNextPrevChild (QCalendarWidgetSc a) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_focusNextPrevChild cobj_x0 (toCBool x1)
instance QfocusOutEvent (QCalendarWidget ()) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_focusOutEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_focusOutEvent_h" qtc_QCalendarWidget_focusOutEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent (QCalendarWidgetSc a) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_focusOutEvent_h cobj_x0 cobj_x1
instance QfocusPreviousChild (QCalendarWidget ()) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_focusPreviousChild cobj_x0
foreign import ccall "qtc_QCalendarWidget_focusPreviousChild" qtc_QCalendarWidget_focusPreviousChild :: Ptr (TQCalendarWidget a) -> IO CBool
instance QfocusPreviousChild (QCalendarWidgetSc a) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_focusPreviousChild cobj_x0
instance QfontChange (QCalendarWidget ()) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_fontChange cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_fontChange" qtc_QCalendarWidget_fontChange :: Ptr (TQCalendarWidget a) -> Ptr (TQFont t1) -> IO ()
instance QfontChange (QCalendarWidgetSc a) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_fontChange cobj_x0 cobj_x1
instance QheightForWidth (QCalendarWidget ()) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_heightForWidth_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QCalendarWidget_heightForWidth_h" qtc_QCalendarWidget_heightForWidth_h :: Ptr (TQCalendarWidget a) -> CInt -> IO CInt
instance QheightForWidth (QCalendarWidgetSc a) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_heightForWidth_h cobj_x0 (toCInt x1)
instance QhideEvent (QCalendarWidget ()) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_hideEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_hideEvent_h" qtc_QCalendarWidget_hideEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent (QCalendarWidgetSc a) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_hideEvent_h cobj_x0 cobj_x1
instance QinputMethodEvent (QCalendarWidget ()) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_inputMethodEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_inputMethodEvent" qtc_QCalendarWidget_inputMethodEvent :: Ptr (TQCalendarWidget a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent (QCalendarWidgetSc a) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_inputMethodEvent cobj_x0 cobj_x1
instance QinputMethodQuery (QCalendarWidget ()) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QCalendarWidget_inputMethodQuery_h" qtc_QCalendarWidget_inputMethodQuery_h :: Ptr (TQCalendarWidget a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery (QCalendarWidgetSc a) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
instance QkeyReleaseEvent (QCalendarWidget ()) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_keyReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_keyReleaseEvent_h" qtc_QCalendarWidget_keyReleaseEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent (QCalendarWidgetSc a) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_keyReleaseEvent_h cobj_x0 cobj_x1
instance QlanguageChange (QCalendarWidget ()) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_languageChange cobj_x0
foreign import ccall "qtc_QCalendarWidget_languageChange" qtc_QCalendarWidget_languageChange :: Ptr (TQCalendarWidget a) -> IO ()
instance QlanguageChange (QCalendarWidgetSc a) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_languageChange cobj_x0
instance QleaveEvent (QCalendarWidget ()) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_leaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_leaveEvent_h" qtc_QCalendarWidget_leaveEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent (QCalendarWidgetSc a) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_leaveEvent_h cobj_x0 cobj_x1
instance Qmetric (QCalendarWidget ()) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_metric cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QCalendarWidget_metric" qtc_QCalendarWidget_metric :: Ptr (TQCalendarWidget a) -> CLong -> IO CInt
instance Qmetric (QCalendarWidgetSc a) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_metric cobj_x0 (toCLong $ qEnum_toInt x1)
instance QmouseDoubleClickEvent (QCalendarWidget ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_mouseDoubleClickEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_mouseDoubleClickEvent_h" qtc_QCalendarWidget_mouseDoubleClickEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent (QCalendarWidgetSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_mouseDoubleClickEvent_h cobj_x0 cobj_x1
instance QmouseMoveEvent (QCalendarWidget ()) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_mouseMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_mouseMoveEvent_h" qtc_QCalendarWidget_mouseMoveEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent (QCalendarWidgetSc a) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_mouseMoveEvent_h cobj_x0 cobj_x1
instance QmouseReleaseEvent (QCalendarWidget ()) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_mouseReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_mouseReleaseEvent_h" qtc_QCalendarWidget_mouseReleaseEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent (QCalendarWidgetSc a) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_mouseReleaseEvent_h cobj_x0 cobj_x1
instance Qmove (QCalendarWidget ()) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_move1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QCalendarWidget_move1" qtc_QCalendarWidget_move1 :: Ptr (TQCalendarWidget a) -> CInt -> CInt -> IO ()
instance Qmove (QCalendarWidgetSc a) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_move1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qmove (QCalendarWidget ()) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QCalendarWidget_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QCalendarWidget_move_qth" qtc_QCalendarWidget_move_qth :: Ptr (TQCalendarWidget a) -> CInt -> CInt -> IO ()
instance Qmove (QCalendarWidgetSc a) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QCalendarWidget_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
instance Qqmove (QCalendarWidget ()) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_move cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_move" qtc_QCalendarWidget_move :: Ptr (TQCalendarWidget a) -> Ptr (TQPoint t1) -> IO ()
instance Qqmove (QCalendarWidgetSc a) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_move cobj_x0 cobj_x1
instance QmoveEvent (QCalendarWidget ()) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_moveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_moveEvent_h" qtc_QCalendarWidget_moveEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent (QCalendarWidgetSc a) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_moveEvent_h cobj_x0 cobj_x1
instance QpaintEngine (QCalendarWidget ()) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_paintEngine_h cobj_x0
foreign import ccall "qtc_QCalendarWidget_paintEngine_h" qtc_QCalendarWidget_paintEngine_h :: Ptr (TQCalendarWidget a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine (QCalendarWidgetSc a) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_paintEngine_h cobj_x0
instance QpaintEvent (QCalendarWidget ()) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_paintEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_paintEvent_h" qtc_QCalendarWidget_paintEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent (QCalendarWidgetSc a) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_paintEvent_h cobj_x0 cobj_x1
instance QpaletteChange (QCalendarWidget ()) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_paletteChange cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_paletteChange" qtc_QCalendarWidget_paletteChange :: Ptr (TQCalendarWidget a) -> Ptr (TQPalette t1) -> IO ()
instance QpaletteChange (QCalendarWidgetSc a) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_paletteChange cobj_x0 cobj_x1
instance Qrepaint (QCalendarWidget ()) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_repaint cobj_x0
foreign import ccall "qtc_QCalendarWidget_repaint" qtc_QCalendarWidget_repaint :: Ptr (TQCalendarWidget a) -> IO ()
instance Qrepaint (QCalendarWidgetSc a) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_repaint cobj_x0
instance Qrepaint (QCalendarWidget ()) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QCalendarWidget_repaint2" qtc_QCalendarWidget_repaint2 :: Ptr (TQCalendarWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance Qrepaint (QCalendarWidgetSc a) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance Qrepaint (QCalendarWidget ()) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_repaint1 cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_repaint1" qtc_QCalendarWidget_repaint1 :: Ptr (TQCalendarWidget a) -> Ptr (TQRegion t1) -> IO ()
instance Qrepaint (QCalendarWidgetSc a) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_repaint1 cobj_x0 cobj_x1
instance QresetInputContext (QCalendarWidget ()) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_resetInputContext cobj_x0
foreign import ccall "qtc_QCalendarWidget_resetInputContext" qtc_QCalendarWidget_resetInputContext :: Ptr (TQCalendarWidget a) -> IO ()
instance QresetInputContext (QCalendarWidgetSc a) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_resetInputContext cobj_x0
instance Qresize (QCalendarWidget ()) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_resize1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QCalendarWidget_resize1" qtc_QCalendarWidget_resize1 :: Ptr (TQCalendarWidget a) -> CInt -> CInt -> IO ()
instance Qresize (QCalendarWidgetSc a) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_resize1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qqresize (QCalendarWidget ()) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_resize cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_resize" qtc_QCalendarWidget_resize :: Ptr (TQCalendarWidget a) -> Ptr (TQSize t1) -> IO ()
instance Qqresize (QCalendarWidgetSc a) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_resize cobj_x0 cobj_x1
instance Qresize (QCalendarWidget ()) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QCalendarWidget_resize_qth cobj_x0 csize_x1_w csize_x1_h
foreign import ccall "qtc_QCalendarWidget_resize_qth" qtc_QCalendarWidget_resize_qth :: Ptr (TQCalendarWidget a) -> CInt -> CInt -> IO ()
instance Qresize (QCalendarWidgetSc a) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QCalendarWidget_resize_qth cobj_x0 csize_x1_w csize_x1_h
instance QsetGeometry (QCalendarWidget ()) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QCalendarWidget_setGeometry1" qtc_QCalendarWidget_setGeometry1 :: Ptr (TQCalendarWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QCalendarWidgetSc a) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance QqsetGeometry (QCalendarWidget ()) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_setGeometry cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_setGeometry" qtc_QCalendarWidget_setGeometry :: Ptr (TQCalendarWidget a) -> Ptr (TQRect t1) -> IO ()
instance QqsetGeometry (QCalendarWidgetSc a) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_setGeometry cobj_x0 cobj_x1
instance QsetGeometry (QCalendarWidget ()) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QCalendarWidget_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QCalendarWidget_setGeometry_qth" qtc_QCalendarWidget_setGeometry_qth :: Ptr (TQCalendarWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QCalendarWidgetSc a) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QCalendarWidget_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
instance QsetMouseTracking (QCalendarWidget ()) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_setMouseTracking cobj_x0 (toCBool x1)
foreign import ccall "qtc_QCalendarWidget_setMouseTracking" qtc_QCalendarWidget_setMouseTracking :: Ptr (TQCalendarWidget a) -> CBool -> IO ()
instance QsetMouseTracking (QCalendarWidgetSc a) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_setMouseTracking cobj_x0 (toCBool x1)
instance QsetVisible (QCalendarWidget ()) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_setVisible_h cobj_x0 (toCBool x1)
foreign import ccall "qtc_QCalendarWidget_setVisible_h" qtc_QCalendarWidget_setVisible_h :: Ptr (TQCalendarWidget a) -> CBool -> IO ()
instance QsetVisible (QCalendarWidgetSc a) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_setVisible_h cobj_x0 (toCBool x1)
instance QshowEvent (QCalendarWidget ()) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_showEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_showEvent_h" qtc_QCalendarWidget_showEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent (QCalendarWidgetSc a) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_showEvent_h cobj_x0 cobj_x1
instance QtabletEvent (QCalendarWidget ()) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_tabletEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_tabletEvent_h" qtc_QCalendarWidget_tabletEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent (QCalendarWidgetSc a) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_tabletEvent_h cobj_x0 cobj_x1
instance QupdateMicroFocus (QCalendarWidget ()) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_updateMicroFocus cobj_x0
foreign import ccall "qtc_QCalendarWidget_updateMicroFocus" qtc_QCalendarWidget_updateMicroFocus :: Ptr (TQCalendarWidget a) -> IO ()
instance QupdateMicroFocus (QCalendarWidgetSc a) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_updateMicroFocus cobj_x0
instance QwheelEvent (QCalendarWidget ()) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_wheelEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_wheelEvent_h" qtc_QCalendarWidget_wheelEvent_h :: Ptr (TQCalendarWidget a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent (QCalendarWidgetSc a) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_wheelEvent_h cobj_x0 cobj_x1
instance QwindowActivationChange (QCalendarWidget ()) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_windowActivationChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QCalendarWidget_windowActivationChange" qtc_QCalendarWidget_windowActivationChange :: Ptr (TQCalendarWidget a) -> CBool -> IO ()
instance QwindowActivationChange (QCalendarWidgetSc a) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_windowActivationChange cobj_x0 (toCBool x1)
instance QchildEvent (QCalendarWidget ()) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_childEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_childEvent" qtc_QCalendarWidget_childEvent :: Ptr (TQCalendarWidget a) -> Ptr (TQChildEvent t1) -> IO ()
instance QchildEvent (QCalendarWidgetSc a) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_childEvent cobj_x0 cobj_x1
instance QconnectNotify (QCalendarWidget ()) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QCalendarWidget_connectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QCalendarWidget_connectNotify" qtc_QCalendarWidget_connectNotify :: Ptr (TQCalendarWidget a) -> CWString -> IO ()
instance QconnectNotify (QCalendarWidgetSc a) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QCalendarWidget_connectNotify cobj_x0 cstr_x1
instance QcustomEvent (QCalendarWidget ()) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_customEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_customEvent" qtc_QCalendarWidget_customEvent :: Ptr (TQCalendarWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QcustomEvent (QCalendarWidgetSc a) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_customEvent cobj_x0 cobj_x1
instance QdisconnectNotify (QCalendarWidget ()) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QCalendarWidget_disconnectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QCalendarWidget_disconnectNotify" qtc_QCalendarWidget_disconnectNotify :: Ptr (TQCalendarWidget a) -> CWString -> IO ()
instance QdisconnectNotify (QCalendarWidgetSc a) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QCalendarWidget_disconnectNotify cobj_x0 cstr_x1
instance QeventFilter (QCalendarWidget ()) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QCalendarWidget_eventFilter_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QCalendarWidget_eventFilter_h" qtc_QCalendarWidget_eventFilter_h :: Ptr (TQCalendarWidget a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter (QCalendarWidgetSc a) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QCalendarWidget_eventFilter_h cobj_x0 cobj_x1 cobj_x2
instance Qreceivers (QCalendarWidget ()) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QCalendarWidget_receivers cobj_x0 cstr_x1
foreign import ccall "qtc_QCalendarWidget_receivers" qtc_QCalendarWidget_receivers :: Ptr (TQCalendarWidget a) -> CWString -> IO CInt
instance Qreceivers (QCalendarWidgetSc a) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QCalendarWidget_receivers cobj_x0 cstr_x1
instance Qsender (QCalendarWidget ()) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_sender cobj_x0
foreign import ccall "qtc_QCalendarWidget_sender" qtc_QCalendarWidget_sender :: Ptr (TQCalendarWidget a) -> IO (Ptr (TQObject ()))
instance Qsender (QCalendarWidgetSc a) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QCalendarWidget_sender cobj_x0
instance QtimerEvent (QCalendarWidget ()) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_timerEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QCalendarWidget_timerEvent" qtc_QCalendarWidget_timerEvent :: Ptr (TQCalendarWidget a) -> Ptr (TQTimerEvent t1) -> IO ()
instance QtimerEvent (QCalendarWidgetSc a) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QCalendarWidget_timerEvent cobj_x0 cobj_x1
|
uduki/hsQt
|
Qtc/Gui/QCalendarWidget.hs
|
bsd-2-clause
| 62,422
| 0
| 15
| 9,385
| 18,884
| 9,569
| 9,315
| -1
| -1
|
newtype NondetT m a = NondetT { runNondetT :: m [a] }
|
davdar/quals
|
writeup-old/sections/04MonadicAAM/04Optimizations/00Widen/04NondetT.hs
|
bsd-3-clause
| 54
| 0
| 8
| 12
| 22
| 14
| 8
| 1
| 0
|
module Helix where
import Rumpus
start :: Start
start = do
spawnChildren [0..100] $ \i -> do
myShape ==> Cube
mySize ==> V3 0.5 0.02 0.02
myPose ==> positionRotation (V3 0 (0.5+i*0.1) 0)
(axisAngle (V3 0 1 0) (i*0.2))
myColor ==> colorHSL (i*0.2) 0.5 0.7
return ()
|
lukexi/rumpus
|
pristine/Intro/Helix.hs
|
bsd-3-clause
| 328
| 0
| 17
| 110
| 145
| 72
| 73
| 11
| 1
|
-- ------------------------------------------------------------
{- |
Module : Yuuko.Text.XML.HXT.Arrow.Edit
Copyright : Copyright (C) 2006-9 Uwe Schmidt
License : MIT
Maintainer : Uwe Schmidt (uwe@fh-wedel.de)
Stability : stable
Portability: portable
common edit arrows
-}
-- ------------------------------------------------------------
module Yuuko.Text.XML.HXT.Arrow.Edit
( canonicalizeAllNodes
, canonicalizeForXPath
, canonicalizeContents
, collapseAllXText
, collapseXText
, xshowEscapeXml
, escapeXmlDoc
, escapeHtmlDoc
, haskellRepOfXmlDoc
, treeRepOfXmlDoc
, addHeadlineToXmlDoc
, indentDoc
, numberLinesInXmlDoc
, preventEmptyElements
, removeComment
, removeAllComment
, removeWhiteSpace
, removeAllWhiteSpace
, removeDocWhiteSpace
, transfCdata
, transfAllCdata
, transfCharRef
, transfAllCharRef
, rememberDTDAttrl
, addDefaultDTDecl
, hasXmlPi
, addXmlPi
, addXmlPiEncoding
, addDoctypeDecl
, addXHtmlDoctypeStrict
, addXHtmlDoctypeTransitional
, addXHtmlDoctypeFrameset
)
where
import Control.Arrow
import Yuuko.Control.Arrow.ArrowList
import Yuuko.Control.Arrow.ArrowIf
import Yuuko.Control.Arrow.ArrowTree
import Yuuko.Control.Arrow.ListArrow
import Yuuko.Text.XML.HXT.Arrow.XmlArrow
import Yuuko.Text.XML.HXT.DOM.Interface
import qualified Yuuko.Text.XML.HXT.DOM.XmlNode as XN
import Yuuko.Text.XML.HXT.DOM.Unicode ( isXmlSpaceChar )
import Yuuko.Text.XML.HXT.DOM.FormatXmlTree ( formatXmlTree )
import Yuuko.Text.XML.HXT.Parser.HtmlParsec ( emptyHtmlTags )
import Yuuko.Text.XML.HXT.Parser.XmlEntities ( xmlEntities )
import Yuuko.Text.XML.HXT.Parser.XhtmlEntities ( xhtmlEntities )
import Data.List ( isPrefixOf )
import qualified Data.Map as M
import Data.Maybe
-- ------------------------------------------------------------
-- |
-- Applies some "Canonical XML" rules to a document tree.
--
-- The rule differ slightly for canonical XML and XPath in handling of comments
--
-- Note: This is not the whole canonicalization as it is specified by the W3C
-- Recommendation. Adding attribute defaults or sorting attributes in lexicographic
-- order is done by the @transform@ function of module @Yuuko.Text.XML.HXT.Validator.Validation@.
-- Replacing entities or line feed normalization is done by the parser.
--
--
-- Not implemented yet:
--
-- - Whitespace within start and end tags is normalized
--
-- - Special characters in attribute values and character content are replaced by character references
--
-- see 'canonicalizeAllNodes' and 'canonicalizeForXPath'
canonicalizeTree' :: LA XmlTree XmlTree -> LA XmlTree XmlTree
canonicalizeTree' toBeRemoved
= processChildren (none `when` isText)
>>>
processBottomUp canonicalize1Node
where
canonicalize1Node :: LA XmlTree XmlTree
canonicalize1Node
= (deep isPi `when` isDTD) -- remove DTD parts, except PIs
>>>
(none `when` toBeRemoved) -- remove unintersting nodes
>>>
( processAttrl ( processChildren transfCharRef
>>>
collapseXText
)
`when` isElem
)
>>>
transfCdata -- CDATA -> text
>>>
transfCharRef -- Char refs -> text
>>>
collapseXText -- combine text
-- |
-- Applies some "Canonical XML" rules to a document tree.
--
-- The rule differ slightly for canonical XML and XPath in handling of comments
--
-- Note: This is not the whole canonicalization as it is specified by the W3C
-- Recommendation. Adding attribute defaults or sorting attributes in lexicographic
-- order is done by the @transform@ function of module @Yuuko.Text.XML.HXT.Validator.Validation@.
-- Replacing entities or line feed normalization is done by the parser.
--
-- Rules: remove DTD parts, processing instructions, comments and substitute char refs in attribute
-- values and text
--
-- Not implemented yet:
--
-- - Whitespace within start and end tags is normalized
--
-- - Special characters in attribute values and character content are replaced by character references
canonicalizeAllNodes :: ArrowList a => a XmlTree XmlTree
canonicalizeAllNodes
= fromLA $
canonicalizeTree' ( isCmt -- remove comment
<+>
isXmlPi -- remove xml declaration
)
-- |
-- Canonicalize a tree for XPath
-- Like 'canonicalizeAllNodes' but comment nodes are not removed
--
-- see 'canonicalizeAllNodes'
canonicalizeForXPath :: ArrowList a => a XmlTree XmlTree
canonicalizeForXPath
= fromLA $
canonicalizeTree' isXmlPi
-- |
-- Canonicalize the contents of a document
--
-- substitutes all char refs in text and attribute values,
-- removes CDATA section and combines all sequences of resulting text
-- nodes into a single text node
--
-- see 'canonicalizeAllNodes'
canonicalizeContents :: ArrowList a => a XmlTree XmlTree
canonicalizeContents
= fromLA $
processBottomUp canonicalize1Node
where
canonicalize1Node :: LA XmlTree XmlTree
canonicalize1Node
= ( processAttrl ( processChildren transfCharRef
>>>
collapseXText
)
`when` isElem
)
>>>
transfCdata -- CDATA -> text
>>>
transfCharRef -- Char refs -> text
>>>
collapseXText -- combine text
-- ------------------------------------------------------------
collapseXText' :: LA XmlTree XmlTree
collapseXText'
= replaceChildren ( listA getChildren >>> arrL (foldr mergeText' []) )
where
mergeText' :: XmlTree -> XmlTrees -> XmlTrees
mergeText' t1 (t2 : ts2)
| XN.isText t1 && XN.isText t2
= let
s1 = fromJust . XN.getText $ t1
s2 = fromJust . XN.getText $ t2
t = XN.mkText (s1 ++ s2)
in
t : ts2
mergeText' t1 ts
= t1 : ts
-- |
-- Collects sequences of text nodes in the list of children of a node into one single text node.
-- This is useful, e.g. after char and entity reference substitution
collapseXText :: ArrowList a => a XmlTree XmlTree
collapseXText
= fromLA $
collapseXText'
-- |
-- Applies collapseXText recursively.
--
--
-- see also : 'collapseXText'
collapseAllXText :: ArrowList a => a XmlTree XmlTree
collapseAllXText
= fromLA $
processBottomUp collapseXText'
-- ------------------------------------------------------------
-- | apply an arrow to the input and convert the resulting XML trees into an XML escaped string
--
-- This is a save variant for converting a tree into an XML string representation that is parsable with 'Yuuko.Text.XML.HXT.Arrow.ReadDocument'.
-- It is implemented with 'Yuuko.Text.XML.HXT.Arrow.XmlArrow.xshow', but xshow does no XML escaping. The XML escaping is done with
-- 'Yuuko.Text.XML.HXT.Arrow.Edit.escapeXmlDoc' before xshow is applied.
--
-- So the following law holds
--
-- > xshowEscape f >>> xread == f
xshowEscapeXml :: ArrowXml a => a n XmlTree -> a n String
xshowEscapeXml f = xshow (f >>> escapeXmlDoc)
-- ------------------------------------------------------------
-- |
-- escape XmlText,
-- transform all special XML chars into char- or entity- refs
type EntityRefTable = M.Map Int String
xmlEntityRefTable
, xhtmlEntityRefTable :: EntityRefTable
xmlEntityRefTable = buildEntityRefTable $ xmlEntities
xhtmlEntityRefTable = buildEntityRefTable $ xhtmlEntities
buildEntityRefTable :: [(String, Int)] -> EntityRefTable
buildEntityRefTable = M.fromList . map (\ (x,y) -> (y,x) )
escapeText'' :: (Char -> XmlTree) -> (Char -> Bool) -> XmlTree -> XmlTrees
escapeText'' escChar isEsc t
= maybe [t] escape' . XN.getText $ t
where
escape' "" = [t] -- empty text nodes remain empty text nodes
escape' s = escape s -- they do not disapear
escape ""
= []
escape (c:s1)
| isEsc c
= escChar c : escape s1
escape s
= XN.mkText s1 : escape s2
where
(s1, s2) = break isEsc s
{-
escapeCharRef :: Char -> XmlTree
escapeCharRef = XN.mkCharRef . fromEnum
-}
escapeEntityRef :: EntityRefTable -> Char -> XmlTree
escapeEntityRef entityTable c
= maybe (XN.mkCharRef c') XN.mkEntityRef . M.lookup c' $ entityTable
where
c' = fromEnum c
escapeXmlEntityRef :: Char -> XmlTree
escapeXmlEntityRef = escapeEntityRef xmlEntityRefTable
escapeHtmlEntityRef :: Char -> XmlTree
escapeHtmlEntityRef = escapeEntityRef xhtmlEntityRefTable
-- ------------------------------------------------------------
-- |
-- escape all special XML chars into XML entity references or char references
--
-- convert the special XML chars \< and & in text nodes into prefefiened XML entity references,
-- in attribute values also \', \", \>, \\n, \\r and \\t are converted into entity or char references,
-- in comments nothing is converted (see XML standard 2.4, useful e.g. for JavaScript).
escapeXmlDoc :: ArrowList a => a XmlTree XmlTree
escapeXmlDoc
= fromLA $ escapeDoc escXmlText escXmlAttrValue
where
escXmlText
= arrL $ escapeText'' escapeXmlEntityRef (`elem` "<&") -- no escape for ", ' and > required: XML standard 2.4
escXmlAttrValue
= arrL $ escapeText'' escapeXmlEntityRef (`elem` "<>\"\'&\n\r\t")
-- |
-- escape all special HTML chars into XHTML entity references or char references
--
-- convert the special XML chars \< and & and all none ASCII chars in text nodes into prefefiened XML or XHTML entity references,
-- in attribute values also \', \", \>, \\n, \\r and \\t are converted into entity or char references,
-- in comments nothing is converted
-- ------------------------------------------------------------
escapeHtmlDoc :: ArrowList a => a XmlTree XmlTree
escapeHtmlDoc
= fromLA $ escapeDoc escHtmlText escHtmlAttrValue
where
escHtmlText
= arrL $ escapeText'' escapeHtmlEntityRef isHtmlTextEsc
escHtmlAttrValue
= arrL $ escapeText'' escapeHtmlEntityRef isHtmlAttrEsc
isHtmlTextEsc c
= c >= toEnum(128) || ( c `elem` "<&" )
isHtmlAttrEsc c
= c >= toEnum(128) || ( c `elem` "<>\"\'&\n\r\t" )
-- ------------------------------------------------------------
escapeDoc :: LA XmlTree XmlTree -> LA XmlTree XmlTree -> LA XmlTree XmlTree
escapeDoc escText escAttr
= escape
where
escape
= choiceA
[ isElem :-> ( processChildren escape
>>>
processAttrl escVal
)
, isText :-> escText
-- , isCmt :-> escCmt
, isDTD :-> processTopDown escDTD
, this :-> this
]
escVal = processChildren escAttr
escDTD = escVal `when` ( isDTDEntity <+> isDTDPEntity )
-- ------------------------------------------------------------
preventEmptyElements :: ArrowList a => [String] -> Bool -> a XmlTree XmlTree
preventEmptyElements ns isHtml
= fromLA $ insertDummyElem
where
isNoneEmpty
| not (null ns) = hasNameWith (localPart >>> (`elem` ns))
| isHtml = hasNameWith (localPart >>> (`notElem` emptyHtmlTags))
| otherwise = this
insertDummyElem
= processBottomUp
( replaceChildren (txt "")
`when`
( isElem
>>>
isNoneEmpty
>>>
neg getChildren
)
)
-- ------------------------------------------------------------
-- |
-- convert a document into a Haskell representation (with show).
--
-- Useful for debugging and trace output.
-- see also : 'treeRepOfXmlDoc', 'numberLinesInXmlDoc'
haskellRepOfXmlDoc :: ArrowList a => a XmlTree XmlTree
haskellRepOfXmlDoc
= fromLA $
root [getAttrl] [show ^>> mkText]
-- |
-- convert a document into a text and add line numbers to the text representation.
--
-- Result is a root node with a single text node as child.
-- Useful for debugging and trace output.
-- see also : 'haskellRepOfXmlDoc', 'treeRepOfXmlDoc'
numberLinesInXmlDoc :: ArrowList a => a XmlTree XmlTree
numberLinesInXmlDoc
= fromLA $
processChildren (changeText numberLines)
where
numberLines :: String -> String
numberLines str
= concat $
zipWith (\ n l -> lineNr n ++ l ++ "\n") [1..] (lines str)
where
lineNr :: Int -> String
lineNr n = (reverse (take 6 (reverse (show n) ++ replicate 6 ' '))) ++ " "
-- |
-- convert a document into a text representation in tree form.
--
-- Useful for debugging and trace output.
-- see also : 'haskellRepOfXmlDoc', 'numberLinesInXmlDoc'
treeRepOfXmlDoc :: ArrowList a => a XmlTree XmlTree
treeRepOfXmlDoc
= fromLA $
root [getAttrl] [formatXmlTree ^>> mkText]
addHeadlineToXmlDoc :: ArrowXml a => a XmlTree XmlTree
addHeadlineToXmlDoc
= fromLA $ ( addTitle $< (getAttrValue a_source >>^ formatTitle) )
where
addTitle str
= replaceChildren ( txt str <+> getChildren <+> txt "\n" )
formatTitle str
= "\n" ++ headline ++ "\n" ++ underline ++ "\n\n"
where
headline = "content of: " ++ str
underline = map (const '=') headline
-- ------------------------------------------------------------
removeComment' :: LA XmlTree XmlTree
removeComment' = none `when` isCmt
-- |
-- remove Comments: @none `when` isCmt@
removeComment :: ArrowXml a => a XmlTree XmlTree
removeComment = fromLA $ removeComment'
-- |
-- remove all comments recursively
removeAllComment :: ArrowXml a => a XmlTree XmlTree
removeAllComment = fromLA $ processBottomUp removeComment'
-- ----------
removeWhiteSpace' :: LA XmlTree XmlTree
removeWhiteSpace' = none `when` isWhiteSpace
-- |
-- simple filter for removing whitespace.
--
-- no check on sigificant whitespace, e.g. in HTML \<pre\>-elements, is done.
--
--
-- see also : 'removeAllWhiteSpace', 'removeDocWhiteSpace'
removeWhiteSpace :: ArrowXml a => a XmlTree XmlTree
removeWhiteSpace = fromLA $ removeWhiteSpace'
-- |
-- simple recursive filter for removing all whitespace.
--
-- removes all text nodes in a tree that consist only of whitespace.
--
--
-- see also : 'removeWhiteSpace', 'removeDocWhiteSpace'
removeAllWhiteSpace :: ArrowXml a => a XmlTree XmlTree
removeAllWhiteSpace = fromLA $ processBottomUp removeWhiteSpace'
-- |
-- filter for removing all not significant whitespace.
--
-- the tree traversed for removing whitespace between elements,
-- that was inserted for indentation and readability.
-- whitespace is only removed at places, where it's not significat
-- preserving whitespace may be controlled in a document tree
-- by a tag attribute @xml:space@
--
-- allowed values for this attribute are @default | preserve@
--
-- input is root node of the document to be cleaned up,
-- output the semantically equivalent simplified tree
--
--
-- see also : 'indentDoc', 'removeAllWhiteSpace'
removeDocWhiteSpace :: ArrowXml a => a XmlTree XmlTree
removeDocWhiteSpace = fromLA $ removeRootWhiteSpace
removeRootWhiteSpace :: LA XmlTree XmlTree
removeRootWhiteSpace
= processChildren processRootElement
`when`
isRoot
where
processRootElement :: LA XmlTree XmlTree
processRootElement
= removeWhiteSpace >>> processChild
where
processChild
= choiceA [ isDTD
:-> removeAllWhiteSpace -- whitespace in DTD is redundant
, this
:-> replaceChildren ( getChildren
>>. indentTrees insertNothing False 1
)
]
-- ------------------------------------------------------------
-- |
-- filter for indenting a document tree for pretty printing.
--
-- the tree is traversed for inserting whitespace for tag indentation.
--
-- whitespace is only inserted or changed at places, where it isn't significant,
-- is's not inserted between tags and text containing non whitespace chars.
--
-- whitespace is only inserted or changed at places, where it's not significant.
-- preserving whitespace may be controlled in a document tree
-- by a tag attribute @xml:space@
--
-- allowed values for this attribute are @default | preserve@.
--
-- input is a complete document tree or a document fragment
-- result is the semantically equivalent formatted tree.
--
--
-- see also : 'removeDocWhiteSpace'
indentDoc :: ArrowXml a => a XmlTree XmlTree
indentDoc = fromLA $
( ( isRoot `guards` indentRoot )
`orElse`
(root [] [this] >>> indentRoot >>> getChildren)
)
-- ------------------------------------------------------------
indentRoot :: LA XmlTree XmlTree
indentRoot = processChildren indentRootChildren
where
indentRootChildren
= removeText >>> indentChild >>> insertNL
where
removeText = none `when` isText
insertNL = this <+> txt "\n"
indentChild = ( replaceChildren
( getChildren
>>.
indentTrees (insertIndentation 2) False 1
)
`whenNot` isDTD
)
-- ------------------------------------------------------------
--
-- copied from EditFilter and rewritten for arrows
-- to remove dependency to the filter module
indentTrees :: (Int -> LA XmlTree XmlTree) -> Bool -> Int -> XmlTrees -> XmlTrees
indentTrees _ _ _ []
= []
indentTrees indentFilter preserveSpace level ts
= runLAs lsf ls
++
indentRest rs
where
runLAs f l
= runLA (constL l >>> f) undefined
(ls, rs)
= break XN.isElem ts
isSignificant :: Bool
isSignificant
= preserveSpace
||
(not . null . runLAs isSignificantPart) ls
isSignificantPart :: LA XmlTree XmlTree
isSignificantPart
= catA
[ isText `guards` neg isWhiteSpace
, isCdata
, isCharRef
, isEntityRef
]
lsf :: LA XmlTree XmlTree
lsf
| isSignificant
= this
| otherwise
= (none `when` isWhiteSpace)
>>>
(indentFilter level <+> this)
indentRest :: XmlTrees -> XmlTrees
indentRest []
| isSignificant
= []
| otherwise
= runLA (indentFilter (level - 1)) undefined
indentRest (t':ts')
= runLA ( ( indentElem
>>>
lsf
)
`when` isElem
) t'
++
( if null ts'
then indentRest
else indentTrees indentFilter preserveSpace level
) ts'
where
indentElem
= replaceChildren ( getChildren
>>.
indentChildren
)
xmlSpaceAttrValue :: String
xmlSpaceAttrValue
= concat . runLA (getAttrValue "xml:space") $ t'
preserveSpace' :: Bool
preserveSpace'
= ( fromMaybe preserveSpace
.
lookup xmlSpaceAttrValue
) [ ("preserve", True)
, ("default", False)
]
indentChildren :: XmlTrees -> XmlTrees
indentChildren cs'
| all (maybe False (all isXmlSpaceChar) . XN.getText) cs'
= []
| otherwise
= indentTrees indentFilter preserveSpace' (level + 1) cs'
-- filter for indenting elements
insertIndentation :: Int -> Int -> LA a XmlTree
insertIndentation indentWidth level
= txt ('\n' : replicate (level * indentWidth) ' ')
-- filter for removing all whitespace
insertNothing :: Int -> LA a XmlTree
insertNothing _ = none
-- ------------------------------------------------------------
transfCdata' :: LA XmlTree XmlTree
transfCdata' = (getCdata >>> mkText) `when` isCdata
-- |
-- converts a CDATA section node into a normal text node
transfCdata :: ArrowXml a => a XmlTree XmlTree
transfCdata = fromLA $
transfCdata'
-- |
-- converts CDATA sections in whole document tree into normal text nodes
transfAllCdata :: ArrowXml a => a XmlTree XmlTree
transfAllCdata = fromLA $
processBottomUp transfCdata'
--
transfCharRef' :: LA XmlTree XmlTree
transfCharRef' = ( getCharRef >>> arr (\ i -> [toEnum i]) >>> mkText )
`when`
isCharRef
-- |
-- converts character references to normal text
transfCharRef :: ArrowXml a => a XmlTree XmlTree
transfCharRef = fromLA $
transfCharRef'
-- |
-- recursively converts all character references to normal text
transfAllCharRef :: ArrowXml a => a XmlTree XmlTree
transfAllCharRef = fromLA $
processBottomUp transfCharRef'
-- ------------------------------------------------------------
rememberDTDAttrl :: ArrowList a => a XmlTree XmlTree
rememberDTDAttrl
= fromLA $
( ( addDTDAttrl $< ( getChildren >>> isDTDDoctype >>> getDTDAttrl ) )
`orElse`
this
)
where
addDTDAttrl al
= seqA . map (uncurry addAttr) . map (first (dtdPrefix ++)) $ al
addDefaultDTDecl :: ArrowList a => a XmlTree XmlTree
addDefaultDTDecl
= fromLA $
( addDTD $< listA (getAttrl >>> (getName &&& xshow getChildren) >>> hasDtdPrefix) )
where
hasDtdPrefix
= isA (fst >>> (dtdPrefix `isPrefixOf`))
>>>
arr (first (drop (length dtdPrefix)))
addDTD []
= this
addDTD al
= replaceChildren
( mkDTDDoctype al none
<+>
txt "\n"
<+>
( getChildren >>> (none `when` isDTDDoctype) ) -- remove old DTD stuff
)
-- ------------------------------------------------------------
hasXmlPi :: ArrowXml a => a XmlTree XmlTree
hasXmlPi
= fromLA
( getChildren
>>>
isPi
>>>
hasName t_xml
)
-- | add an \<?xml version=\"1.0\"?\> processing instruction
-- if it's not already there
addXmlPi :: ArrowXml a => a XmlTree XmlTree
addXmlPi
= fromLA
( insertChildrenAt 0 ( ( mkPi (mkSNsName t_xml) none
>>>
addAttr a_version "1.0"
)
<+>
txt "\n"
)
`whenNot`
hasXmlPi
)
-- | add an encoding spec to the \<?xml version=\"1.0\"?\> processing instruction
addXmlPiEncoding :: ArrowXml a => String -> a XmlTree XmlTree
addXmlPiEncoding enc
= fromLA $
processChildren ( addAttr a_encoding enc
`when`
( isPi >>> hasName t_xml )
)
-- | add an XHTML strict doctype declaration to a document
addXHtmlDoctypeStrict
, addXHtmlDoctypeTransitional
, addXHtmlDoctypeFrameset :: ArrowXml a => a XmlTree XmlTree
-- | add an XHTML strict doctype declaration to a document
addXHtmlDoctypeStrict
= addDoctypeDecl "html" "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
-- | add an XHTML transitional doctype declaration to a document
addXHtmlDoctypeTransitional
= addDoctypeDecl "html" "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
-- | add an XHTML frameset doctype declaration to a document
addXHtmlDoctypeFrameset
= addDoctypeDecl "html" "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"
-- | add a doctype declaration to a document
--
-- The arguments are the root element name, the PUBLIC id and the SYSTEM id
addDoctypeDecl :: ArrowXml a => String -> String -> String -> a XmlTree XmlTree
addDoctypeDecl rootElem public system
= fromLA $
replaceChildren
( mkDTDDoctype ( ( if null public then id else ( (k_public, public) : ) )
.
( if null system then id else ( (k_system, system) : ) )
$ [ (a_name, rootElem) ]
) none
<+>
txt "\n"
<+>
getChildren
)
-- ------------------------------------------------------------
|
nfjinjing/yuuko
|
src/Yuuko/Text/XML/HXT/Arrow/Edit.hs
|
bsd-3-clause
| 23,058
| 700
| 14
| 5,180
| 4,219
| 2,428
| 1,791
| 427
| 4
|
module SegmentationTests where
import Test.QuickCheck
import Data.Char
import Prose.Types
import Prose.Segmentation.Graphemes as Graph
import Prose.Segmentation.Words as Word
import Prose.Internal.GraphemeBreakTest as GBT
import Prose.Internal.WordBreakTest as WBT
a1s = "óòo̧ö" :: String
a1accents = filter (not.isLetter) a1s
newtype G1 = G1 String deriving Show
instance Arbitrary G1 where
arbitrary = do alen <- choose (0,1) :: Gen Int
acc <- vectorOf alen (elements a1accents)
c <- elements ['a'..'z']
return $ G1 $ [c] ++ acc
{- TODO FIXME!
size :: [Grapheme] -> Int
size = sum . map length
g1_prop s = size (Graph.segment s) == length s
-}
properlyBroken segm broken = segm (concat broken) == broken
|| error (show broken)
-- GraphemeBreakTest
g2_check = all (properlyBroken Graph.segment) GBT.graphemebreaktest
-- WordBreakTest
w1_check = all (properlyBroken Word.segment) WBT.wordbreaktest
|
llelf/prose
|
tests/SegmentationTests.hs
|
bsd-3-clause
| 1,002
| 0
| 11
| 223
| 250
| 138
| 112
| 20
| 1
|
{-# LANGUAGE RecursiveDo #-}
module Main where
import LOGL.Application
import LOGL.Camera
import Foreign.Ptr
import Graphics.UI.GLFW as GLFW
import Graphics.Rendering.OpenGL.GL as GL hiding (normalize, position)
import Graphics.GLUtil
import System.FilePath
import Graphics.Rendering.OpenGL.GL.Shaders.ProgramObjects
import Linear.Matrix
import Linear.V3
import Linear.Vector
import Linear.Quaternion
import Linear.Projection
import Linear.Metric
import Reactive.Banana.Frameworks
import Reactive.Banana.Combinators hiding (empty)
import LOGL.FRP
import LOGL.Objects
main :: IO ()
main = do
GLFW.init
w <- createAppWindow 800 600 "LearnOpenGL"
setCursorInputMode (window w) CursorInputMode'Disabled
depthFunc $= Just Less
lampShader <- simpleShaderProgram ("data" </> "2_Lighting" </> "1_Colors" </> "lamp.vs")
("data" </> "2_Lighting" </> "1_Colors" </> "lamp.frag")
lightingShader <- simpleShaderProgram ("data" </> "2_Lighting" </> "2_Basic-lighting" </> "specular.vs")
("data" </> "2_Lighting" </> "2_Basic-lighting" </> "specular.frag")
cubeVBO <- createCubeVBO
containerVAO <- createContVAO cubeVBO
lightVAO <- createLampVAO cubeVBO
--polygonMode $= (Line, Line)
let networkDescription :: MomentIO ()
networkDescription = mdo
idleE <- idleEvent w
camB <- createAppCamera w (V3 0.0 0.0 3.0)
reactimate $ drawScene lightingShader containerVAO lampShader lightVAO w <$> (camB <@ idleE)
runAppLoopEx w networkDescription
deleteObjectName lightVAO
deleteObjectName containerVAO
deleteObjectName cubeVBO
terminate
drawScene :: ShaderProgram -> VertexArrayObject -> ShaderProgram -> VertexArrayObject -> AppWindow -> Camera GLfloat -> IO ()
drawScene lightingShader contVAO lampShader lightVAO w cam = do
pollEvents
clearColor $= Color4 0.1 0.1 0.1 1.0
clear [ColorBuffer, DepthBuffer]
Just time <- getTime
let lightX = 1.0 + 2.0 * sin time
lightY = sin (time / 2.0)
lightPos = V3 (realToFrac lightX) (realToFrac lightY) (2.0 :: GLfloat)
-- draw the container cube
currentProgram $= Just (program lightingShader)
setUniform lightingShader "objectColor" (V3 (1.0 :: GLfloat) 0.5 0.31)
setUniform lightingShader "lightColor" (V3 (1.0 :: GLfloat) 1.0 1.0)
setUniform lightingShader "lightPos" lightPos
setUniform lightingShader "viewPos" (position cam)
let view = viewMatrix cam
projection = perspective (radians (zoom cam)) (800.0 / 600.0) 0.1 (100.0 :: GLfloat)
setUniform lightingShader "view" view
setUniform lightingShader "projection" projection
let model = identity :: M44 GLfloat
setUniform lightingShader "model" model
withVAO contVAO $ drawArrays Triangles 0 36
-- draw the lamp
currentProgram $= Just (program lampShader)
setUniform lampShader "view" view
setUniform lampShader "projection" projection
let model = mkTransformationMat (0.2 *!! identity) lightPos
setUniform lampShader "model" model
withVAO lightVAO $ drawArrays Triangles 0 36
swap w
createCubeVBO :: IO BufferObject
createCubeVBO = makeBuffer ArrayBuffer cubeWithNormals
createContVAO :: BufferObject -> IO VertexArrayObject
createContVAO vbo = do
vao <- genObjectName
bindVertexArrayObject $= Just vao
bindBuffer ArrayBuffer $= Just vbo
vertexAttribPointer (AttribLocation 0) $= (ToFloat, VertexArrayDescriptor 3 Float (6*4) offset0)
vertexAttribArray (AttribLocation 0) $= Enabled
vertexAttribPointer (AttribLocation 1) $= (ToFloat, VertexArrayDescriptor 3 Float (6*4) (offsetPtr (3*4)))
vertexAttribArray (AttribLocation 1) $= Enabled
bindVertexArrayObject $= Nothing
return vao
createLampVAO :: BufferObject -> IO VertexArrayObject
createLampVAO vbo = do
vao <- genObjectName
bindVertexArrayObject $= Just vao
bindBuffer ArrayBuffer $= Just vbo
vertexAttribPointer (AttribLocation 0) $= (ToFloat, VertexArrayDescriptor 3 Float (6*4) offset0)
vertexAttribArray (AttribLocation 0) $= Enabled
bindVertexArrayObject $= Nothing
return vao
|
atwupack/LearnOpenGL
|
app/2_Lighting/2_Basic-lighting/Basic-lighting-specular.hs
|
bsd-3-clause
| 4,146
| 0
| 15
| 793
| 1,181
| 570
| 611
| 93
| 1
|
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.ARB.GlSpirv
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.ARB.GlSpirv (
-- * Extension Support
glGetARBGlSpirv,
gl_ARB_gl_spirv,
-- * Enums
pattern GL_SHADER_BINARY_FORMAT_SPIR_V_ARB,
pattern GL_SPIR_V_BINARY_ARB,
-- * Functions
glSpecializeShaderARB
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/ARB/GlSpirv.hs
|
bsd-3-clause
| 744
| 0
| 5
| 105
| 62
| 46
| 16
| 10
| 0
|
-- | Extra functions for optparse-applicative.
module Options.Applicative.Builder.Extra
(boolFlags
,boolFlagsNoDefault
,maybeBoolFlags
,firstBoolFlags
,enableDisableFlags
,enableDisableFlagsNoDefault
,extraHelpOption
,execExtraHelp
,textOption
,textArgument
,optionalFirst
) where
import Control.Monad (when)
import Data.Monoid
import Options.Applicative
import Options.Applicative.Types (readerAsk)
import System.Environment (withArgs)
import System.FilePath (takeBaseName)
import Data.Text (Text)
import qualified Data.Text as T
-- | Enable/disable flags for a 'Bool'.
boolFlags :: Bool -- ^ Default value
-> String -- ^ Flag name
-> String -- ^ Help suffix
-> Mod FlagFields Bool
-> Parser Bool
boolFlags defaultValue = enableDisableFlags defaultValue True False
-- | Enable/disable flags for a 'Bool', without a default case (to allow chaining with '<|>').
boolFlagsNoDefault :: String -- ^ Flag name
-> String -- ^ Help suffix
-> Mod FlagFields Bool
-> Parser Bool
boolFlagsNoDefault = enableDisableFlagsNoDefault True False
-- | Enable/disable flags for a @('Maybe' 'Bool')@.
maybeBoolFlags :: String -- ^ Flag name
-> String -- ^ Help suffix
-> Mod FlagFields (Maybe Bool)
-> Parser (Maybe Bool)
maybeBoolFlags = enableDisableFlags Nothing (Just True) (Just False)
-- | Like 'maybeBoolFlags', but parsing a 'First'.
firstBoolFlags :: String -> String -> Mod FlagFields (Maybe Bool) -> Parser (First Bool)
firstBoolFlags long0 help0 mod0 = First <$> maybeBoolFlags long0 help0 mod0
-- | Enable/disable flags for any type.
enableDisableFlags :: (Eq a)
=> a -- ^ Default value
-> a -- ^ Enabled value
-> a -- ^ Disabled value
-> String -- ^ Name
-> String -- ^ Help suffix
-> Mod FlagFields a
-> Parser a
enableDisableFlags defaultValue enabledValue disabledValue name helpSuffix mods =
enableDisableFlagsNoDefault enabledValue disabledValue name helpSuffix mods <|>
pure defaultValue
-- | Enable/disable flags for any type, without a default (to allow chaining with '<|>')
enableDisableFlagsNoDefault :: (Eq a)
=> a -- ^ Enabled value
-> a -- ^ Disabled value
-> String -- ^ Name
-> String -- ^ Help suffix
-> Mod FlagFields a
-> Parser a
enableDisableFlagsNoDefault enabledValue disabledValue name helpSuffix mods =
last <$> some
((flag'
enabledValue
(hidden <>
internal <>
long name <>
help helpSuffix <>
mods) <|>
flag'
disabledValue
(hidden <>
internal <>
long ("no-" ++ name) <>
help helpSuffix <>
mods)) <|>
flag'
disabledValue
(long (concat ["[no-]", name]) <>
help (concat ["Enable/disable ", helpSuffix]) <>
mods))
-- | Show an extra help option (e.g. @--docker-help@ shows help for all @--docker*@ args).
--
-- To actually have that help appear, use 'execExtraHelp' before executing the main parser.
extraHelpOption :: Bool -- ^ Hide from the brief description?
-> String -- ^ Program name, e.g. @"stack"@
-> String -- ^ Option glob expression, e.g. @"docker*"@
-> String -- ^ Help option name, e.g. @"docker-help"@
-> Parser (a -> a)
extraHelpOption hide progName fakeName helpName =
infoOption (optDesc' ++ ".") (long helpName <> hidden <> internal) <*>
infoOption (optDesc' ++ ".") (long fakeName <>
help optDesc' <>
(if hide then hidden <> internal else idm))
where optDesc' = concat ["Run '", takeBaseName progName, " --", helpName, "' for details"]
-- | Display extra help if extra help option passed in arguments.
--
-- Since optparse-applicative doesn't allow an arbitrary IO action for an 'abortOption', this
-- was the best way I found that doesn't require manually formatting the help.
execExtraHelp :: [String] -- ^ Command line arguments
-> String -- ^ Extra help option name, e.g. @"docker-help"@
-> Parser a -- ^ Option parser for the relevant command
-> String -- ^ Option description
-> IO ()
execExtraHelp args helpOpt parser pd =
when (args == ["--" ++ helpOpt]) $
withArgs ["--help"] $ do
_ <- execParser (info (hiddenHelper <*>
((,) <$>
parser <*>
some (strArgument (metavar "OTHER ARGUMENTS"))))
(fullDesc <> progDesc pd))
return ()
where hiddenHelper = abortOption ShowHelpText (long "help" <> hidden <> internal)
-- | 'option', specialized to 'Text'.
textOption :: Mod OptionFields Text -> Parser Text
textOption = option (T.pack <$> readerAsk)
-- | 'argument', specialized to 'Text'.
textArgument :: Mod ArgumentFields Text -> Parser Text
textArgument = argument (T.pack <$> readerAsk)
-- | Like 'optional', but returning a 'First'.
optionalFirst :: Alternative f => f a -> f (First a)
optionalFirst = fmap First . optional
|
phadej/stack
|
src/Options/Applicative/Builder/Extra.hs
|
bsd-3-clause
| 5,791
| 0
| 20
| 2,003
| 1,057
| 563
| 494
| 109
| 2
|
module Spreadsheet.Renderer where
import Data.List
import Data.Ratio
import Numeric
import Spreadsheet
import ListUtilities
renderCell :: CellType -> CellValue -> String
renderCell StringT (StringV xs) = xs
renderCell (NumberT Nothing) (NumberV n) | denominator n == 1 = show (numerator n)
renderCell (NumberT p) (NumberV n) = showFFloat (fmap fromInteger p) (fromRational n :: Double) ""
renderCell DateT (DateV d) = show d
renderCell _ EmptyV = ""
renderCell _ _ = "!!!"
renderCellType :: CellType -> String
renderCellType StringT = "text"
renderCellType (NumberT p) = "number" ++ maybe "" ((':':).show) p
renderCellType DateT = "date"
renderSpreadsheet :: Spreadsheet -> String
renderSpreadsheet (Spreadsheet hfs rs)
= unlines
$ map (intercalate " ")
$ zipWith3 headerPad widths hs ss
: zipWith formatPad widths fTexts
: [headerBar]
: map (zipWith3 dataPad widths fs) rTexts
where
widths = map maximum
$ transpose
$ map headerWidth hfs
: map length fTexts
: map (map cellWidth) rTexts
headerBar = replicate (sum widths + length widths - 1) '='
hs = map columnName hfs
fs = map columnType hfs
ss = map columnSort hfs
headerWidth h = length (columnName h) + sortLength (columnSort h) + 4
-- extra 4 because header is wrapped by '< ' and ' >'
cellWidth d = length d + 4
-- extra 4 because cell is wrapped by '[ ' and ' ]'
fTexts = map renderCellType fs
rTexts = map (zipWith renderCell fs) rs
sortLength Nothing = 0 -- ''
sortLength (Just _) = 2 -- ' +' and ' -'
-- | Render the spreadsheet in markdown.
renderSmd :: Spreadsheet -> String
renderSmd (Spreadsheet headers cells)
= unlines
$ map (intercalate "|")
$ padRow colNames
: headerSep
: map padRow renderedCells
where
-- Minimum width is 2 for the separator ":-"
widths = (map (max 2 . maximum . map length) . transpose)
(colNames : renderedCells)
mkSep w = ':' : replicate (w-1) '-'
headerSep = map mkSep widths
colTypes = map columnType headers
colNames = map (escapeString . columnName) headers
renderedCells = map renderRow cells
padRow = zipWith (\w -> padRight w ' ') widths
renderRow = map escapeString . zipWith renderCell colTypes
escapeString = concatMap markDownEscape
markDownEscape :: Char -> String
markDownEscape c =
case c of
'=' -> esc
'*' -> esc
'{' -> esc
'}' -> esc
'[' -> esc
']' -> esc
'(' -> esc
')' -> esc
'#' -> esc
'+' -> esc
'_' -> esc
'.' -> esc
'!' -> esc
'|' -> esc
_ -> [c]
where esc = ['\\',c]
headerPad :: Int -> String -> Maybe SortOrder -> String
headerPad i xs Nothing = "< " ++ padRight (i - 4) ' ' xs ++ " >"
headerPad i xs (Just s) = "< " ++ padRight (i - 6) ' ' xs ++ " " ++ sortStr ++ " >"
where
sortStr = case s of
Ascending -> "+"
Descending -> "-"
formatPad :: Int -> String -> String
formatPad i xs = padRight i ' ' xs
dataPad :: Int -> CellType -> String -> String
dataPad i cellType xs = "[ " ++ pad (i - 4) ' ' xs ++ " ]"
where
pad = case cellType of
StringT -> padRight
DateT -> padRight
NumberT _ -> padLeft
|
glguy/simple-spreadsheet-tools
|
lib/Spreadsheet/Renderer.hs
|
bsd-3-clause
| 3,273
| 0
| 14
| 901
| 1,125
| 567
| 558
| 90
| 15
|
{-# OPTIONS_GHC -Wall #-}
-- | Get the roots of shifted Legendre and Radau polynomials
--
-- >>> shiftedLegendreRoots 3
-- Just [0.11270166537925831,0.5,0.8872983346207417]
-- >>> shiftedRadauRoots 2
-- Just [0.1550510257216822,0.6449489742783178]
--
-- The roots are pre-computed and only a finite number are provided
--
-- >>> (V.length allShiftedLegendreRoots, V.length allShiftedRadauRoots)
-- (301,301)
-- >>> shiftedLegendreRoots 1000000000000000
-- Nothing
--
-- There are N roots in the Nth Jacobi polynomial
--
-- >>> import Data.Maybe ( fromJust )
-- >>> V.length (fromJust (shiftedLegendreRoots 5))
-- 5
-- >>> all (\k -> k == V.length (fromJust (shiftedLegendreRoots k))) [0..(V.length allShiftedLegendreRoots - 1)]
-- True
-- >>> all (\k -> k == V.length (fromJust (shiftedRadauRoots k))) [0..(V.length allShiftedRadauRoots - 1)]
-- True
module JacobiRoots
( shiftedLegendreRoots
, shiftedRadauRoots
, allShiftedLegendreRoots
, allShiftedRadauRoots
) where
import Data.Binary ( decode )
import qualified Data.Vector as V
import Data.Vector ( (!?) )
import JacobiRootsBinary ( allShiftedLegendreRootsBinary, allShiftedRadauRootsBinary )
-- | get the roots of the Nth shifted Legendre polynomial
--
-- @
-- 'shiftedLegendreRoots' == ('allShiftedLegendreRoots' '!?')
-- @
--
-- >>> mapM_ (print . shiftedLegendreRoots) [0..3]
-- Just []
-- Just [0.5]
-- Just [0.2113248654051871,0.7886751345948129]
-- Just [0.11270166537925831,0.5,0.8872983346207417]
shiftedLegendreRoots :: Int -> Maybe (V.Vector Double)
shiftedLegendreRoots = (allShiftedLegendreRoots !?)
-- | get the roots of the Nth shifted Radau polynomial
--
-- @
-- 'shiftedRadauRoots' == ('allShiftedRadauRoots' '!?')
-- @
--
-- >>> mapM_ (print . shiftedRadauRoots) [0..3]
-- Just []
-- Just [0.3333333333333333]
-- Just [0.1550510257216822,0.6449489742783178]
-- Just [8.858795951270394e-2,0.4094668644407347,0.787659461760847]
shiftedRadauRoots :: Int -> Maybe (V.Vector Double)
shiftedRadauRoots = (allShiftedRadauRoots !?)
-- | roots of shifted Jacobi polynomials with alpha=0, beta=0
allShiftedLegendreRoots :: V.Vector (V.Vector Double)
allShiftedLegendreRoots = V.fromList $ map V.fromList $ decode allShiftedLegendreRootsBinary
-- | roots of shifted Jacobi polynomials with alpha=1, beta=0
allShiftedRadauRoots :: V.Vector (V.Vector Double)
allShiftedRadauRoots = V.fromList $ map V.fromList $ decode allShiftedRadauRootsBinary
|
ghorn/jacobi-roots
|
src/JacobiRoots.hs
|
bsd-3-clause
| 2,453
| 0
| 9
| 350
| 247
| 159
| 88
| 18
| 1
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
module Scripts.ComadReview where
import ClassyPrelude
import Appian
import Appian.Types
import Appian.Instances
import Appian.Lens
import Appian.Client
import Data.Aeson
import Data.Aeson.Lens
import Control.Lens
import Control.Lens.Action.Reified
import Scripts.Common
import Scripts.ReviewCommon
import Appian.Internal.Arbitrary
import qualified Test.QuickCheck as QC
import Control.Monad.Time
import Scripts.ComadReviewTypes
import Data.Random (MonadRandom)
import Control.Monad.Except
comadInitialReview :: (RapidFire m, MonadGen m) => ReviewBaseConf -> ComadReviewConf -> AppianT m Value
comadInitialReview baseConf conf = do
(rid, v) <- myAssignedReport (conf ^? comadId) baseConf
rref <- handleMissing "recordRef" v $ v ^? getGridFieldCell . traverse . gfColumns . at "Application/Request Number" . traverse . _TextCellLink . _2 . traverse
-- distributeLinks_ (\rid -> editAdjustmentAmounts rid >> reviewComadRequest rid) rid conf v
editAdjustmentAmounts rref
reviewComadRequest rref
editAdjustmentAmounts :: (RapidFire m, MonadGen m) => RecordRef -> AppianT m Value
editAdjustmentAmounts rid =
viewRecordDashboard rid (Dashboard "summary")
>>= flip viewRelatedActions rid
>>= uncurry (executeRelatedAction "Edit Adjustment Amount")
>>= forAdjustments
>>= sendUpdates "Submit" (MonadicFold $ to $ buttonUpdate "Submit")
forAdjustments :: (RapidFire m, MonadGen m) => Value -> AppianT m Value
forAdjustments = forGridRows_ sendUpdates (^. gfIdentifiers . traverse) (MonadicFold $ getGridFieldCell . traverse) (\gfi _ v -> editAdjustment v gfi)
pageAdjustments :: (RapidFire m, MonadGen m) => Value -> AppianT m Value
pageAdjustments val = foldGridFieldPages (MonadicFold $ getGridFieldCell . traverse) editAdjustments val val
editAdjustments :: (RapidFire m, MonadGen m) => Value -> GridField GridFieldCell -> AppianT m (Value, Value)
editAdjustments val gf = do
v <- foldGridField' editAdjustment val gf
return (v, v)
editAdjustment :: (RapidFire m, MonadGen m) => Value -> GridFieldIdent -> AppianT m Value
editAdjustment val ident = do
gf <- handleMissing "FRN Adjustment Grid" val $ val ^? getGridFieldCell . traverse
val' <- sendUpdates "Adjustments: Select FRN Checkbox" (selectGridfieldUpdateF ident gf) val
let amtGen = QC.resize 50000 $ QC.arbitrarySizedNatural
arbitraryAmt = intFieldArbitraryUpdateF_ (fillIntField_ amtGen)
sendUpdates "Continue to Edit FRN Adjustment" (MonadicFold $ to $ buttonUpdate "Continue") val'
>>= sendUpdates "Enter FRN Data" (arbitraryAmt "COMAD Overlap Amount"
<|> arbitraryAmt "COMAD Recover Overlap"
<|> arbitraryAmt "RIDF Overlap"
<|> arbitraryAmt "COMAD/RIDF Overlap"
<|> arbitraryAmt "FRN Cross-COMAD Request Overlap"
<|> MonadicFold (checkboxGroupUpdate "Applicant RIDF Responsible Party" [1])
<|> MonadicFold (checkboxGroupUpdate "Applicant COMAD Responsible Party" mempty)
)
>>= sendUpdates "Calculate & Save" ( arbitraryAmt "Applicant RIDF Amount"
<|> MonadicFold (to $ buttonUpdate "Calculate")
<|> MonadicFold (to $ buttonUpdate "Save")
)
reviewComadRequest :: (RapidFire m, MonadGen m) => RecordRef -> AppianT m Value
reviewComadRequest rid =
viewRecordDashboard rid (Dashboard "summary")
>>= flip viewRelatedActions rid
>>= uncurry (executeRelatedAction "Review COMAD Request")
>>= forViolations
>>= sendUpdates' "Continue to 'Review FRN Decisions'" (MonadicFold (to $ buttonUpdate "Continue"))
>>= handleDecisionValidation
>>= forDecisions
>>= sendUpdates "Continue to 'Review Notes'" (MonadicFold $ to $ buttonUpdate "Continue")
>>= addNotes
>>= sendUpdates "Send to Next Reviewer" (MonadicFold $ to $ buttonUpdate "Send to Next Reviewer")
forViolations :: (RapidFire m, MonadGen m) => Value -> AppianT m Value
forViolations = forGridRows_ sendUpdates (^. gfIdentifiers . traverse) (MonadicFold $ getGridFieldCell . traverse) (\gfi _ v -> addViolation v gfi)
pageViolations :: (RapidFire m, MonadGen m) => Value -> AppianT m Value
pageViolations val = foldGridFieldPages (MonadicFold $ getGridFieldCell . traverse) addViolations val val
addViolations :: (RapidFire m, MonadGen m) => Value -> GridField GridFieldCell -> AppianT m (Value, Value)
addViolations val gf = do
v <- foldGridField' addViolation val gf
return (v, v)
addViolation :: (RapidFire m, MonadGen m) => Value -> GridFieldIdent -> AppianT m Value
addViolation val ident = do
gf <- handleMissing "FRN Violation Grid" val $ val ^? getGridFieldCell . traverse
sendUpdates' "Violations: Select FRN Checkbox & Review Violations" (selectGridfieldUpdateF ident gf
<|> MonadicFold (to $ buttonUpdate "Review Violation(s) for FRN")
) val
>>= handleNoViolation
handleNoViolation :: (RapidFire m, MonadGen m) => Either (ScriptError, Value) Value -> AppianT m Value
handleNoViolation (Left (se, _)) = case se ^? _ValidationsError . runFold ((,) <$> Fold _1 <*> Fold _2) of
Just (["You cannot add a Violation to an FRN that you have marked as \"No Violation\""], v) -> return v
Just ([], _) -> error "Violations not implemented yet!"
_ -> throwError se
handleNoViolation (Right v) =
sendUpdates "Add Violation Button" (MonadicFold $ to $ buttonUpdate "Add Violation") v
>>= sendUpdates "Add Violation" (MonadicFold $ dropping 1 getGridFieldCell . traverse . gfColumns . at "" . traverse . _TextCellDynLink . _2 . traverse . to toUpdate . to Right)
>>= sendUpdates "Select Party at Fault & Save" (MonadicFold (to $ dropdownUpdate "Party at Fault" 2)
<|> MonadicFold (to $ buttonUpdate "Save & Continue")
)
>>= sendUpdates "Add Rationale Button" (MonadicFold (to $ buttonUpdate "Add Rationale"))
>>= sendUpdates "Select Rationale Type" (MonadicFold (to $ dropdownUpdate "Rationale Type" 3))
>>= sendUpdates "Select Rationale Text" (MonadicFold $ dropping 2 getGridFieldCell . traverse . gfColumns . at "" . traverse . _TextCellDynLink . _2 . traverse . to toUpdate . to Right)
>>= sendUpdates "Save Rationale" (MonadicFold $ to $ buttonUpdate "Save Rationale")
>>= sendUpdates "Back to Violations" (MonadicFold $ to $ buttonUpdate "Back")
>>= sendUpdates "Back to Review COMAD Request" (MonadicFold $ to $ buttonUpdate "Back")
handleDecisionValidation :: MonadThrow m => Either (ScriptError, Value) Value -> AppianT m Value
handleDecisionValidation (Left (se, _)) = case se ^? _ValidationsError . runFold ((,) <$> Fold (_1 . to (all $ isPrefixOf "You must select a Decision for FRN")) <*> Fold _2) of
Just (True, v) -> return v
_ -> throwError se
handleDecisionValidation (Right v) = return v
pageDecisions :: (RapidFire m, MonadGen m) => Value -> AppianT m Value
pageDecisions val = foldGridFieldPages (MonadicFold $ getGridFieldCell . traverse) addDecisions val val
addDecisions :: (RapidFire m, MonadGen m) => Value -> GridField GridFieldCell -> AppianT m (Value, Value)
addDecisions val gf = do
v <- foldGridField' addDecision val gf
return (v, v)
forDecisions :: (RapidFire m, MonadGen m) => Value -> AppianT m Value
forDecisions = forGridRows_ sendUpdates (^. gfIdentifiers . traverse) (MonadicFold $ getGridFieldCell . traverse) (\gfi _ v -> addDecision v gfi)
addDecision :: (RapidFire m, MonadGen m) => Value -> GridFieldIdent -> AppianT m Value
addDecision val ident = do
gf <- handleMissing "FRN Decision Grid" val $ val ^? getGridFieldCell . traverse
eRes <- sendUpdates' "Decisions: Select FRN Checkbox" (selectGridfieldUpdateF ident gf) val
val' <- case eRes of
Right v -> return v
Left (se, _) -> case se ^? _ValidationsError . _2 of
Just v -> return v
_ -> throwError se
df <- handleMissing "FRN Decision Dropdown" val' $ val' ^? getDropdown "FRN Decision"
let choices
| nChoices > 1 = [2..nChoices]
| otherwise = mempty
nChoices = df ^. dfChoices . to length
addDecision_ FirstTry ident val' choices
data DecisionState
= FirstTry
| Retry
-- Retries an arbitrary decision until one succeeds or there are none left to chose from.
addDecision_ :: (RapidFire m, MonadGen m) => DecisionState -> GridFieldIdent -> Value -> [Int] -> AppianT m Value
addDecision_ decState ident val [] = throwError $ MissingComponentError ("There are no available decisions to make! ident: " <> tshow ident, val)
addDecision_ decState ident val l = do
gf <- handleMissing "FRN Decision Grid" val $ val ^? getGridFieldCell . traverse
val' <- case decState of
FirstTry -> return val
Retry -> do
eRes <- sendUpdates' "Decisions: Select FRN Checkbox" (selectGridfieldUpdateF ident gf) val
case eRes of
Right v -> return v
Left (se, _) -> case se ^? _ValidationsError . _2 of
Just v -> return v
_ -> throwError se
idx <- genArbitrary $ QC.elements l
eRes <- sendUpdates' "Select & Save FRN Decision" (MonadicFold (to $ dropdownUpdate "FRN Decision" $ trace ("Making decision: " <> show idx) idx)
<|> MonadicFold (to $ buttonUpdate "Save Decision")
) val'
case eRes of
Right val'' -> return val''
-- Left ve -> addDecision_ Retry ident (ve ^. validationsExc . _2) (delete idx l)
Left (se, _) -> case se ^? _ValidationsError . runFold ((,) <$> Fold (_1 . to (all $ isPrefixOf "You must select a Decision for FRN")) <*> Fold _2) of
Just (True, v) -> return v
Just (False, v) -> addDecision_ Retry ident v (delete idx l)
|
limaner2002/EPC-tools
|
USACScripts/src/Scripts/ComadReview.hs
|
bsd-3-clause
| 10,141
| 0
| 25
| 2,350
| 2,853
| 1,414
| 1,439
| -1
| -1
|
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TupleSections #-}
module Control.Broccoli.Eval where
import Control.Applicative
import Data.List
import Data.Ord
import Data.Monoid
import Data.Maybe
import Control.Comonad
import Test.QuickCheck
import Test.QuickCheck.Function
import Data.Map (Map)
import qualified Data.Map as M
import Debug.Trace
import Unsafe.Coerce
-- | @E a@ represents events with values of type @a@.
--
-- > E a = [(Time, a)]
data E a where
ConstantE :: [(Time, a)] -> E a
FmapE :: forall a b . (b -> a) -> E b -> E a
JustE :: E (Maybe a) -> E a
UnionE :: E a -> E a -> E a
DelayE :: Integer -> Double -> E a -> E a
SnapshotE :: forall a b c . Integer -> Bias -> (c -> b -> a) -> X c -> E b -> E a
EdgeE :: forall a b . a ~ (b,b) => X b -> E a
InputE :: InHook a -> E a
DebugE :: (a -> String) -> E a -> E a
-- | @X a@ represents time signals with values of type @a@.
--
-- > X a = Time -> a
data X a where
PureX :: a -> X a
TimeX :: a ~ Time => X a
FmapX :: forall a b . (b -> a) -> X b -> X a
ApplX :: forall a b . X (b -> a) -> X b -> X a
TrapX :: a -> E a -> X a
TimeWarpX :: (Time -> Time) -> (Time -> Time) -> X a -> X a
instance Functor E where
fmap f e = FmapE f e
instance Functor X where
fmap f sig = FmapX f sig
instance Applicative X where
pure x = PureX x
ff <*> xx = ApplX ff xx
instance Monoid a => Monoid (X a) where
mempty = pure mempty
mappend x1 x2 = liftA2 mappend x1 x2
-- | mempty = 'never', mappend = 'unionE'
instance Monoid (E a) where
mempty = never
mappend = unionE
-- | extract = 'atZero', duplicate @x@ at @t@ is 'timeShift' @t x@
instance Comonad X where
extract = atZero
duplicate x = fmap (\t -> timeShift t x) time
type Time = Double
type Handler a = a -> Time -> IO ()
data Bias = Now | NowMinus deriving (Eq, Ord, Show, Read)
type InHook a = Int -> [Int] -> (Time -> Time) -> ([a] -> Time -> IO ()) -> IO ()
-- | Seconds since start of simulation.
time :: X Time
time = TimeX
-- | An event that never happens.
never :: E a
never = occurs []
-- | Merge all the occurrences from two events together.
unionE :: E a -> E a -> E a
unionE = UnionE
-- | An event with occurrences explicitly specified in ascending order.
occurs :: [(Time, a)] -> E a
occurs = ConstantE
-- | > atZero x = x `at` 0
atZero :: X a -> a
atZero = (`at` 0)
-- | A signal that remembers the most recent occurrence of an event.
-- Takes a value to output prior to any events.
trap :: a -> E a -> X a
trap = TrapX
justE :: E (Maybe a) -> E a
justE = JustE
-- | Delay occurrences of an event.
delayE :: Double -> E a -> E a
delayE dt e = DelayE 0 dt e
-- | Shift a signal forward in time. A negative shift shifts back in time.
timeShift :: Double -> X a -> X a
timeShift delta sig = timeWarp (subtract delta) (+ delta) sig
-- | Time warp a signal. The inverse of the warp function must exist and
-- be provided.
timeWarp :: (Time -> Time) -> (Time -> Time) -> X a -> X a
timeWarp = TimeWarpX
-- | Like 'timeWarp' but doesn't require an inverse. Doesn't work with events.
timeWarp' :: (Time -> Time) -> X a -> X a
timeWarp' f x = if timeOnlyX x
then timeWarp f undefined x
else error "timeWarp': can't handle events. Try regular timeWarp."
-- | When the event occurs the value of the signal immediately before that
-- time will be captured. Therefore the output can feed back into the input.
snapshot :: (a -> b -> c) -> X a -> E b -> E c
snapshot = SnapshotE 0 NowMinus
-- | Like 'snapshot' but captures the value 'at' the time of the event.
-- Therefore the input cannot depend on the output.
snapshot' :: (a -> b -> c) -> X a -> E b -> E c
snapshot' = SnapshotE 0 Now
-- | Event occurs on transitions in a piecewise constant signal. Doesn't
-- work on continuously varying signals.
edge :: X a -> E (a, a)
edge x = if containsTimeX x
then error "edge: input not piecewise constant"
else EdgeE x
at :: X a -> Time -> a
at x t = case nextTimeX x of
Nothing -> phaseX x t
Just t' -> if t < t'
then phaseX x t
else let foo = tailX x in foo `at` t
occs :: E a -> [(Time, a)]
occs e = case nextTimeE e of
Nothing -> []
Just t -> let (v,e') = headE e in (t, v) : occs e'
-- divide a non-never event into first and rest occurrences
headE :: E a -> (a, E a)
headE arg = case arg of
ConstantE [] -> error "headE []"
ConstantE ((t,v):os) -> (v, ConstantE os)
FmapE f e -> let (v,e') = headE e in (f v, FmapE f e')
JustE e -> let (v, e') = headJustE e in (v, JustE e')
UnionE e1 e2 ->
let mt1 = nextTimeE e1 in
let mt2 = nextTimeE e2 in
if mLTE mt1 mt2
then let (v,e') = headE e1 in (v, UnionE e' e2)
else let (v,e') = headE e2 in (v, UnionE e1 e')
DelayE name delta e -> let (v,e') = headE e in (v, DelayE name delta e')
SnapshotE name bias cons x e -> ans where
(v2,e') = headE e
Just t = nextTimeE e
v1 = case nextTimeX x of
Nothing -> phaseX x t
Just t' -> if t <= t' then phaseX x t else error "fuck"
x' = case nextTimeX x of
Nothing -> x
Just t' -> if t < t' then x else tailX x
v = cons v1 v2
ans = (v, SnapshotE name bias cons x' e')
EdgeE x -> case nextTimeX x of
Nothing -> error "headE nonsense 1"
Just t -> ((ph t, ph' t), EdgeE (tailX x)) where
ph = phaseX x
ph' = phaseX (tailX x)
InputE _ -> error "headE input"
DebugE _ e -> headE e
-- drop the current phase and replace with next phase, unless that is nonsense
tailX :: X a -> X a
tailX arg = case arg of
PureX v -> error "tailX pure"
TimeX -> error "tailX time"
FmapX f x -> FmapX f (tailX x)
ApplX ff xx -> case nextTimeX ff of
Nothing -> case nextTimeX xx of
Nothing -> error "tailX nonsense 1"
Just _ -> ApplX ff (tailX xx)
Just t1 -> case nextTimeX xx of
Nothing -> ApplX (tailX ff) xx
Just t2 -> case compare t1 t2 of
LT -> ApplX (tailX ff) xx
GT -> ApplX ff (tailX xx)
EQ -> ApplX (tailX ff) (tailX xx)
TrapX v e -> case nextTimeE e of
Nothing -> error "tailX nonsense 2"
Just t -> let (v', e') = lastO e t in TrapX v' e'
TimeWarpX w wi x -> TimeWarpX w wi (tailX x)
-- the "current phase" of a signal
phaseX :: X a -> Time -> a
phaseX arg t = case arg of
PureX v -> v
TimeX -> t
FmapX f x -> f (phaseX x t)
ApplX ff xx -> (phaseX ff t) (phaseX xx t)
TrapX v e -> v
TimeWarpX w _ x -> phaseX x (w t)
-- find next transition time if any
nextTimeX :: X a -> Maybe Time
nextTimeX arg = case arg of
PureX v -> Nothing
TimeX -> Nothing
FmapX _ x -> nextTimeX x
ApplX ff xx -> case catMaybes [nextTimeX ff, nextTimeX xx] of
[] -> Nothing
ts -> Just (minimum ts)
TrapX v e -> nextTimeE e
TimeWarpX _ wi x -> fmap wi (nextTimeX x)
-- find next occurrence time if any
nextTimeE :: E a -> Maybe Time
nextTimeE arg = case arg of
ConstantE [] -> Nothing
ConstantE ((t,v):_) -> Just t
FmapE _ e -> nextTimeE e
JustE e -> nextJust e
UnionE e1 e2 -> case catMaybes [nextTimeE e1, nextTimeE e2] of
[] -> Nothing
ts -> Just (minimum ts)
DelayE _ delta e -> fmap (+delta) (nextTimeE e)
SnapshotE _ _ _ _ e -> nextTimeE e
EdgeE x -> nextTimeX x
InputE _ -> Nothing
DebugE _ e -> nextTimeE e
nextJust :: E (Maybe a) -> Maybe Time
nextJust e = case nextTimeE e of
Nothing -> Nothing
Just t -> case headE e of
(Just v, e') -> Just t
(Nothing, e') -> nextJust e'
headJustE :: E (Maybe a) -> (a, E (Maybe a))
headJustE e = case headE e of
(Just v, e') -> (v, e')
(Nothing, e') -> headJustE e'
-- a trap takes the last of a series of occurrences happening at the same time
lastO :: E a -> Time -> (a, E a)
lastO e t =
let (v,e') = headE e in
case nextTimeE e' of
Nothing -> (v,e')
Just t' | t' == t -> lastO e' t
| otherwise -> (v,e')
shX :: X a -> String
shX arg = case arg of
PureX _ -> "Pure"
TimeX -> "Time"
FmapX _ x -> "Fmap"
ApplX _ _ -> "Appl"
TrapX _ _ -> "Trap"
TimeWarpX _ _ _ -> "Warp"
shE :: E a -> String
shE arg = case arg of
ConstantE _ -> "Constant"
FmapE _ e -> "FmapE"
JustE e -> "Just"
UnionE e1 e2 -> "Union"
DelayE _ delta e -> "Delay"
SnapshotE _ _ _ _ e -> "Snap"
EdgeE x -> "Edge"
InputE _ -> "Input"
DebugE _ e -> "Debug"
timeOnlyX :: X a -> Bool
timeOnlyX arg = case arg of
PureX _ -> True
TimeX -> True
FmapX _ x -> timeOnlyX x
ApplX ff xx -> timeOnlyX ff && timeOnlyX xx
TrapX _ _ -> False
TimeWarpX _ _ x -> timeOnlyX x
containsTimeX :: X a -> Bool
containsTimeX arg = case arg of
PureX _ -> False
TimeX -> True
FmapX _ x -> containsTimeX x
ApplX ff xx -> containsTimeX ff || containsTimeX xx
TrapX _ _ -> False
TimeWarpX _ _ x -> containsTimeX x
mLTE :: Ord a => Maybe a -> Maybe a -> Bool
mLTE (Just a) (Just b) = a <= b
mLTE (Just _) Nothing = True
mLTE Nothing (Just _) = False
mLTE Nothing Nothing = error "mLTE nonsense"
rezip :: (Time -> a) -> [(Time, Time -> a)] -> [(Time -> a, Time)]
rezip _ [] = []
rezip ph0 ((t1,ph1):phs) = (ph0,t1) : rezip ph1 phs
-- experiments
w t = 10 - t/2
wi t = 20 - 2*t
e1 = occurs [(2, (1)), (4, (7)), (6, (5))]
e2 = occurs [(3, 0), (4, 1), (4, 2), (5, 10)]
x3 = (liftA2 (+) (trap (-1) e1) (trap (-1) e2))
e4 = edge x3
e5 = e4 <> occurs [(2.5, q 90), (4, q 40), (10,q 0), (10, q 2), (11, q 9)]
e6 = e4 <> delayE 1 (occurs [(3, q 40)])
q x = (x,x)
e7 = edge (timeWarp w wi x3)
e8 = delayE 5 (occurs [(0, ())] <> e8)
counter :: E () -> X Int
counter bump = out where
out = trap 0 e2
e2 = SnapshotE 0 NowMinus const next bump
next = (+1) <$> out
counter' :: E () -> X Int
counter' bump = out where
out = trap 0 e2
e2 = SnapshotE 0 NowMinus const next bump
next = (+1) <$> out
------
-- merge two sorted lists into another sorted list lazily
merge :: (a -> a -> Ordering) -> [a] -> [a] -> [a]
merge _ [] ys = ys
merge _ xs [] = xs
merge comp (x:xs) (y:ys) = case comp x y of
EQ -> x:merge comp xs (y:ys)
LT -> x:merge comp xs (y:ys)
GT -> y:merge comp (x:xs) ys
srToPeriod :: Int -> Double
srToPeriod = abs . recip . realToFrac
data WarpDirection = Forward | Backward deriving (Eq, Show)
warp :: (Time -> Time) -> WarpDirection
warp g = case compare (g 0) (g 1) of
LT -> Forward
EQ -> error "bad time warp"
GT -> Backward
prop_occurs :: Eq a => [(Time,a)] -> Bool
prop_occurs os = occs (occurs os) == os
prop_fmap :: Eq b => Fun a b -> E a -> Bool
prop_fmap (Fun _ f) e = occs (f <$> e) == map (fmap f) (occs e)
prop_justE :: Eq a => E (Maybe a) -> Bool
prop_justE e = catMaybes (map f (occs e)) == occs (JustE e) where
f (_, Nothing) = Nothing
f (t, Just v) = Just (t,v)
prop_unionE :: Eq a => E a -> E a -> Bool
prop_unionE e1 e2 = merge (comparing fst) (occs e1) (occs e2) == occs (e1 <> e2)
prop_unionE2 :: Bool
prop_unionE2 = merge (comparing fst) (occs e1) (occs e2) == occs (e1 <> e2) where
e1 = occurs [(-1, 'a'), (0,'b'), (1,'c')]
e2 = occurs [(0, 'd'), (1,'e'), (2,'f')]
-- not exactly true due to floating point
{-
prop_delayE :: Eq a => Double -> E a -> Bool
prop_delayE delta e = all id (zipWith f (occs e) (occs e')) where
f (t1,v1) (t2,v2) = t2 - t1 == delta && v1 == v2
e' = DelayE (fmap (,delta) e)
-}
prop_snapshot1 :: Eq a => X a -> E a -> Bool
prop_snapshot1 x e = occs (SnapshotE 0 Now (,) x e) == fmap f (occs e) where
f (t, v) = (t, (x `at` t, v))
prop_snapshot2 :: Bool
prop_snapshot2 = occs (SnapshotE 0 Now (,) x e) == fmap f (occs e) where
e = occurs [(0, 'a'), (1, 'b'), (2, 'c')]
x = TrapX 'z' (occurs [(0,'d'), (1,'e'), (2,'f')])
f (t, v) = (t, (x `at` t, v))
prop_snapshot3 :: Bool
prop_snapshot3 = occs (SnapshotE 0 NowMinus (,) x e) == ans where
e = occurs [(0, 'a'), (1, 'b'), (2, 'c')]
x = TrapX 'z' (occurs [(0,'d'), (1,'e'), (2,'f')])
ans = [(0, ('z','a')), (1, ('d','b')), (2, ('e','c'))]
prop_snapshot4 :: Bool
prop_snapshot4 = occs (SnapshotE 0 Now (,) x e) == ans where
e = occurs [(-1, 'a'), (0, 'b'), (1, 'c')]
x = TimeWarpX negate negate (TrapX 'z' (occurs [(-1,'d'), (0,'e'), (1,'f')]))
ans = [(-1, ('f','a')), (0, ('e','b')), (1, ('d','c'))]
prop_snapshot5 :: Bool
prop_snapshot5 = occs (SnapshotE 0 NowMinus (,) x e) == ans where
e = occurs [(-1, 'a'), (0, 'b'), (1, 'c')]
x = TimeWarpX negate negate (TrapX 'z' (occurs [(-1,'d'), (0,'e'), (1,'f')]))
ans = [(-1, ('z','a')), (0, ('f','b')), (1, ('e','c'))]
prop_warp1 :: Eq a => Time -> X a -> Bool
prop_warp1 t x = (TimeWarpX f undefined x) `at` t == x `at` (f t) where
f u = u**3
prop_warp2 :: Eq a => Time -> a -> E a -> Bool
prop_warp2 t v0 e = (TimeWarpX f undefined x) `at` t == x `at` (f t) where
x = TrapX v0 e
f u = -u**3
prop_applX :: Eq b => Time -> X (Fun Int b) -> X Int -> Bool
prop_applX t ff xx = (liftA2 app ff xx) `at` t == app (ff `at` t) (xx `at` t) where
app (Fun _ f) x = f x
instance Show a => Show (E a) where
show e = "occurs " ++ show (occs e)
{-
instance Show (X a) where
show arg = case arg of
PureX _ -> "PureX ?"
TimeX -> "TimeX"
FmapX _ _ -> "FmapX ? ?"
ApplX _ _ -> "ApplX ? ?"
TrapX _ _ -> "TrapX ? ?"
TimeWarpX _ _ _ -> "TimeWarpX ? ? ?"
-}
instance Arbitrary a => Arbitrary (E a) where
arbitrary = (occurs . sortBy (comparing fst)) <$> listOf o where
o = do
t <- choose (-100, 100)
v <- arbitrary
return (t, v)
instance Arbitrary a => Arbitrary (X a) where
arbitrary = oneof [boringGen, trapGen]
boringGen :: Arbitrary a => Gen (X a)
boringGen = do
vs <- listOf1 arbitrary
let l = length vs
return $ (\t -> vs !! (floor t `mod` l)) <$> TimeX
trapGen :: Arbitrary a => Gen (X a)
trapGen = do
e <- arbitrary
v0 <- arbitrary
return (TrapX v0 e)
data Progress = Progress
{ prDelayNames :: [Integer]
, prSnapEvents :: (Map Integer (E Any)) }
prAddDN :: Progress -> Integer -> Progress
prAddDN pr i = pr { prDelayNames = i : prDelayNames pr }
prAddSnapEvent :: Progress -> Integer -> E a -> Progress
prAddSnapEvent pr name e = pr { prSnapEvents = f (prSnapEvents pr) } where
f m = M.insert name (unsafeCoerce e) m
-- not type safe but it isn't visible to the client
prLookupEvent :: Progress -> Integer -> E a -> E a
prLookupEvent pr name eDef = case M.lookup name (prSnapEvents pr) of
Nothing -> eDef
Just e -> (unsafeCoerce e)
prEmpty :: Progress
prEmpty = Progress [] M.empty
|
evanrinehart/broccoli
|
Control/Broccoli/Eval.hs
|
bsd-3-clause
| 14,305
| 0
| 19
| 3,629
| 6,624
| 3,418
| 3,206
| 354
| 16
|
module Data.Empty where
import Data.Countable
import Data.Searchable
class (Finite n) => Empty n where
never :: n -> a
instance (Empty a, Empty b) => Empty (Either a b) where
never (Left a) = never a
never (Right a) = never a
instance (Empty a, Finite b) => Empty (a, b) where
never (a, _) = never a
instance (AtLeastOneCountable a, Finite a, Empty b) => Empty (a -> b) where
never ab = never (ab countFirst)
data None
instance Countable None where
countPrevious = never
countMaybeNext Nothing = Nothing
countMaybeNext (Just n) = never n
instance Searchable None where
search = finiteSearch
instance Finite None where
allValues = []
assemble _ = pure never
instance Empty None where
never a = case a of {}
instance Eq None where
a == _b = never a
instance Ord None where
a <= _b = never a
instance Show None where
show a = never a
|
AshleyYakeley/countable
|
src/Data/Empty.hs
|
bsd-3-clause
| 904
| 0
| 8
| 228
| 372
| 190
| 182
| -1
| -1
|
----------------------------------------------------------------------------
-- |
-- Module : ModuleWithImportsAndHiding
-- Copyright : (c) Sergey Vinokurov 2015
-- License : BSD3-style (see LICENSE)
-- Maintainer : serg.foo@gmail.com
----------------------------------------------------------------------------
module ModuleWithImportsAndHiding where
import Imported1
import Imported2 hiding (bar2)
baz :: a -> a
baz x = x
|
sergv/tags-server
|
test-data/0001module_with_imports/ModuleWithImportsAndHiding.hs
|
bsd-3-clause
| 443
| 0
| 5
| 62
| 40
| 27
| 13
| 5
| 1
|
{-# LANGUAGE FlexibleContexts #-}
module EFA.Data.ND.Cube.Grid where
import qualified EFA.Data.Vector as DV
import qualified EFA.Data.ND as ND
import qualified EFA.Data.Axis.Strict as Axis
import EFA.Utility(Caller,ModuleName(..),(|>),FunctionName, genCaller)
import qualified Type.Data.Num.Unary as Unary
import qualified Data.FixedLength as FL
import qualified Data.Map as Map
import qualified Data.Traversable as Trav
import qualified Data.Foldable as Fold
m :: ModuleName
m = ModuleName "Grid"
nc :: FunctionName -> Caller
nc = genCaller m
-- newtype Idx = Idx {getInt :: Int} deriving Show
type Grid typ dim label vec a = ND.Data dim (Axis.Axis typ label vec a)
--instance Ref.ToData Grid where
-- toData (Grid vec) = Ref.SingleData "Grid" $ toData vec
type DimIdx dim = ND.Data dim Axis.Idx
newtype LinIdx = LinIdx {getInt:: Int} deriving (Show,Eq)
toLinear ::
(Unary.Natural dim, DV.Storage vec a, DV.Length vec)=>
Grid typ dim label vec a -> DimIdx dim -> LinIdx
toLinear axes indices = LinIdx $
Fold.foldl (\cum (ax, Axis.Idx idx) -> cum * Axis.len ax + idx) 0 $
FL.zipWith (,) axes indices
fromLinear ::
(Unary.Natural dim, DV.Storage vec a, DV.Length vec) =>
Grid typ dim label vec a -> LinIdx -> DimIdx dim
fromLinear axes (LinIdx idx) =
fmap Axis.Idx $ snd $
Trav.mapAccumR (\r ax -> divMod r (Axis.len ax)) idx axes
create ::
(Unary.Natural dim, Ord a,
DV.Zipper vec,
DV.Storage vec a,
DV.Storage vec Bool,
DV.Singleton vec) =>
Caller -> ND.Data dim (label,vec a) -> Grid typ dim label vec a
create caller = FL.map (uncurry $ Axis.fromVec newCaller)
where newCaller = caller |> (nc "create")
-- | generate a vector as linear listing of all coordinates in a grid
toVector ::
(Unary.Natural dim,
DV.Storage vec (ND.Data dim a),
DV.Storage vec a,
DV.FromList vec) =>
Grid typ dim label vec a ->
vec (ND.Data dim a)
toVector =
DV.fromList . Trav.traverse (DV.toList . Axis.getVec)
-- | Get Sizes of alle Axes
sizes ::
(Unary.Natural dim, DV.Storage vec a, DV.Length vec) =>
Grid typ dim label vec a -> ND.Data dim Int
sizes = FL.map Axis.len
-- | Remove axes of specified dimensions
extract ::
(Unary.Natural dim, Unary.Natural dim2) =>
Caller ->
Grid typ dim label vec a ->
ND.Data dim2 ND.Idx ->
Grid typ dim2 label vec a
extract caller grid =
FL.map (ND.lookup (caller |> nc "extract") grid)
-- | Generate a complete index room, but restrain index for dimension to be reduced to the specified value
reductionIndexVector ::
(Unary.Natural dim,
DV.Walker vec,DV.Storage vec LinIdx,DV.Length vec,
DV.Storage vec (ND.Data dim Axis.Idx),
DV.Singleton vec,
DV.Storage vec Axis.Idx,
DV.Storage vec a,
DV.FromList vec) =>
Grid typ dim label vec a -> Map.Map ND.Idx Axis.Idx -> vec LinIdx
reductionIndexVector axes dimensionsToReduce =
DV.map (toLinear axes) $ toVector $ FL.zipWith f FL.indicesInt axes
where f dim axis@(Axis.Axis l _) =
case Map.lookup (ND.Idx dim) dimensionsToReduce of
Just index -> Axis.Axis l $ DV.singleton index
Nothing -> Axis.imap (\index _ -> index) axis
|
energyflowanalysis/efa-2.1
|
src/EFA/Data/ND/Cube/Grid.hs
|
bsd-3-clause
| 3,137
| 0
| 13
| 623
| 1,140
| 606
| 534
| 75
| 2
|
{-# LANGUAGE DeriveDataTypeable, DeriveGeneric, MultiParamTypeClasses
#-}
module FOmega.SemanticSig where
import Control.Monad (forM)
import Data.Typeable(Typeable)
import GHC.Generics (Generic)
import Unbound.Generics.LocallyNameless (Bind, Embed, Alpha, Subst, LFresh)
import qualified Unbound.Generics.LocallyNameless as U
import FOmega.Syntax
-- Σ
data SemanticSig =
-- [τ]
ValSem !Type
-- [= τ:κ]
| TypeSem !Type !Kind
-- [= Ξ] -- We don't have nested signature definitions in
-- Insomnia inside modules, but we have them inside toplevels.
| SigSem !AbstractSig
-- [= δ = {f1:τ1 | … | fN:τN} : κ]
| DataSem !TyVar !DataTypeSem !Kind
-- { f1 : Σ1, ..., fn : Σn }
| ModSem ![(Field, SemanticSig)]
-- ∀ α1:κ1 ... αN:κN . Σ → Ξ
| FunctorSem !(Bind [(TyVar, Embed Kind)] SemanticFunctor)
-- Dist Ξ
| ModelSem AbstractSig
deriving (Show, Typeable, Generic)
data SemanticFunctor =
-- Σ1 → ... Σn → Ξ
SemanticFunctor ![SemanticSig] !AbstractSig
deriving (Show, Typeable, Generic)
-- Ξ
newtype AbstractSig =
-- ∃ α1:κ1 ... αN:κN . Σ
AbstractSig (Bind [(TyVar, Embed Kind)] SemanticSig)
deriving (Show, Typeable, Generic)
newtype DataTypeSem =
-- λαs:κs. f1 (τ11,…,τn1), ⋯ , fN (τN1,…,τmN)
-- we assume that the fields are all FUser and correspond to the constructors,
-- and that they refer to a free variable δ (of kind κs → ⋆) which corresponds to the
-- recursive occurrences of the datatype itself
DataTypeSem (Bind [(TyVar, Embed Kind)] [(Field, [Type])])
deriving (Show, Typeable, Generic)
instance Alpha SemanticSig
instance Alpha SemanticFunctor
instance Alpha AbstractSig
instance Alpha DataTypeSem
instance Subst Type SemanticSig
instance Subst Type SemanticFunctor
instance Subst Type AbstractSig
instance Subst Type DataTypeSem
-- * Embedding into F Omega
--
-- The "F-ing Modules" paper shows that semantic signatures can be embedded into plain vanilla FΩ.
--
embedSemanticSig :: LFresh m => SemanticSig -> m Type
embedSemanticSig (ValSem t) = return $ TRecord [(FVal, t)]
embedSemanticSig (TypeSem t k) = do
-- this is slightly tricky because we want to embed a higher-kinded
-- constructor t of kind k into KType. We don't care about the
-- particulars of the embedding as long as we have something of kind
-- KType that is inhabited whenever t is well-formed. So we use the
-- type of an identity function of argument (α t) where α is of kind
-- k→KType.
a <- U.lfresh $ U.s2n "α"
let
tConsume = TApp (TV a) t
tEmbed = TForall $ U.bind (a, U.embed $ k `KArr` KType) $ TArr tConsume tConsume
return $ TRecord [(FType, tEmbed)]
embedSemanticSig (SigSem absSig) = do
s <- embedAbstractSig absSig
return $ TRecord [(FSig, s `TArr` s)]
embedSemanticSig (DataSem d dt k) = embedDataTypeSem d k dt
embedSemanticSig (ModSem fas) = do
fts <- forM fas $ \(f, s) -> do
t <- embedSemanticSig s
return (f, t)
return $ TRecord fts
embedSemanticSig (FunctorSem bnd) =
embedSemanticFunctor bnd
embedSemanticSig (ModelSem abstr) = do
t <- embedAbstractSig abstr
return $ TDist t
embedSemanticFunctor :: LFresh m =>
U.Bind [(TyVar, U.Embed Kind)] SemanticFunctor
-> m Type
embedSemanticFunctor bnd =
U.lunbind bnd $ \(tvks, SemanticFunctor doms cod) -> do
domTs <- mapM embedSemanticSig doms
codT <- embedAbstractSig cod
return $ closeForalls tvks $ domTs `tArrs` codT
embedAbstractSig :: LFresh m => AbstractSig -> m Type
embedAbstractSig (AbstractSig bnd) =
U.lunbind bnd $ \(tvks, sig) -> do
t <- embedSemanticSig sig
return $ tExists' tvks t
-- | embed a datatype into the type language
-- δ ≙ μδ:κs→⋆. λαs:κs. f1(τ11,…,τn1), ⋯, fN(τ1N,…,τmN)
-- becomes
-- { dataOut : ∀γ:(κs→⋆)→⋆ . γ δ → γ (λαs:κs . {f1 : ⊗τ1s | ⋯ | fN : ⊗τNs })
-- , dataIn : { f1 : ∀αs:κs . τ1s → δ αs ; … ; fN : ∀αs:κs . τNs → δ αs }
-- }
-- where δ is assumed to be free (and will usually be existentially quantified somewhere in
-- the surrounding context.
--
-- That is, dataOut converts δ (in some sort of type context) to a sum
-- type of constructors, and dataIn is a record of injection
-- functions.
embedDataTypeSem :: LFresh m => TyVar -> Kind -> DataTypeSem -> m Type
embedDataTypeSem dataTyVar kData (DataTypeSem bnd) =
U.lunbind bnd $ \(tvks_, conFArgs) -> do
let tvks = map (\(f,ek) -> (f, U.unembed ek)) tvks_
outTy <- dataTypeOut tvks conFArgs
inTy <- dataTypeIn tvks conFArgs
return $ TRecord [(FDataOut, outTy),
(FDataIn, inTy)]
where
dataTypeOut tvks conFArgs = do
let conTys = flip map conFArgs $ \(fld, args) ->
(fld, tupleT args)
codLam = tLams tvks (TSum conTys)
vg <- U.lfresh (U.s2n "γ")
let g = TV vg
kg = kData `KArr` KType
return $ TForall $ U.bind (vg, U.embed kg) $ (g `TApp` TV dataTyVar) `TArr` (g `TApp` codLam)
dataTypeIn tvks conFArgs =
let d = TV dataTyVar `tApps` (map (TV . fst) tvks)
conTys = flip map conFArgs $ \(fld, args) ->
(fld, tForalls tvks $ args `tArrs` d)
in return $ TRecord conTys
closeForalls :: [(TyVar, Embed Kind)] -> Type -> Type
closeForalls [] = id
closeForalls (ak:aks) =
TForall . U.bind ak . closeForalls aks
|
lambdageek/insomnia
|
src/FOmega/SemanticSig.hs
|
bsd-3-clause
| 5,431
| 0
| 17
| 1,185
| 1,437
| 757
| 680
| 116
| 1
|
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.SetupWrapper
-- Copyright : (c) The University of Glasgow 2006,
-- Duncan Coutts 2008
--
-- Maintainer : cabal-devel@haskell.org
-- Stability : alpha
-- Portability : portable
--
-- An interface to building and installing Cabal packages.
-- If the @Built-Type@ field is specified as something other than
-- 'Custom', and the current version of Cabal is acceptable, this performs
-- setup actions directly. Otherwise it builds the setup script and
-- runs it with the given arguments.
module Distribution.Client.SetupWrapper (
setupWrapper,
SetupScriptOptions(..),
defaultSetupScriptOptions,
) where
import Distribution.Client.Types
( InstalledPackage )
import qualified Distribution.Make as Make
import qualified Distribution.Simple as Simple
import Distribution.Version
( Version(..), VersionRange, anyVersion
, intersectVersionRanges, orLaterVersion
, withinRange )
import Distribution.Package
( PackageIdentifier(..), PackageName(..), Package(..), packageName
, packageVersion, Dependency(..) )
import Distribution.PackageDescription
( GenericPackageDescription(packageDescription)
, PackageDescription(..), specVersion, BuildType(..) )
import Distribution.PackageDescription.Parse
( readPackageDescription )
import Distribution.Simple.Configure
( configCompiler )
import Distribution.Simple.Compiler
( CompilerFlavor(GHC), Compiler, PackageDB(..), PackageDBStack )
import Distribution.Simple.Program
( ProgramConfiguration, emptyProgramConfiguration
, rawSystemProgramConf, ghcProgram )
import Distribution.Simple.BuildPaths
( defaultDistPref, exeExtension )
import Distribution.Simple.Command
( CommandUI(..), commandShowOptions )
import Distribution.Simple.GHC
( ghcVerbosityOptions )
import qualified Distribution.Client.PackageIndex as PackageIndex
import Distribution.Client.PackageIndex (PackageIndex)
import Distribution.Client.IndexUtils
( getInstalledPackages )
import Distribution.Simple.Utils
( die, debug, info, cabalVersion, findPackageDesc, comparing
, createDirectoryIfMissingVerbose, rewriteFile )
import Distribution.Client.Utils
( moreRecentFile, inDir )
import Distribution.Text
( display )
import Distribution.Verbosity
( Verbosity )
import System.Directory ( doesFileExist, getCurrentDirectory )
import System.FilePath ( (</>), (<.>) )
import System.IO ( Handle )
import System.Exit ( ExitCode(..), exitWith )
import System.Process ( runProcess, waitForProcess )
import Control.Monad ( when, unless )
import Data.List ( maximumBy )
import Data.Maybe ( fromMaybe, isJust )
import Data.Char ( isSpace )
data SetupScriptOptions = SetupScriptOptions {
useCabalVersion :: VersionRange,
useCompiler :: Maybe Compiler,
usePackageDB :: PackageDBStack,
usePackageIndex :: Maybe (PackageIndex InstalledPackage),
useProgramConfig :: ProgramConfiguration,
useDistPref :: FilePath,
useLoggingHandle :: Maybe Handle,
useWorkingDir :: Maybe FilePath
}
defaultSetupScriptOptions :: SetupScriptOptions
defaultSetupScriptOptions = SetupScriptOptions {
useCabalVersion = anyVersion,
useCompiler = Nothing,
usePackageDB = [GlobalPackageDB, UserPackageDB],
usePackageIndex = Nothing,
useProgramConfig = emptyProgramConfiguration,
useDistPref = defaultDistPref,
useLoggingHandle = Nothing,
useWorkingDir = Nothing
}
setupWrapper :: Verbosity
-> SetupScriptOptions
-> Maybe PackageDescription
-> CommandUI flags
-> (Version -> flags)
-> [String]
-> IO ()
setupWrapper verbosity options mpkg cmd flags extraArgs = do
pkg <- maybe getPkg return mpkg
let setupMethod = determineSetupMethod options' buildType'
options' = options {
useCabalVersion = intersectVersionRanges
(useCabalVersion options)
(orLaterVersion (specVersion pkg))
}
buildType' = fromMaybe Custom (buildType pkg)
mkArgs cabalLibVersion = commandName cmd
: commandShowOptions cmd (flags cabalLibVersion)
++ extraArgs
setupMethod verbosity options' (packageId pkg) buildType' mkArgs
where
getPkg = findPackageDesc (fromMaybe "." (useWorkingDir options))
>>= readPackageDescription verbosity
>>= return . packageDescription
-- | Decide if we're going to be able to do a direct internal call to the
-- entry point in the Cabal library or if we're going to have to compile
-- and execute an external Setup.hs script.
--
determineSetupMethod :: SetupScriptOptions -> BuildType -> SetupMethod
determineSetupMethod options buildType'
| isJust (useLoggingHandle options)
|| buildType' == Custom = externalSetupMethod
| cabalVersion `withinRange`
useCabalVersion options = internalSetupMethod
| otherwise = externalSetupMethod
type SetupMethod = Verbosity
-> SetupScriptOptions
-> PackageIdentifier
-> BuildType
-> (Version -> [String]) -> IO ()
-- ------------------------------------------------------------
-- * Internal SetupMethod
-- ------------------------------------------------------------
internalSetupMethod :: SetupMethod
internalSetupMethod verbosity options _ bt mkargs = do
let args = mkargs cabalVersion
debug verbosity $ "Using internal setup method with build-type " ++ show bt
++ " and args:\n " ++ show args
inDir (useWorkingDir options) $
buildTypeAction bt args
buildTypeAction :: BuildType -> ([String] -> IO ())
buildTypeAction Simple = Simple.defaultMainArgs
buildTypeAction Configure = Simple.defaultMainWithHooksArgs
Simple.autoconfUserHooks
buildTypeAction Make = Make.defaultMainArgs
buildTypeAction Custom = error "buildTypeAction Custom"
buildTypeAction (UnknownBuildType _) = error "buildTypeAction UnknownBuildType"
-- ------------------------------------------------------------
-- * External SetupMethod
-- ------------------------------------------------------------
externalSetupMethod :: SetupMethod
externalSetupMethod verbosity options pkg bt mkargs = do
debug verbosity $ "Using external setup method with build-type " ++ show bt
createDirectoryIfMissingVerbose verbosity True setupDir
(cabalLibVersion, options') <- cabalLibVersionToUse
debug verbosity $ "Using Cabal library version " ++ display cabalLibVersion
setupHs <- updateSetupScript cabalLibVersion bt
debug verbosity $ "Using " ++ setupHs ++ " as setup script."
compileSetupExecutable options' cabalLibVersion setupHs
invokeSetupScript (mkargs cabalLibVersion)
where
workingDir = case fromMaybe "" (useWorkingDir options) of
[] -> "."
dir -> dir
setupDir = workingDir </> useDistPref options </> "setup"
setupVersionFile = setupDir </> "setup" <.> "version"
setupProgFile = setupDir </> "setup" <.> exeExtension
cabalLibVersionToUse :: IO (Version, SetupScriptOptions)
cabalLibVersionToUse = do
savedVersion <- savedCabalVersion
case savedVersion of
Just version | version `withinRange` useCabalVersion options
-> return (version, options)
_ -> do (comp, conf, options') <- configureCompiler options
version <- installedCabalVersion options comp conf
writeFile setupVersionFile (show version ++ "\n")
return (version, options')
savedCabalVersion = do
versionString <- readFile setupVersionFile `catch` \_ -> return ""
case reads versionString of
[(version,s)] | all isSpace s -> return (Just version)
_ -> return Nothing
installedCabalVersion :: SetupScriptOptions -> Compiler
-> ProgramConfiguration -> IO Version
installedCabalVersion _ _ _ | packageName pkg == PackageName "Cabal" =
return (packageVersion pkg)
installedCabalVersion options' comp conf = do
index <- case usePackageIndex options' of
Just index -> return index
Nothing -> getInstalledPackages verbosity
comp (usePackageDB options') conf
let cabalDep = Dependency (PackageName "Cabal") (useCabalVersion options)
case PackageIndex.lookupDependency index cabalDep of
[] -> die $ "The package requires Cabal library version "
++ display (useCabalVersion options)
++ " but no suitable version is installed."
pkgs -> return $ bestVersion (map packageVersion pkgs)
where
bestVersion = maximumBy (comparing preference)
preference version = (sameVersion, sameMajorVersion
,stableVersion, latestVersion)
where
sameVersion = version == cabalVersion
sameMajorVersion = majorVersion version == majorVersion cabalVersion
majorVersion = take 2 . versionBranch
stableVersion = case versionBranch version of
(_:x:_) -> even x
_ -> False
latestVersion = version
configureCompiler :: SetupScriptOptions
-> IO (Compiler, ProgramConfiguration, SetupScriptOptions)
configureCompiler options' = do
(comp, conf) <- case useCompiler options' of
Just comp -> return (comp, useProgramConfig options')
Nothing -> configCompiler (Just GHC) Nothing Nothing
(useProgramConfig options') verbosity
return (comp, conf, options' { useCompiler = Just comp,
useProgramConfig = conf })
-- | Decide which Setup.hs script to use, creating it if necessary.
--
updateSetupScript :: Version -> BuildType -> IO FilePath
updateSetupScript _ Custom = do
useHs <- doesFileExist setupHs
useLhs <- doesFileExist setupLhs
unless (useHs || useLhs) $ die
"Using 'build-type: Custom' but there is no Setup.hs or Setup.lhs script."
return (if useHs then setupHs else setupLhs)
where
setupHs = workingDir </> "Setup.hs"
setupLhs = workingDir </> "Setup.lhs"
updateSetupScript cabalLibVersion _ = do
rewriteFile setupHs (buildTypeScript cabalLibVersion)
return setupHs
where
setupHs = setupDir </> "setup.hs"
buildTypeScript :: Version -> String
buildTypeScript cabalLibVersion = case bt of
Simple -> "import Distribution.Simple; main = defaultMain\n"
Configure -> "import Distribution.Simple; main = defaultMainWithHooks "
++ if cabalLibVersion >= Version [1,3,10] []
then "autoconfUserHooks\n"
else "defaultUserHooks\n"
Make -> "import Distribution.Make; main = defaultMain\n"
Custom -> error "buildTypeScript Custom"
UnknownBuildType _ -> error "buildTypeScript UnknownBuildType"
-- | If the Setup.hs is out of date wrt the executable then recompile it.
-- Currently this is GHC only. It should really be generalised.
--
compileSetupExecutable :: SetupScriptOptions -> Version -> FilePath -> IO ()
compileSetupExecutable options' cabalLibVersion setupHsFile = do
setupHsNewer <- setupHsFile `moreRecentFile` setupProgFile
cabalVersionNewer <- setupVersionFile `moreRecentFile` setupProgFile
let outOfDate = setupHsNewer || cabalVersionNewer
when outOfDate $ do
debug verbosity "Setup script is out of date, compiling..."
(_, conf, _) <- configureCompiler options'
--TODO: get Cabal's GHC module to export a GhcOptions type and render func
rawSystemProgramConf verbosity ghcProgram conf $
ghcVerbosityOptions verbosity
++ ["--make", setupHsFile, "-o", setupProgFile
,"-odir", setupDir, "-hidir", setupDir
,"-i", "-i" ++ workingDir ]
++ ghcPackageDbOptions (usePackageDB options')
++ if packageName pkg == PackageName "Cabal"
then []
else ["-package", display cabalPkgid]
where
cabalPkgid = PackageIdentifier (PackageName "Cabal") cabalLibVersion
ghcPackageDbOptions :: PackageDBStack -> [String]
ghcPackageDbOptions dbstack = case dbstack of
(GlobalPackageDB:UserPackageDB:dbs) -> concatMap specific dbs
(GlobalPackageDB:dbs) -> "-no-user-package-conf"
: concatMap specific dbs
_ -> ierror
where
specific (SpecificPackageDB db) = [ "-package-conf", db ]
specific _ = ierror
ierror = error "internal error: unexpected package db stack"
invokeSetupScript :: [String] -> IO ()
invokeSetupScript args = do
info verbosity $ unwords (setupProgFile : args)
case useLoggingHandle options of
Nothing -> return ()
Just logHandle -> info verbosity $ "Redirecting build log to "
++ show logHandle
currentDir <- getCurrentDirectory
process <- runProcess (currentDir </> setupProgFile) args
(useWorkingDir options) Nothing
Nothing (useLoggingHandle options) (useLoggingHandle options)
exitCode <- waitForProcess process
unless (exitCode == ExitSuccess) $ exitWith exitCode
|
yihuang/cabal-install
|
Distribution/Client/SetupWrapper.hs
|
bsd-3-clause
| 13,810
| 0
| 17
| 3,547
| 2,799
| 1,482
| 1,317
| 250
| 21
|
module ImageQuery.Printer where
import ImageQuery (
ImageQueryStatement(SetImageQueryParameter,GetImageQueryResult),
ImageQueryParameter(Threshold,Channel,Smoothing,SubRect,StencilImage,Polarity),
ImageQuery(TableQuery,IslandImage,ImageOfAverage,LineImage,AreaHistogram),
TableQuery(ValueInPoint,AverageAroundPoint,AverageOfImage,IslandQuery),
IslandQuery(NumberOfIslands,AverageAreaOfIslands,AverageOutlineOfIslands),
Polarity(Bright,Dark),
Orientation(Horizontal,Vertical),
Channel(Red,Green,Blue),
Power(One,OneOverTwo,ThreeOverTwo))
type Printer a = a -> String
imageQueriesPrinter :: Printer [ImageQueryStatement]
imageQueriesPrinter = unlines . map imageQueryStatementPrinter
imageQueryStatementPrinter :: Printer ImageQueryStatement
imageQueryStatementPrinter (SetImageQueryParameter imagequeryparameter) =
imageQueryParameterPrinter imagequeryparameter
imageQueryStatementPrinter (GetImageQueryResult imagequery) =
imageQueryPrinter imagequery
imageQueryParameterPrinter :: Printer ImageQueryParameter
imageQueryParameterPrinter (Threshold threshold) = "set_threshold " ++ show threshold
imageQueryParameterPrinter (Channel channel) = "set_channel " ++ channelPrinter channel
imageQueryParameterPrinter (Smoothing smoothing) = "set_smoothing " ++ show smoothing
imageQueryParameterPrinter (SubRect (x,y,w,h)) = "set_subrect " ++ numbersPrinter [x,y,w,h]
imageQueryParameterPrinter (StencilImage filepath _) = "set_stencil " ++ filepath
imageQueryParameterPrinter (Polarity polarity) = "set_polarity " ++ polarityPrinter polarity
imageQueryPrinter :: Printer ImageQuery
imageQueryPrinter (TableQuery tablequery) = tableQueryPrinter tablequery
imageQueryPrinter ImageOfAverage = "output_average_image"
imageQueryPrinter (LineImage orientation x y l) =
"output_line_image " ++ orientationPrinter orientation ++ " " ++ numbersPrinter [x,y,l]
imageQueryPrinter IslandImage = "output_island_images"
imageQueryPrinter (AreaHistogram binsize power) = unwords [
"output_area_histogram",show binsize,powerPrinter power]
tableQueryPrinter :: Printer TableQuery
tableQueryPrinter (ValueInPoint x y) = "table_value_in_point " ++ numbersPrinter [x,y]
tableQueryPrinter (AverageAroundPoint x y r) = "table_average_around_point " ++ numbersPrinter [x,y,r]
tableQueryPrinter AverageOfImage = "table_average_of_image"
tableQueryPrinter (IslandQuery NumberOfIslands) =
"table_number_of_islands"
tableQueryPrinter (IslandQuery AverageAreaOfIslands) =
"table_average_area_of_islands"
tableQueryPrinter (IslandQuery AverageOutlineOfIslands) =
"table_average_outline_of_islands"
orientationPrinter :: Printer Orientation
orientationPrinter Horizontal = "horizontal"
orientationPrinter Vertical = "vertical"
polarityPrinter :: Printer Polarity
polarityPrinter Bright = "bright"
polarityPrinter Dark = "dark"
numbersPrinter :: Printer [Int]
numbersPrinter = unwords . map show
channelPrinter :: Printer Channel
channelPrinter Red = "red"
channelPrinter Green = "green"
channelPrinter Blue = "blue"
powerPrinter :: Printer Power
powerPrinter One = "one"
powerPrinter OneOverTwo = "one_over_two"
powerPrinter ThreeOverTwo = "three_over_two"
|
phischu/pem-images
|
src/ImageQuery/Printer.hs
|
bsd-3-clause
| 3,200
| 0
| 8
| 340
| 727
| 404
| 323
| 60
| 1
|
module Main where
import Data.IORef
import Data.Time.Clock
import Control.Concurrent.ParallelIO.Global
n :: Int
n = 1000000
main :: IO ()
main = do
r <- newIORef (0 :: Int)
let incRef = atomicModifyIORef r (\a -> (a, a))
time $ parallel_ $ replicate n $ incRef
v <- readIORef r
stopGlobalPool
print v
time :: IO a -> IO a
time action = do
start <- getCurrentTime
result <- action
stop <- getCurrentTime
print $ stop `diffUTCTime` start
return result
|
batterseapower/parallel-io
|
Control/Concurrent/ParallelIO/Benchmark.hs
|
bsd-3-clause
| 499
| 0
| 13
| 128
| 191
| 96
| 95
| 21
| 1
|
--
--
--
----------------
-- Exercise 7.8.
----------------
--
--
--
module E'7''8 where
import Test.QuickCheck
elemNum :: Integer -> [Integer] -> Integer
elemNum _ [] = 0
elemNum referenceInteger (integer : remainingIntegers)
| integer /= referenceInteger = (elemNum referenceInteger remainingIntegers)
| otherwise = 1 + (elemNum referenceInteger remainingIntegers)
{- GHCi>
elemNum 1 []
elemNum 1 [ 0 , 0 , 0 ]
elemNum 1 [ 0 , 0 , 1 ]
elemNum 1 [ 0 , 1 , 0 ]
elemNum 1 [ 0 , 1 , 1 ]
elemNum 1 [ 1 , 0 , 0 ]
elemNum 1 [ 1 , 0 , 1 ]
elemNum 1 [ 1 , 1 , 0 ]
elemNum 1 [ 1 , 1 , 1 ]
-}
-- 0
-- 0
-- 1
-- 1
-- 2
-- 1
-- 2
-- 2
-- 3
elemNum' :: Integer -> [Integer] -> Integer
elemNum' referenceInteger integerList
= sum [ 1 | integer <- integerList , integer == referenceInteger ]
prop_elemNum :: Integer -> [Integer] -> Bool
prop_elemNum integer integerList
= elemNum integer integerList == elemNum' integer integerList
{- GHCi>
quickCheck prop_elemNum
-}
-- Other solution for "elemNum":
elemNum'3 :: Integer -> [Integer] -> Integer
elemNum'3 referenceInteger integerList
= toInteger (length [ 1 | integer <- integerList , integer == referenceInteger ])
prop_elemNum'3 :: Integer -> [Integer] -> Bool
prop_elemNum'3 integer integerList
= elemNum integer integerList == elemNum'3 integer integerList
{- GHCi>
quickCheck prop_elemNum'3
-}
|
pascal-knodel/haskell-craft
|
_/links/E'7''8.hs
|
mit
| 1,413
| 0
| 10
| 320
| 297
| 163
| 134
| 19
| 1
|
module AssignTypes where
import Types
import Obj
import Util
import TypeError
import Data.List (nub)
import qualified Data.Map as Map
import Debug.Trace
{-# ANN assignTypes "HLint: ignore Eta reduce" #-}
-- | Walk the whole expression tree and replace all occurences of VarTy with their corresponding actual type.
assignTypes :: TypeMappings -> XObj -> Either TypeError XObj
assignTypes mappings root = visit root
where
visit xobj =
case obj xobj of
(Lst _) -> visitList xobj
(Arr _) -> visitArray xobj
_ -> assignType xobj
visitList :: XObj -> Either TypeError XObj
visitList (XObj (Lst xobjs) i t) =
do visited <- mapM (assignTypes mappings) xobjs
let xobj' = XObj (Lst visited) i t
assignType xobj'
visitList _ = error "The function 'visitList' only accepts XObjs with lists in them."
visitArray :: XObj -> Either TypeError XObj
visitArray (XObj (Arr xobjs) i t) =
do visited <- mapM (assignTypes mappings) xobjs
let xobj' = XObj (Arr visited) i t
assignType xobj'
visitArray _ = error "The function 'visitArray' only accepts XObjs with arrays in them."
assignType :: XObj -> Either TypeError XObj
assignType xobj = case ty xobj of
Just startingType ->
let finalType = replaceTyVars mappings startingType
in if isArrayTypeOK finalType
then Right (xobj { ty = Just finalType })
else Left (ArraysCannotContainRefs xobj)
Nothing -> return xobj
isArrayTypeOK :: Ty -> Bool
isArrayTypeOK (StructTy "Array" [RefTy _]) = False -- An array containing refs!
isArrayTypeOK _ = True
-- | Change auto generated type names (i.e. 't0') to letters (i.e. 'a', 'b', 'c', etc...)
-- | TODO: Only change variables that are machine generated.
beautifyTypeVariables :: XObj -> Either TypeError XObj
beautifyTypeVariables root =
let Just t = ty root
tys = nub (typeVariablesInOrderOfAppearance t)
mappings = Map.fromList (zip (map (\(VarTy name) -> name) tys)
(map (VarTy . (:[])) ['a'..]))
in assignTypes mappings root
typeVariablesInOrderOfAppearance :: Ty -> [Ty]
typeVariablesInOrderOfAppearance (FuncTy argTys retTy) =
concatMap typeVariablesInOrderOfAppearance argTys ++ typeVariablesInOrderOfAppearance retTy
typeVariablesInOrderOfAppearance (StructTy _ typeArgs) =
concatMap typeVariablesInOrderOfAppearance typeArgs
typeVariablesInOrderOfAppearance (RefTy innerTy) =
typeVariablesInOrderOfAppearance innerTy
typeVariablesInOrderOfAppearance (PointerTy innerTy) =
typeVariablesInOrderOfAppearance innerTy
typeVariablesInOrderOfAppearance t@(VarTy _) =
[t]
typeVariablesInOrderOfAppearance _ =
[]
|
eriksvedang/Carp
|
src/AssignTypes.hs
|
mpl-2.0
| 2,730
| 0
| 17
| 595
| 708
| 352
| 356
| 59
| 7
|
{-# 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.MachineLearning.CreateBatchPrediction
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Generates predictions for a group of observations. The observations to
-- process exist in one or more data files referenced by a 'DataSource'.
-- This operation creates a new 'BatchPrediction', and uses an 'MLModel'
-- and the data files referenced by the 'DataSource' as information
-- sources.
--
-- 'CreateBatchPrediction' is an asynchronous operation. In response to
-- 'CreateBatchPrediction', Amazon Machine Learning (Amazon ML) immediately
-- returns and sets the 'BatchPrediction' status to 'PENDING'. After the
-- 'BatchPrediction' completes, Amazon ML sets the status to 'COMPLETED'.
--
-- You can poll for status updates by using the GetBatchPrediction
-- operation and checking the 'Status' parameter of the result. After the
-- 'COMPLETED' status appears, the results are available in the location
-- specified by the 'OutputUri' parameter.
--
-- /See:/ <http://http://docs.aws.amazon.com/machine-learning/latest/APIReference/API_CreateBatchPrediction.html AWS API Reference> for CreateBatchPrediction.
module Network.AWS.MachineLearning.CreateBatchPrediction
(
-- * Creating a Request
createBatchPrediction
, CreateBatchPrediction
-- * Request Lenses
, cbpBatchPredictionName
, cbpBatchPredictionId
, cbpMLModelId
, cbpBatchPredictionDataSourceId
, cbpOutputURI
-- * Destructuring the Response
, createBatchPredictionResponse
, CreateBatchPredictionResponse
-- * Response Lenses
, cbprsBatchPredictionId
, cbprsResponseStatus
) where
import Network.AWS.MachineLearning.Types
import Network.AWS.MachineLearning.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'createBatchPrediction' smart constructor.
data CreateBatchPrediction = CreateBatchPrediction'
{ _cbpBatchPredictionName :: !(Maybe Text)
, _cbpBatchPredictionId :: !Text
, _cbpMLModelId :: !Text
, _cbpBatchPredictionDataSourceId :: !Text
, _cbpOutputURI :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateBatchPrediction' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cbpBatchPredictionName'
--
-- * 'cbpBatchPredictionId'
--
-- * 'cbpMLModelId'
--
-- * 'cbpBatchPredictionDataSourceId'
--
-- * 'cbpOutputURI'
createBatchPrediction
:: Text -- ^ 'cbpBatchPredictionId'
-> Text -- ^ 'cbpMLModelId'
-> Text -- ^ 'cbpBatchPredictionDataSourceId'
-> Text -- ^ 'cbpOutputURI'
-> CreateBatchPrediction
createBatchPrediction pBatchPredictionId_ pMLModelId_ pBatchPredictionDataSourceId_ pOutputURI_ =
CreateBatchPrediction'
{ _cbpBatchPredictionName = Nothing
, _cbpBatchPredictionId = pBatchPredictionId_
, _cbpMLModelId = pMLModelId_
, _cbpBatchPredictionDataSourceId = pBatchPredictionDataSourceId_
, _cbpOutputURI = pOutputURI_
}
-- | A user-supplied name or description of the 'BatchPrediction'.
-- 'BatchPredictionName' can only use the UTF-8 character set.
cbpBatchPredictionName :: Lens' CreateBatchPrediction (Maybe Text)
cbpBatchPredictionName = lens _cbpBatchPredictionName (\ s a -> s{_cbpBatchPredictionName = a});
-- | A user-supplied ID that uniquely identifies the 'BatchPrediction'.
cbpBatchPredictionId :: Lens' CreateBatchPrediction Text
cbpBatchPredictionId = lens _cbpBatchPredictionId (\ s a -> s{_cbpBatchPredictionId = a});
-- | The ID of the 'MLModel' that will generate predictions for the group of
-- observations.
cbpMLModelId :: Lens' CreateBatchPrediction Text
cbpMLModelId = lens _cbpMLModelId (\ s a -> s{_cbpMLModelId = a});
-- | The ID of the 'DataSource' that points to the group of observations to
-- predict.
cbpBatchPredictionDataSourceId :: Lens' CreateBatchPrediction Text
cbpBatchPredictionDataSourceId = lens _cbpBatchPredictionDataSourceId (\ s a -> s{_cbpBatchPredictionDataSourceId = a});
-- | The location of an Amazon Simple Storage Service (Amazon S3) bucket or
-- directory to store the batch prediction results. The following
-- substrings are not allowed in the s3 key portion of the \"outputURI\"
-- field: \':\', \'\/\/\', \'\/.\/\', \'\/..\/\'.
--
-- Amazon ML needs permissions to store and retrieve the logs on your
-- behalf. For information about how to set permissions, see the
-- <http://docs.aws.amazon.com/machine-learning/latest/dg Amazon Machine Learning Developer Guide>.
cbpOutputURI :: Lens' CreateBatchPrediction Text
cbpOutputURI = lens _cbpOutputURI (\ s a -> s{_cbpOutputURI = a});
instance AWSRequest CreateBatchPrediction where
type Rs CreateBatchPrediction =
CreateBatchPredictionResponse
request = postJSON machineLearning
response
= receiveJSON
(\ s h x ->
CreateBatchPredictionResponse' <$>
(x .?> "BatchPredictionId") <*> (pure (fromEnum s)))
instance ToHeaders CreateBatchPrediction where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("AmazonML_20141212.CreateBatchPrediction" ::
ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON CreateBatchPrediction where
toJSON CreateBatchPrediction'{..}
= object
(catMaybes
[("BatchPredictionName" .=) <$>
_cbpBatchPredictionName,
Just ("BatchPredictionId" .= _cbpBatchPredictionId),
Just ("MLModelId" .= _cbpMLModelId),
Just
("BatchPredictionDataSourceId" .=
_cbpBatchPredictionDataSourceId),
Just ("OutputUri" .= _cbpOutputURI)])
instance ToPath CreateBatchPrediction where
toPath = const "/"
instance ToQuery CreateBatchPrediction where
toQuery = const mempty
-- | Represents the output of a CreateBatchPrediction operation, and is an
-- acknowledgement that Amazon ML received the request.
--
-- The CreateBatchPrediction operation is asynchronous. You can poll for
-- status updates by using the GetBatchPrediction operation and checking
-- the 'Status' parameter of the result.
--
-- /See:/ 'createBatchPredictionResponse' smart constructor.
data CreateBatchPredictionResponse = CreateBatchPredictionResponse'
{ _cbprsBatchPredictionId :: !(Maybe Text)
, _cbprsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateBatchPredictionResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cbprsBatchPredictionId'
--
-- * 'cbprsResponseStatus'
createBatchPredictionResponse
:: Int -- ^ 'cbprsResponseStatus'
-> CreateBatchPredictionResponse
createBatchPredictionResponse pResponseStatus_ =
CreateBatchPredictionResponse'
{ _cbprsBatchPredictionId = Nothing
, _cbprsResponseStatus = pResponseStatus_
}
-- | A user-supplied ID that uniquely identifies the 'BatchPrediction'. This
-- value is identical to the value of the 'BatchPredictionId' in the
-- request.
cbprsBatchPredictionId :: Lens' CreateBatchPredictionResponse (Maybe Text)
cbprsBatchPredictionId = lens _cbprsBatchPredictionId (\ s a -> s{_cbprsBatchPredictionId = a});
-- | The response status code.
cbprsResponseStatus :: Lens' CreateBatchPredictionResponse Int
cbprsResponseStatus = lens _cbprsResponseStatus (\ s a -> s{_cbprsResponseStatus = a});
|
fmapfmapfmap/amazonka
|
amazonka-ml/gen/Network/AWS/MachineLearning/CreateBatchPrediction.hs
|
mpl-2.0
| 8,385
| 0
| 13
| 1,675
| 929
| 563
| 366
| 119
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.OpsWorks.AssignVolume
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Assigns one of the stack's registered Amazon EBS volumes to a specified
-- instance. The volume must first be registered with the stack by calling 'RegisterVolume'. After you register the volume, you must call 'UpdateVolume' to specify a
-- mount point before calling 'AssignVolume'. For more information, see <http://docs.aws.amazon.com/opsworks/latest/userguide/resources.html ResourceManagement>.
--
-- Required Permissions: To use this action, an IAM user must have a Manage
-- permissions level for the stack, or an attached policy that explicitly grants
-- permissions. For more information on user permissions, see <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing UserPermissions>.
--
-- <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_AssignVolume.html>
module Network.AWS.OpsWorks.AssignVolume
(
-- * Request
AssignVolume
-- ** Request constructor
, assignVolume
-- ** Request lenses
, avInstanceId
, avVolumeId
-- * Response
, AssignVolumeResponse
-- ** Response constructor
, assignVolumeResponse
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.OpsWorks.Types
import qualified GHC.Exts
data AssignVolume = AssignVolume
{ _avInstanceId :: Maybe Text
, _avVolumeId :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'AssignVolume' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'avInstanceId' @::@ 'Maybe' 'Text'
--
-- * 'avVolumeId' @::@ 'Text'
--
assignVolume :: Text -- ^ 'avVolumeId'
-> AssignVolume
assignVolume p1 = AssignVolume
{ _avVolumeId = p1
, _avInstanceId = Nothing
}
-- | The instance ID.
avInstanceId :: Lens' AssignVolume (Maybe Text)
avInstanceId = lens _avInstanceId (\s a -> s { _avInstanceId = a })
-- | The volume ID.
avVolumeId :: Lens' AssignVolume Text
avVolumeId = lens _avVolumeId (\s a -> s { _avVolumeId = a })
data AssignVolumeResponse = AssignVolumeResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'AssignVolumeResponse' constructor.
assignVolumeResponse :: AssignVolumeResponse
assignVolumeResponse = AssignVolumeResponse
instance ToPath AssignVolume where
toPath = const "/"
instance ToQuery AssignVolume where
toQuery = const mempty
instance ToHeaders AssignVolume
instance ToJSON AssignVolume where
toJSON AssignVolume{..} = object
[ "VolumeId" .= _avVolumeId
, "InstanceId" .= _avInstanceId
]
instance AWSRequest AssignVolume where
type Sv AssignVolume = OpsWorks
type Rs AssignVolume = AssignVolumeResponse
request = post "AssignVolume"
response = nullResponse AssignVolumeResponse
|
romanb/amazonka
|
amazonka-opsworks/gen/Network/AWS/OpsWorks/AssignVolume.hs
|
mpl-2.0
| 3,798
| 0
| 9
| 787
| 428
| 261
| 167
| 54
| 1
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="hu-HU">
<title>Ruby Scripting</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Keresés</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
veggiespam/zap-extensions
|
addOns/jruby/src/main/javahelp/org/zaproxy/zap/extension/jruby/resources/help_hu_HU/helpset_hu_HU.hs
|
apache-2.0
| 962
| 84
| 52
| 157
| 395
| 208
| 187
| -1
| -1
|
-- | Server methods to do user authentication.
--
-- We authenticate clients using HTTP Basic or Digest authentication and we
-- authorise users based on membership of particular user groups.
--
{-# LANGUAGE PatternGuards #-}
module Distribution.Server.Framework.Auth (
-- * Checking authorisation
guardAuthorised,
-- ** Realms
RealmName,
hackageRealm,
adminRealm,
-- ** Creating password hashes
newPasswdHash,
UserName,
PasswdPlain,
PasswdHash,
-- ** Special cases
guardAuthenticated,
guardPriviledged,
-- * deprecatged
withHackageAuth
) where
import Distribution.Server.Users.Types (UserId, UserName(..), UserAuth(..), UserInfo(userName))
import qualified Distribution.Server.Users.Types as Users
import qualified Distribution.Server.Users.Users as Users
import qualified Distribution.Server.Users.Group as Group
import qualified Distribution.Server.Framework.ResourceTypes as Resource
import Distribution.Server.Framework.AuthCrypt
import Distribution.Server.Framework.AuthTypes
import Distribution.Server.Framework.Error
import Distribution.Server.Pages.Template (hackagePage)
import Distribution.Server.Pages.Util (makeInput)
import Distribution.Server.Util.Happstack (rqRealMethod)
import Distribution.Server.Util.ContentType
import Distribution.Text (display)
import Happstack.Server
import qualified Happstack.Crypto.Base64 as Base64
import Control.Monad.Trans (MonadIO, liftIO)
import qualified Data.ByteString.Char8 as BS
import Text.XHtml.Table (simpleTable)
import Text.XHtml.Strict
import qualified Text.XHtml.Strict as XHtml
import Control.Monad (guard, join, liftM2, mzero)
import Control.Monad.Error.Class (Error, noMsg)
import Data.Char (intToDigit, isAsciiLower)
import System.Random (randomRs, newStdGen)
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Text.ParserCombinators.ReadP as Parse
import Data.Maybe (listToMaybe)
import Data.List (intercalate)
------------------------------------------------------------------------
-- The old deprecated interface
--
{-# DEPRECATED withHackageAuth "use guardAuthorised instead" #-}
withHackageAuth :: Users.Users -> Maybe Group.UserList
-> (UserId -> UserInfo -> ServerPartE a) -> ServerPartE a
withHackageAuth users mgroup action = do
(uid, uinfo) <- guardAuthenticated hackageRealm users
maybe (return ()) (\group -> guardPriviledged group uid) mgroup
action uid uinfo
------------------------------------------------------------------------
-- Main auth methods
--
hackageRealm, adminRealm :: RealmName
hackageRealm = RealmName "Hackage"
adminRealm = RealmName "Hackage admin"
-- | Check that the client is authenticated and is authorised to perform some
-- priviledged action.
--
-- We check that:
--
-- * the client has supplied appropriate authentication credentials for a
-- known enabled user account;
-- * is a member of a given group of users who are permitted to perform
-- certain priviledged actions.
--
guardAuthorised :: RealmName -> Users.Users -> Group.UserList
-> ServerPartE (UserId, UserInfo)
guardAuthorised realm users group = do
(uid, uinfo) <- guardAuthenticated realm users
guardPriviledged group uid
return (uid, uinfo)
-- | Check that the client is authenticated. Returns the information about the
-- user account that the client authenticates as.
--
-- This checks the client has supplied appropriate authentication credentials
-- for a known enabled user account.
--
-- It only checks the user is known, it does not imply that the user is
-- authorised to do anything in particular, see 'guardAuthorised'.
--
guardAuthenticated :: RealmName -> Users.Users -> ServerPartE (UserId, UserInfo)
guardAuthenticated realm users = do
req <- askRq
either (authError realm) return $
case getHeaderAuth req of
Just (BasicAuth, ahdr) -> checkBasicAuth users realm ahdr
Just (DigestAuth, ahdr) -> checkDigestAuth users ahdr req
Nothing -> Left NoAuthError
where
getHeaderAuth :: Request -> Maybe (AuthType, BS.ByteString)
getHeaderAuth req =
case getHeader "authorization" req of
Just hdr
| BS.isPrefixOf (BS.pack "Digest ") hdr
-> Just (DigestAuth, BS.drop 7 hdr)
| BS.isPrefixOf (BS.pack "Basic ") hdr
-> Just (BasicAuth, BS.drop 6 hdr)
_ -> Nothing
data AuthType = BasicAuth | DigestAuth
-- | Check that a given user is permitted to perform certain priviledged
-- actions.
--
-- This is based on whether the user is a mamber of a particular group of
-- priviledged users.
--
-- It only checks if the user is in the priviledged user group, it does not
-- imply that the current client has been authenticated, see 'guardAuthorised'.
--
guardPriviledged :: Group.UserList -> UserId -> ServerPartE ()
guardPriviledged ugroup uid
| Group.member uid ugroup = return ()
| otherwise = errForbidden "Forbidden" [MText "No access for this page."]
------------------------------------------------------------------------
-- Basic auth method
--
-- | Use HTTP Basic auth to authenticate the client as an active enabled user.
--
checkBasicAuth :: Users.Users -> RealmName -> BS.ByteString
-> Either AuthError (UserId, UserInfo)
checkBasicAuth users realm ahdr = do
authInfo <- getBasicAuthInfo realm ahdr ?! UnrecognizedAuthError
let uname = basicUsername authInfo
uid <- Users.lookupName uname users ?! NoSuchUserError
uinfo <- Users.lookupId uid users ?! NoSuchUserError
uauth <- getUserAuth uinfo ?! NoSuchUserError
passwdhash <- getPasswdHash uauth ?! OldAuthError (userName uinfo)
guard (checkBasicAuthInfo passwdhash authInfo) ?! PasswordMismatchError
return (uid, uinfo)
getBasicAuthInfo :: RealmName -> BS.ByteString -> Maybe BasicAuthInfo
getBasicAuthInfo realm authHeader
| (name, ':':pass) <- splitHeader authHeader
= Just BasicAuthInfo {
basicRealm = realm,
basicUsername = UserName name,
basicPasswd = PasswdPlain pass
}
| otherwise = Nothing
where
splitHeader = break (':'==) . Base64.decode . BS.unpack
setBasicAuthChallenge :: RealmName -> ServerPartE ()
setBasicAuthChallenge (RealmName realmName) = do
addHeaderM headerName headerValue
where
headerName = "WWW-Authenticate"
headerValue = "Basic realm=\"" ++ realmName ++ "\""
------------------------------------------------------------------------
-- Digest auth method
--
-- See RFC 2617 http://www.ietf.org/rfc/rfc2617
-- Digest auth TODO:
-- * support domain for the protection space (otherwise defaults to whole server)
-- * nonce generation is not ideal: consists just of a random number
-- * nonce is not checked
-- * opaque is not used
-- | Use HTTP Digest auth to authenticate the client as an active enabled user.
--
checkDigestAuth :: Users.Users -> BS.ByteString -> Request
-> Either AuthError (UserId, UserInfo)
checkDigestAuth users ahdr req = do
authInfo <- getDigestAuthInfo ahdr req ?! UnrecognizedAuthError
let uname = digestUsername authInfo
uid <- Users.lookupName uname users ?! NoSuchUserError
uinfo <- Users.lookupId uid users ?! NoSuchUserError
uauth <- getUserAuth uinfo ?! NoSuchUserError
passwdhash <- getPasswdHash uauth ?! OldAuthError (userName uinfo)
guard (checkDigestAuthInfo passwdhash authInfo) ?! PasswordMismatchError
-- TODO: if we want to prevent replay attacks, then we must check the
-- nonce and nonce count and issue stale=true replies.
return (uid, uinfo)
-- | retrieve the Digest auth info from the headers
--
getDigestAuthInfo :: BS.ByteString -> Request -> Maybe DigestAuthInfo
getDigestAuthInfo authHeader req = do
authMap <- parseDigestHeader authHeader
username <- Map.lookup "username" authMap
nonce <- Map.lookup "nonce" authMap
response <- Map.lookup "response" authMap
uri <- Map.lookup "uri" authMap
let mb_qop = Map.lookup "qop" authMap
qopInfo <- case mb_qop of
Just "auth" -> do
nc <- Map.lookup "nc" authMap
cnonce <- Map.lookup "cnonce" authMap
return (QopAuth nc cnonce)
Nothing -> return QopNone
_ -> mzero
return DigestAuthInfo {
digestUsername = UserName username,
digestNonce = nonce,
digestResponse = response,
digestURI = uri,
digestRqMethod = show (rqRealMethod req),
digestQoP = qopInfo
}
where
-- Parser derived from RFCs 2616 and 2617
parseDigestHeader :: BS.ByteString -> Maybe (Map String String)
parseDigestHeader =
fmap Map.fromList . parse . BS.unpack
where
parse :: String -> Maybe [(String, String)]
parse s = listToMaybe [ x | (x, "") <- Parse.readP_to_S parser s ]
parser :: Parse.ReadP [(String, String)]
parser = Parse.skipSpaces
>> Parse.sepBy1 nameValuePair
(Parse.skipSpaces >> Parse.char ',' >> Parse.skipSpaces)
nameValuePair = do
name <- Parse.munch1 isAsciiLower
Parse.char '='
value <- quotedString
return (name, value)
quotedString :: Parse.ReadP String
quotedString =
join Parse.between
(Parse.char '"')
(Parse.many $ (Parse.char '\\' >> Parse.get) Parse.<++ Parse.satisfy (/='"'))
Parse.<++ (liftM2 (:) (Parse.satisfy (/='"')) (Parse.munch (/=',')))
setDigestAuthChallenge :: RealmName -> ServerPartE ()
setDigestAuthChallenge (RealmName realmName) = do
nonce <- liftIO generateNonce
addHeaderM headerName (headerValue nonce)
where
headerName = "WWW-Authenticate"
-- Note that offering both qop=\"auth,auth-int\" can confuse some browsers
-- e.g. see http://code.google.com/p/chromium/issues/detail?id=45194
headerValue nonce =
"Digest " ++
intercalate ", "
[ "realm=" ++ quote realmName
, "qop=" ++ quote "auth"
, "nonce=" ++ quote nonce
, "opaque=" ++ quote ""
]
generateNonce = fmap (take 32 . map intToDigit . randomRs (0, 15)) newStdGen
quote s = '"' : s ++ ['"']
------------------------------------------------------------------------
-- Common
--
getUserAuth :: UserInfo -> Maybe UserAuth
getUserAuth userInfo =
case Users.userStatus userInfo of
Users.Active _ auth -> Just auth
_ -> Nothing
getPasswdHash :: UserAuth -> Maybe PasswdHash
getPasswdHash (NewUserAuth hash) = Just hash
getPasswdHash (OldUserAuth _) = Nothing
-- | The \"oh noes?!\" operator
--
(?!) :: Maybe a -> e -> Either e a
ma ?! e = maybe (Left e) Right ma
------------------------------------------------------------------------
-- Errors
--
authError :: RealmName -> AuthError -> ServerPartE a
authError realm err = do
-- we want basic first, but addHeaderM makes them come out reversed
setDigestAuthChallenge realm
setBasicAuthChallenge realm
req <- askRq
let accepts = maybe [] (parseContentAccept . BS.unpack) (getHeader "Accept" req)
want_text = foldr (\ct rest_want_text -> case ct of ContentType { ctType = "text", ctSubtype = st }
| st `elem` ["html", "xhtml"] -> False
| st == "plain" -> True
_ -> rest_want_text) True accepts
finishWith $ (showAuthError want_text (rqPeer req) err) {
rsCode = case err of
UnrecognizedAuthError -> 400
OldAuthError _ -> 403 -- Fits in that authenticating will make no difference...
_ -> 401
}
data AuthError = NoAuthError | UnrecognizedAuthError | NoSuchUserError
| PasswordMismatchError | OldAuthError UserName
deriving Show
instance Error AuthError where
noMsg = NoAuthError
showAuthError :: Bool -> Host -> AuthError -> Response
showAuthError want_text (hostname, port) err = case err of
NoAuthError -> toResponse "No authorization provided."
UnrecognizedAuthError -> toResponse "Authorization scheme not recognized."
NoSuchUserError -> toResponse "Username or password incorrect."
PasswordMismatchError -> toResponse "Username or password incorrect."
OldAuthError uname
| want_text -> toResponse $ "Hackage has been upgraded to use more secure passwords. You need login to Hackage and reenter your password at http://" ++ hostname ++ ":" ++ show port ++ rel_url
| otherwise -> toResponse $ Resource.XHtml $ hackagePage "Change password"
[ toHtml "You haven't logged in since Hackage was upgraded. Please reenter your password below to upgrade your account."
, form ! [theclass "box", XHtml.method "POST", action rel_url] <<
[ simpleTable [] []
[ makeInput [thetype "password"] "password" "Old password"
, makeInput [thetype "password"] "repeat-password" "Repeat old password"
]
, hidden "try-upgrade" "1"
, hidden "_method" "PUT" --method override
, paragraph << input ! [thetype "submit", value "Upgrade password"]
]
]
where rel_url = "/user/" ++ display uname ++ "/password"
|
isomorphism/hackage2
|
Distribution/Server/Framework/Auth.hs
|
bsd-3-clause
| 13,865
| 0
| 20
| 3,506
| 2,906
| 1,538
| 1,368
| 220
| 5
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Compare.JsonBuilder () where
import Prelude.Compat hiding ((<>))
import Data.Json.Builder
import Data.Monoid ((<>))
import Twitter
instance JsObject Metadata where
toObject Metadata{..} = row "result_type" result_type
instance Value Metadata where
toJson = toJson . toObject
instance JsObject Geo where
toObject Geo{..} =
row "type_" type_ <>
row "coordinates" coordinates
instance Value Geo where
toJson = toJson . toObject
instance Value a => Value (Maybe a) where
toJson (Just a) = toJson a
toJson Nothing = jsNull
instance JsObject Story where
toObject Story{..} =
row "from_user_id_str" from_user_id_str <>
row "profile_image_url" profile_image_url <>
row "created_at" created_at <>
row "from_user" from_user <>
row "id_str" id_str <>
row "metadata" metadata <>
row "to_user_id" to_user_id <>
row "text" text <>
row "id" id_ <>
row "from_user_id" from_user_id <>
row "geo" geo <>
row "iso_language_code" iso_language_code <>
row "to_user_id_str" to_user_id_str <>
row "source" source
instance Value Story where
toJson = toJson . toObject
instance JsObject Result where
toObject Result{..} =
row "results" results <>
row "max_id" max_id <>
row "since_id" since_id <>
row "refresh_url" refresh_url <>
row "next_page" next_page <>
row "results_per_page" results_per_page <>
row "page" page <>
row "completed_in" completed_in <>
row "since_id_str" since_id_str <>
row "max_id_str" max_id_str <>
row "query" query
instance Value Result where
toJson = toJson . toObject
|
dmjio/aeson
|
benchmarks/bench/Compare/JsonBuilder.hs
|
bsd-3-clause
| 1,815
| 0
| 19
| 409
| 485
| 239
| 246
| 55
| 0
|
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section{Haskell abstract syntax definition}
This module glues together the pieces of the Haskell abstract syntax,
which is declared in the various \tr{Hs*} modules. This module,
therefore, is almost nothing but re-exporting.
-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types]
-- in module PlaceHolder
{-# LANGUAGE ConstraintKinds #-}
module HsSyn (
module HsBinds,
module HsDecls,
module HsExpr,
module HsImpExp,
module HsLit,
module HsPat,
module HsTypes,
module HsUtils,
module HsDoc,
module PlaceHolder,
module HsExtension,
Fixity,
HsModule(..)
) where
-- friends:
import GhcPrelude
import HsDecls
import HsBinds
import HsExpr
import HsImpExp
import HsLit
import PlaceHolder
import HsExtension
import HsPat
import HsTypes
import BasicTypes ( Fixity, WarningTxt )
import HsUtils
import HsDoc
-- others:
import Outputable
import SrcLoc
import Module ( ModuleName )
-- libraries:
import Data.Data hiding ( Fixity )
-- | Haskell Module
--
-- All we actually declare here is the top-level structure for a module.
data HsModule name
= HsModule {
hsmodName :: Maybe (Located ModuleName),
-- ^ @Nothing@: \"module X where\" is omitted (in which case the next
-- field is Nothing too)
hsmodExports :: Maybe (Located [LIE name]),
-- ^ Export list
--
-- - @Nothing@: export list omitted, so export everything
--
-- - @Just []@: export /nothing/
--
-- - @Just [...]@: as you would expect...
--
--
-- - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnOpen'
-- ,'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
hsmodImports :: [LImportDecl name],
-- ^ We snaffle interesting stuff out of the imported interfaces early
-- on, adding that info to TyDecls/etc; so this list is often empty,
-- downstream.
hsmodDecls :: [LHsDecl name],
-- ^ Type, class, value, and interface signature decls
hsmodDeprecMessage :: Maybe (Located WarningTxt),
-- ^ reason\/explanation for warning/deprecation of this module
--
-- - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnOpen'
-- ,'ApiAnnotation.AnnClose'
--
-- For details on above see note [Api annotations] in ApiAnnotation
hsmodHaddockModHeader :: Maybe LHsDocString
-- ^ Haddock module info and description, unparsed
--
-- - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnOpen'
-- ,'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
}
-- ^ 'ApiAnnotation.AnnKeywordId's
--
-- - 'ApiAnnotation.AnnModule','ApiAnnotation.AnnWhere'
--
-- - 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnSemi',
-- 'ApiAnnotation.AnnClose' for explicit braces and semi around
-- hsmodImports,hsmodDecls if this style is used.
-- For details on above see note [Api annotations] in ApiAnnotation
deriving instance (DataId name) => Data (HsModule name)
instance (SourceTextX pass, OutputableBndrId pass)
=> Outputable (HsModule pass) where
ppr (HsModule Nothing _ imports decls _ mbDoc)
= pp_mb mbDoc $$ pp_nonnull imports
$$ pp_nonnull decls
ppr (HsModule (Just name) exports imports decls deprec mbDoc)
= vcat [
pp_mb mbDoc,
case exports of
Nothing -> pp_header (text "where")
Just es -> vcat [
pp_header lparen,
nest 8 (fsep (punctuate comma (map ppr (unLoc es)))),
nest 4 (text ") where")
],
pp_nonnull imports,
pp_nonnull decls
]
where
pp_header rest = case deprec of
Nothing -> pp_modname <+> rest
Just d -> vcat [ pp_modname, ppr d, rest ]
pp_modname = text "module" <+> ppr name
pp_mb :: Outputable t => Maybe t -> SDoc
pp_mb (Just x) = ppr x
pp_mb Nothing = empty
pp_nonnull :: Outputable t => [t] -> SDoc
pp_nonnull [] = empty
pp_nonnull xs = vcat (map ppr xs)
|
ezyang/ghc
|
compiler/hsSyn/HsSyn.hs
|
bsd-3-clause
| 4,681
| 0
| 21
| 1,447
| 666
| 385
| 281
| 71
| 1
|
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE EmptyDataDecls #-}
module Data.Streaming.Zlib.Lowlevel
( ZStreamStruct
, ZStream'
, zstreamNew
, Strategy(..)
, deflateInit2
, inflateInit2
, c_free_z_stream_inflate
, c_free_z_stream_deflate
, c_set_avail_in
, c_set_avail_out
, c_get_avail_out
, c_get_avail_in
, c_get_next_in
, c_call_inflate_noflush
, c_call_deflate_noflush
, c_call_deflate_finish
, c_call_deflate_flush
, c_call_deflate_full_flush
, c_call_deflate_set_dictionary
, c_call_inflate_set_dictionary
) where
import Foreign.C
import Foreign.Ptr
import Codec.Compression.Zlib (WindowBits (WindowBits))
data ZStreamStruct
type ZStream' = Ptr ZStreamStruct
data Strategy =
StrategyDefault
| StrategyFiltered
| StrategyHuffman
| StrategyRLE
| StrategyFixed
deriving (Show,Eq,Ord,Enum)
foreign import ccall unsafe "streaming_commons_create_z_stream"
zstreamNew :: IO ZStream'
foreign import ccall unsafe "streaming_commons_deflate_init2"
c_deflateInit2 :: ZStream' -> CInt -> CInt -> CInt -> CInt
-> IO ()
deflateInit2 :: ZStream' -> Int -> WindowBits -> Int -> Strategy -> IO ()
deflateInit2 zstream level windowBits memlevel strategy =
c_deflateInit2 zstream (fromIntegral level) (wbToInt windowBits)
(fromIntegral memlevel)
(fromIntegral $ fromEnum strategy)
foreign import ccall unsafe "streaming_commons_inflate_init2"
c_inflateInit2 :: ZStream' -> CInt -> IO ()
inflateInit2 :: ZStream' -> WindowBits -> IO ()
inflateInit2 zstream wb = c_inflateInit2 zstream (wbToInt wb)
foreign import ccall unsafe "&streaming_commons_free_z_stream_inflate"
c_free_z_stream_inflate :: FunPtr (ZStream' -> IO ())
foreign import ccall unsafe "&streaming_commons_free_z_stream_deflate"
c_free_z_stream_deflate :: FunPtr (ZStream' -> IO ())
foreign import ccall unsafe "streaming_commons_set_avail_in"
c_set_avail_in :: ZStream' -> Ptr CChar -> CUInt -> IO ()
foreign import ccall unsafe "streaming_commons_set_avail_out"
c_set_avail_out :: ZStream' -> Ptr CChar -> CUInt -> IO ()
foreign import ccall unsafe "streaming_commons_get_avail_out"
c_get_avail_out :: ZStream' -> IO CUInt
foreign import ccall unsafe "streaming_commons_get_avail_in"
c_get_avail_in :: ZStream' -> IO CUInt
foreign import ccall unsafe "streaming_commons_get_next_in"
c_get_next_in :: ZStream' -> IO (Ptr CChar)
foreign import ccall unsafe "streaming_commons_call_inflate_noflush"
c_call_inflate_noflush :: ZStream' -> IO CInt
foreign import ccall unsafe "streaming_commons_call_deflate_noflush"
c_call_deflate_noflush :: ZStream' -> IO CInt
foreign import ccall unsafe "streaming_commons_call_deflate_finish"
c_call_deflate_finish :: ZStream' -> IO CInt
foreign import ccall unsafe "streaming_commons_call_deflate_flush"
c_call_deflate_flush :: ZStream' -> IO CInt
foreign import ccall unsafe "streaming_commons_call_deflate_full_flush"
c_call_deflate_full_flush :: ZStream' -> IO CInt
foreign import ccall unsafe "streaming_commons_deflate_set_dictionary"
c_call_deflate_set_dictionary :: ZStream' -> Ptr CChar -> CUInt -> IO ()
foreign import ccall unsafe "streaming_commons_inflate_set_dictionary"
c_call_inflate_set_dictionary :: ZStream' -> Ptr CChar -> CUInt -> IO ()
wbToInt :: WindowBits -> CInt
wbToInt (WindowBits i) = fromIntegral i
wbToInt _ = 15
|
fpco/streaming-commons
|
Data/Streaming/Zlib/Lowlevel.hs
|
mit
| 3,501
| 0
| 12
| 626
| 760
| 407
| 353
| -1
| -1
|
{-# LANGUAGE TemplateHaskell, FlexibleInstances, MultiParamTypeClasses, PatternGuards #-}
--
-- Copyright (c) 2005-6 Don Stewart - http://www.cse.unsw.edu.au/~dons
-- GPL version 2 or later (see http://www.gnu.org/copyleft/gpl.html)
--
-- grab a random line of code from a directory full of .hs code
--
module Plugin.Code where
import Plugin
import Text.Regex
$(plugin "Code")
instance Module CodeModule [FilePath] where
moduleDefState _ = io $ getSourceFiles $
fptoolsPath config </> "libraries" </> "base"
moduleHelp _ _ = "code. Print random line of code from $fptools"
moduleCmds _ = ["code"]
process_ _ "code" _ = do
fs <- readMS
(file,line) <- liftIO $ do
f <- stdGetRandItem fs
h <- openFile f ReadMode
s <- hGetContents h
l <- getRandSrcOf (lines s) 1000 -- number of times to try
hClose h
return (f, (dropSpace . expandTab $ l))
-- dump raw output
return [basename file ++ ": " ++ line]
--
-- work out our list of potential source files
-- evil!
--
-- Going to be expensive at startup, no?
--
getSourceFiles :: FilePath -> IO [FilePath]
getSourceFiles d = do
(o,_,_) <- popen "/usr/bin/find" [d,"-name","*.hs","-o","-name","*.lhs"] Nothing
return (lines o)
-- give up:
getRandSrcOf :: [String] -> Int -> IO String
getRandSrcOf s 0 | s == [] = return []
| otherwise = return $ head s
-- otherwise get a random src line
getRandSrcOf ss n = do
s <- stdGetRandItem ss
case () of {_
| Just _ <- comment `matchRegex` s -> getRandSrcOf ss (n-1)
| Just _ <- ws `matchRegex` s -> getRandSrcOf ss (n-1)
| Just _ <- nl `matchRegex` s -> getRandSrcOf ss (n-1)
| Just _ <- pragma `matchRegex` s -> getRandSrcOf ss (n-1)
| Just _ <- imports `matchRegex` s -> getRandSrcOf ss (n-1)
| Just _ <- wheres `matchRegex` s -> getRandSrcOf ss (n-1)
| Just _ <- mods `matchRegex` s -> getRandSrcOf ss (n-1)
| Just _ <- nested `matchRegex` s -> getRandSrcOf ss (n-1)
| Just _ <- cpp `matchRegex` s -> getRandSrcOf ss (n-1)
| Just _ <- cpp' `matchRegex` s -> getRandSrcOf ss (n-1)
| length s < 30 -> getRandSrcOf ss (n-1)
| otherwise -> return s -- got it
}
where comment = mkRegex "--"
nested = mkRegex "{"
pragma = mkRegex "OPTION"
cpp = mkRegex "#if"
cpp' = mkRegex "#include"
ws = mkRegex "^ " -- line *must* start with an identifer
nl = mkRegex "\n"
imports = mkRegex "^import"
wheres = mkRegex "^ *where"
mods = mkRegex "module"
|
zeekay/lambdabot
|
Plugin/Code.hs
|
mit
| 2,985
| 0
| 16
| 1,077
| 873
| 440
| 433
| 52
| 1
|
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}
module Logic where
import Data.Dynamic as Dynamic
import Text.ParserCombinators.Parsec
-- the identity of a language
class (Show id, Typeable id) => Language id where
language_name :: id -> String
language_name = show
-- categories, needed for signatures and signature morphisms
class (Language id, Eq sign, Show sign, Eq morphism) =>
Category id sign morphism | id -> sign, id -> morphism where
identity :: id -> sign -> morphism
o :: id -> morphism -> morphism -> Maybe morphism
dom, cod :: id -> morphism -> sign
-- abstract syntax, parsing and printing
class (Language id, Show basic_spec, Eq basic_spec, Typeable basic_spec,
Show symbol_mapping, Eq symbol_mapping, Typeable symbol_mapping,
Show sentence, Eq sentence) =>
Syntax id sign sentence basic_spec symbol_mapping
| id -> sign, id -> basic_spec, id -> symbol_mapping, id -> sentence where
parse_basic_spec :: id -> CharParser st basic_spec
parse_symbol_mapping :: id -> CharParser st symbol_mapping
parse_sentence :: id -> sign -> String -> sentence
-- module Logic continued
-- a theory consists of a signature and a set of sentences
type Theory sign sentence = (sign, [sentence])
-- static analysis
class (Syntax id sign sentence basic_spec symbol_mapping,
Typeable sign, Typeable morphism, Typeable sentence) =>
StaticAnalysis id sign morphism sentence basic_spec symbol_mapping
| id -> morphism where
basic_analysis ::
id -> sign -> basic_spec -> Maybe (Theory sign sentence)
-- the input signature contains imported stuff
stat_symbol_mapping ::
id -> symbol_mapping -> sign -> Maybe morphism
-- Proofs
data Proof_status = Open | Disproved | Proved deriving Show
-- logic (entailment system)
class (Category id sign morphism,
StaticAnalysis id sign morphism sentence basic_spec symbol_mapping) =>
Logic id sign morphism sentence basic_spec symbol_mapping
where empty_signature :: id -> sign
empty_theory :: id -> Theory sign sentence
empty_theory i = (empty_signature i, [])
map_sentence :: id -> morphism -> sentence -> Maybe sentence
inv_map_sentence :: id -> morphism -> sentence -> Maybe sentence
prover :: id -> Theory sign sentence -- theory that shall be assumed
-> sentence -- the proof goal
-> IO Proof_status
-- logic translations
data Logic_translation id1 s1 m1 sen1 b1 sy1 id2 s2 m2 sen2 b2 sy2 =
Logic_translation { source :: id1,
target :: id2,
tr_sign :: s1 -> s2,
tr_mor :: m1 -> m2,
tr_sen :: s1 -> sen1 -> Maybe sen2,
inv_tr_sen :: s1 -> sen2 -> Maybe sen1 }
|
keithodulaigh/Hets
|
mini/Logic.hs
|
gpl-2.0
| 2,994
| 0
| 12
| 879
| 690
| 385
| 305
| 48
| 0
|
{-# LANGUAGE CPP #-}
main = do
#if !defined(VERSION_containers)
putStrLn "OK"
#endif
|
sdiehl/ghc
|
testsuite/tests/driver/T11763.hs
|
bsd-3-clause
| 89
| 0
| 7
| 16
| 15
| 8
| 7
| 3
| 1
|
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="pt-BR">
<title>Form Handler | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
kingthorin/zap-extensions
|
addOns/formhandler/src/main/javahelp/org/zaproxy/zap/extension/formhandler/resources/help_pt_BR/helpset_pt_BR.hs
|
apache-2.0
| 973
| 83
| 52
| 159
| 396
| 209
| 187
| -1
| -1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.