code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.BackendServices.Delete
-- 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)
--
-- Deletes the specified BackendService resource.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.backendServices.delete@.
module Network.Google.Resource.Compute.BackendServices.Delete
(
-- * REST Resource
BackendServicesDeleteResource
-- * Creating a Request
, backendServicesDelete
, BackendServicesDelete
-- * Request Lenses
, bsdRequestId
, bsdProject
, bsdBackendService
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.backendServices.delete@ method which the
-- 'BackendServicesDelete' request conforms to.
type BackendServicesDeleteResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"global" :>
"backendServices" :>
Capture "backendService" Text :>
QueryParam "requestId" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] Operation
-- | Deletes the specified BackendService resource.
--
-- /See:/ 'backendServicesDelete' smart constructor.
data BackendServicesDelete =
BackendServicesDelete'
{ _bsdRequestId :: !(Maybe Text)
, _bsdProject :: !Text
, _bsdBackendService :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'BackendServicesDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'bsdRequestId'
--
-- * 'bsdProject'
--
-- * 'bsdBackendService'
backendServicesDelete
:: Text -- ^ 'bsdProject'
-> Text -- ^ 'bsdBackendService'
-> BackendServicesDelete
backendServicesDelete pBsdProject_ pBsdBackendService_ =
BackendServicesDelete'
{ _bsdRequestId = Nothing
, _bsdProject = pBsdProject_
, _bsdBackendService = pBsdBackendService_
}
-- | An optional request ID to identify requests. Specify a unique request ID
-- so that if you must retry your request, the server will know to ignore
-- the request if it has already been completed. For example, consider a
-- situation where you make an initial request and the request times out.
-- If you make the request again with the same request ID, the server can
-- check if original operation with the same request ID was received, and
-- if so, will ignore the second request. This prevents clients from
-- accidentally creating duplicate commitments. The request ID must be a
-- valid UUID with the exception that zero UUID is not supported
-- (00000000-0000-0000-0000-000000000000).
bsdRequestId :: Lens' BackendServicesDelete (Maybe Text)
bsdRequestId
= lens _bsdRequestId (\ s a -> s{_bsdRequestId = a})
-- | Project ID for this request.
bsdProject :: Lens' BackendServicesDelete Text
bsdProject
= lens _bsdProject (\ s a -> s{_bsdProject = a})
-- | Name of the BackendService resource to delete.
bsdBackendService :: Lens' BackendServicesDelete Text
bsdBackendService
= lens _bsdBackendService
(\ s a -> s{_bsdBackendService = a})
instance GoogleRequest BackendServicesDelete where
type Rs BackendServicesDelete = Operation
type Scopes BackendServicesDelete =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient BackendServicesDelete'{..}
= go _bsdProject _bsdBackendService _bsdRequestId
(Just AltJSON)
computeService
where go
= buildClient
(Proxy :: Proxy BackendServicesDeleteResource)
mempty
|
brendanhay/gogol
|
gogol-compute/gen/Network/Google/Resource/Compute/BackendServices/Delete.hs
|
mpl-2.0
| 4,461
| 0
| 16
| 965
| 477
| 287
| 190
| 76
| 1
|
module Main where
import Graphics.UI.Gtk (initGUI, mainGUI)
import System.Gnome.GConf
import Monad (when)
import System.Exit (exitFailure)
import List (intersperse)
main = do
-- connect to gconf
conf <- gconfGetDefault
-- for the purposes of this demo check for key and display usage message
exists <- conf `gconfDirExists` "/apps/gtk2hs-gconf-demo"
when (not exists) (do putStrLn usageMessage
exitFailure)
-- get and print initial values
(intValue :: Int) <- conf `gconfGet` "/apps/gtk2hs-gconf-demo/intValue"
(boolValue :: Maybe Bool) <- conf `gconfGet` "/apps/gtk2hs-gconf-demo/boolValue"
(floatValue :: Double) <- conf `gconfGet` "/apps/gtk2hs-gconf-demo/floatValue"
(stringValue :: String) <- conf `gconfGet` "/apps/gtk2hs-gconf-demo/stringValue"
(pairValue :: (Int,Bool)) <- conf `gconfGet` "/apps/gtk2hs-gconf-demo/pairValue"
(listValue :: [Int]) <- conf `gconfGet` "/apps/gtk2hs-gconf-demo/listValue"
print intValue
print boolValue
print floatValue
print stringValue
print pairValue
print listValue
-- register for notification of changes
conf `gconfAddDir` "/apps/gtk2hs-gconf-demo"
-- using the prefered API which allows you to specify the key/dir of interest.
-- This is usuall what you want because you'll do different things in response
-- to changes in different keys. Also, it allows you to use native types rather
-- than converting from a dynamic type.
gconfNotifyAdd conf "/apps/gtk2hs-gconf-demo/intValue"
doSomethingWhenIntValueChanges
gconfNotifyAdd conf "/apps/gtk2hs-gconf-demo/boolValue"
doSomethingWhenBoolValueChanges
gconfNotifyAdd conf "/apps/gtk2hs-gconf-demo/floatValue"
doSomethingWhenFloatValueChanges
gconfNotifyAdd conf "/apps/gtk2hs-gconf-demo/stringValue"
doSomethingWhenStringValueChanges
gconfNotifyAdd conf "/apps/gtk2hs-gconf-demo/pairValue"
doSomethingWhenPairValueChanges
gconfNotifyAdd conf "/apps/gtk2hs-gconf-demo/listValue"
doSomethingWhenListValueChanges
-- and the other API (which gives you notifications on everything)
conf `afterValueChanged` doSomethingWhenAnyKeyChanges
-- run the glib main loop otherwise we wouldn't wait for changes
putStrLn $ "waiting for any changes in the gconf dir"
++ "\"/apps/gtk2hs-gconf-demo\""
initGUI
mainGUI
-- Our various doSomething* functions
--
doSomethingWhenIntValueChanges :: String -> Int -> IO ()
doSomethingWhenIntValueChanges key value =
putStrLn $ "[method1] intValue changed to " ++ show value
-- This one is designed to cope with the key being unset
doSomethingWhenBoolValueChanges :: String -> Maybe Bool -> IO ()
doSomethingWhenBoolValueChanges key (Just value) =
putStrLn $ "[method1] boolValue changed to " ++ show value
doSomethingWhenBoolValueChanges key Nothing =
putStrLn $ "[method1] boolValue was unset"
doSomethingWhenFloatValueChanges :: String -> Double -> IO ()
doSomethingWhenFloatValueChanges key value =
putStrLn $ "[method1] floatValue changed to " ++ show value
doSomethingWhenStringValueChanges :: String -> String -> IO ()
doSomethingWhenStringValueChanges key value =
putStrLn $ "[method1] stringValue changed to " ++ show value
doSomethingWhenPairValueChanges :: String -> (Int, Bool) -> IO ()
doSomethingWhenPairValueChanges key value =
putStrLn $ "[method1] pairValue changed to " ++ show value
doSomethingWhenListValueChanges :: String -> [Int] -> IO ()
doSomethingWhenListValueChanges key value =
putStrLn $ "[method1] listValue changed to " ++ show value
doSomethingWhenAnyKeyChanges :: String -> Maybe GConfValueDyn -> IO ()
doSomethingWhenAnyKeyChanges key (Just value) =
putStrLn $ "[method2] the key " ++ key ++ " changed to " ++ showGConfValue value
doSomethingWhenAnyKeyChanges key Nothing =
putStrLn $ "[method2] the key " ++ key ++ " was unset"
-- Helper function to display a value and its type
-- This is not an important part of the demo
--
showGConfValue :: GConfValueDyn -> String
showGConfValue value =
showGConfValue_ValueOnly value ++ " :: " ++ showGConfValue_Type value
showGConfValue_ValueOnly :: GConfValueDyn -> String
showGConfValue_ValueOnly (GConfValueString s) = show s
showGConfValue_ValueOnly (GConfValueInt n) = show n
showGConfValue_ValueOnly (GConfValueBool b) = show b
showGConfValue_ValueOnly (GConfValueFloat f) = show f
showGConfValue_ValueOnly (GConfValueList as) =
"[" ++ (concat $ intersperse "," $ map showGConfValue_ValueOnly as) ++ "]"
showGConfValue_ValueOnly (GConfValuePair (a,b)) =
"(" ++ showGConfValue_ValueOnly a
++ ", " ++ showGConfValue_ValueOnly b ++ ")"
showGConfValue_Type :: GConfValueDyn -> String
showGConfValue_Type (GConfValueString s) = "String"
showGConfValue_Type (GConfValueInt n) = "Int"
showGConfValue_Type (GConfValueBool b) = "Bool"
showGConfValue_Type (GConfValueFloat f) = "Double"
-- gconf does type empty lists too but our GConfValueDyn cannot represent
-- them using the GConfValueClass is preferable in this sense as it can type
-- all the GConfValue stuff exactly (so long as that type is known statically)
showGConfValue_Type (GConfValueList []) = "[unknown]"
showGConfValue_Type (GConfValueList (a:_)) = "[" ++ showGConfValue_Type a ++ "]"
showGConfValue_Type (GConfValuePair (a,b)) = "(" ++ showGConfValue_Type a ++ ", "
++ showGConfValue_Type b ++ ")"
usageMessage =
"To use this gconf demo program, first create the required gconf entrys.\n"
++ "Use the following commands:\n"
++ " gconftool-2 --set /apps/gtk2hs-gconf-demo/intValue --type int 3\n"
++ " gconftool-2 --set /apps/gtk2hs-gconf-demo/boolValue --type bool false\n"
++ " gconftool-2 --set /apps/gtk2hs-gconf-demo/floatValue --type float 3.141592\n"
++ " gconftool-2 --set /apps/gtk2hs-gconf-demo/stringValue --type string foo\n"
++ " gconftool-2 --set /apps/gtk2hs-gconf-demo/pairValue --type pair \\\n"
++ " --car-type int --cdr-type bool \"(3,false)\"\n"
++ " gconftool-2 --set /apps/gtk2hs-gconf-demo/listValue --type list \\\n"
++ " --list-type int \"[0,1,2,3,4]\"\n"
++ "This demo will display the values of these keys and then watch them for\n"
++ "changes. Use the gconf-editor program to change the values of these keys.\n"
++ "Hit ^C when you get bored.\n"
++ "To delete the keys when you're finnished with this demo use:\n"
++ " gconftool-2 --recursive-unset /apps/gtk2hs-gconf-demo"
|
thiagoarrais/gtk2hs
|
demo/gconf/GConfDemo.hs
|
lgpl-2.1
| 6,494
| 0
| 18
| 1,111
| 1,134
| 572
| 562
| -1
| -1
|
{-# LANGUAGE DataKinds
, ExplicitNamespaces
, TypeFamilies
, TypeOperators
, UndecidableInstances
#-}
module VinylTypeLits
( NatToLit
, LitToNat
)
where
import Data.Vinyl.TypeLevel as V (Nat(Z, S))
import GHC.TypeLits as G (Nat, type (+), type (-))
type family NatToLit (n :: V.Nat) :: G.Nat
where NatToLit 'Z = 0
NatToLit ('S n) = 1 + NatToLit n
type family LitToNat (n :: G.Nat) :: V.Nat
where LitToNat 0 = 'Z
LitToNat n = 'S (LitToNat (n - 1))
|
cumber/havro
|
src/VinylTypeLits.hs
|
lgpl-3.0
| 525
| 0
| 10
| 155
| 167
| 101
| 66
| 16
| 0
|
{-# LANGUAGE NoMonomorphismRestriction #-}
module Jaek.Render.Tree (
drawTree
)
where
import Jaek.Tree
import Diagrams.Prelude hiding (First (..))
import Diagrams.Backend.Cairo
import Data.Monoid
import Data.Tree (Tree (..))
drawTree :: HTree -> QDiagram Cairo R2 (First TreePath)
drawTree = drawTree'
-- adding the name because that way I can retrieve the associated NameMap.
-- At present, the 'circle' function creates an ellipse from the named points
-- C E N W S, which (presumably) are Center, East, North, West, South
-- I can use this to draw the lines, just go from Center to Center
-- for checking if a point is in the diagram, using the Query interface
-- seems more sensible, I just need to come up with the correct monoid,
-- one which indicates the node we're in.
drawTree' (Node dt childs) =
fmap (queryFunc $ nodePath dt) (circle 1
# scaleY 0.5
# fc darkblue
# lw 0.1
# lc deepskyblue
# pad 1.1
# named (show $ nodePath dt)
)
===
(hcat' with {sep = 0.2} (map drawTree' childs) # centerX)
queryFunc :: TreePath -> Any -> First TreePath
queryFunc path an = if getAny an then First (Just path) else First Nothing
|
JohnLato/jaek
|
src/Jaek/Render/Tree.hs
|
lgpl-3.0
| 1,194
| 0
| 14
| 263
| 262
| 141
| 121
| 22
| 2
|
{-
Created : 2013 Oct 01 (Tue) 14:46:30 by carr.
Last Modified : 2014 Mar 05 (Wed) 13:25:38 by Harold Carr.
-}
module FP03ObjSetsTweetSetTest where
import FP03ObjSetsTweetData
import FP03ObjSetsTweetReader
import FP03ObjSetsTweetSet
import Test.HUnit
import Test.HUnit.Util
set1, set2, set3, set4c, set4d, set5, seven, three, one, five, nine, eight :: TweetSet
c, d :: Tweet
set1 = Empty
set2 = incl set1 (Tweet "a" "a body" 20)
set3 = incl set2 (Tweet "b" "b body" 20)
c = Tweet "c" "c body" 7
d = Tweet "d" "d body" 9
set4c = incl set3 c
set4d = incl set3 d
set5 = incl set4c d
seven = NonEmpty (Tweet "7" "7" 7) Empty Empty
three = incl seven (Tweet "3" "3" 3)
one = incl three (Tweet "1" "1" 1)
five = incl one (Tweet "5" "5" 5)
nine = incl five (Tweet "9" "9" 9)
eight = incl nine (Tweet "8" "8" 8)
trends :: [Tweet]
trends = descendingByRetweet set5
getUser :: Tweet -> String
getUser (Tweet user _ _ ) = user
getRetweets :: Tweet -> Int
getRetweets (Tweet _ _ retweets) = retweets
tests :: Test
tests = TestList
[teq "filter': on empty set" (size (filter' (\x -> getUser x == "a") set1)) 0
,teq "filter': a on set5" (size (filter' (\x -> getUser x == "a") set5)) 1
,teq "filter': 20 on set5" (size (filter' (\x -> getRetweets x == 20) set5)) 2
,teq "union: set4c and set4d" (size (set4c `union` set4d)) 4
,teq "union: with empty set (1)" (size (set5 `union` set1)) 4
,teq "union: with empty set (2)" (size (set1 `union` set5)) 4
,teq "descending: set5" (null trends) False
,teq "descending: ..." ((getUser (head trends) == "a") || (getUser (head trends) == "b")) True
]
------------------------------------------------------------------------------
googleKeywords, appleKeywords :: [String]
googleKeywords = ["android", "Android", "galaxy", "Galaxy", "nexus", "Nexus"]
appleKeywords = ["ios", "iOS", "iphone", "iPhone", "ipad", "iPad"]
main :: IO Counts
main = do
runTestTT tests
gizmodoTweets <- parseTweets gizmodoJSON
techcrunchTweets <- parseTweets techcrunchJSON
engadgetTweets <- parseTweets engadgetJSON
amazondealsTweets <- parseTweets amazondealsJSON
cnetTweets <- parseTweets cnetJSON
gadgetlabTweets <- parseTweets gadgetlabJSON
mashableTweets <- parseTweets mashableJSON
let all' = allTweets [gizmodoTweets, techcrunchTweets, engadgetTweets, amazondealsTweets, cnetTweets, gadgetlabTweets, mashableTweets]
runTestTT $ TestList[teq "size all'" (size all') 695]
-- foreach all' (\x -> putStrLn (show x))
let googleTweets = collectByKeywords all' googleKeywords
runTestTT $ TestList[teq "size googleTweets" (size googleTweets) 38]
let appleTweets = collectByKeywords all' appleKeywords
runTestTT $ TestList[teq "size appleTweets" (size appleTweets) 150]
let trending = descendingByRetweet $ googleTweets `union ` appleTweets
runTestTT $ TestList[teq "size trending" (length trending) 179] -- TODO : why is this not 150 + 38 (maybe because of identical text but different users)
-- TODO : ensure that selected Tweets in trending are as expected
-- forM_ trending print
-- End of file.
|
haroldcarr/learn-haskell-coq-ml-etc
|
haskell/course/2013-11-coursera-fp-odersky-but-in-haskell/FP03ObjSetsTweetSetTest.hs
|
unlicense
| 3,582
| 0
| 15
| 1,039
| 955
| 506
| 449
| 59
| 1
|
{-# Language TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{- |
This module aims to make mapping between algebraic data types and bson
documents easy.
You can also generate documents with 'selectFields', which takes a
list of functions names that of type a -> b and returns a function
of type a -> Document.
Example:
> import Data.Bson.Mapping
> import Data.Time.Clock
> import Data.Data (Typeable)
>
> data Post = Post { time :: UTCTime
> , author :: String
> , content :: String
> , votes :: Int
> }
> deriving (Show, Read, Eq, Ord, Typeable)
> $(deriveBson ''Post)
>
> main :: IO ()
> main = do
> now <- getCurrentTime
> let post = Post now "francesco" "lorem ipsum" 5
> (fromBson (toBson post) :: IO Post) >>= print
> print $ toBson post
> print $ $(selectFields ['time, 'content]) post
-}
module Data.Bson.Mapping
( Bson (..)
, deriveBson
, selectFields
, getLabel
, getConsDoc
, subDocument
, getField
) where
import Prelude hiding (lookup)
import Data.Bson
import Data.Data (Typeable)
import Data.Text (Text, append, cons, pack)
import Language.Haskell.TH
import Language.Haskell.TH.Lift ()
class (Show a, Eq a, Typeable a) => Bson a where
toBson :: a -> Document
fromBson :: Monad m => Document -> m a
-- | Derive 'Bson' and 'Val' declarations for a data type.
deriveBson :: Name -> Q [Dec]
deriveBson type' = do
(cx, conss, keys) <- bsonType
-- Each type in the data type must be an instance of val
let context = [ classP ''Val [varT key] | key <- keys ] ++ map return cx
-- Generate the functions for the Bson instance
let fs = [ funD 'toBson (map deriveToBson conss)
, funD 'fromBson [clause [] (normalB $ deriveFromBson conss) []]
]
i <- instanceD (sequence context) (mkType ''Bson [mkType type' (map varT keys)]) fs
-- Generate the Val instance (easy, since a Bson doc is
-- automatically a Val)
doc <- newName "doc"
i' <- instanceD (cxt []) (mkType ''Val [mkType type' (map varT keys)])
[ funD 'val [clause [] (normalB $ [| Doc . toBson |]) []]
, funD 'cast' [ clause [conP 'Doc [varP doc]] (normalB $ [| fromBson $(varE doc) |]) []
, clause [[p| _ |]] (normalB $ [| Nothing |]) []
]
]
return [i, i']
where
-- Check that wha has been provided is a data/newtype declaration
bsonType = do
info <- reify type'
case info of
TyConI (DataD cx _ keys _ conss _) -> return (cx, conss, map conv keys)
TyConI (NewtypeD cx _ keys _ con _) -> return (cx, [con], map conv keys)
_ -> inputError
mkType con = foldl appT (conT con)
conv (PlainTV n) = n
conv (KindedTV n _) = n
inputError = error $ "deriveBson: Invalid type provided. " ++
"The type must be a data type or a newtype. " ++
"Currently infix constructors and existential types are not supported."
-- deriveToBson generates the clauses that pattern match the
-- constructors of the data type, and then the function to convert
-- them to Bson.
deriveToBson :: Con -> Q Clause
-- If it's a constructor with named fields, we can simply use
-- selectFields
deriveToBson (RecC name fields) = do
let fieldsDoc = selectFields $ map (\(n, _, _) -> n) fields
consDoc <- getConsDoc name
i <- newName "i"
-- With data Foo = Foo {one :: String, two :: Int}
-- This will produce something like:
-- toBson i@Foo{} = merge ["_cons" =: "Foo"] ["one" =: one i, "two" =: two i]
clause [asP i (recP name [])] (normalB $ [| (merge $(getConsDoc name)) ($fieldsDoc $(varE i)) |]) []
-- If it's a normal constructor, generate a document with an array
-- with the data.
deriveToBson (NormalC name types) = do
-- There are no types, but just a constructor (data Foo = Foo),
-- simply store the constructor name.
if null types
then clause [recP name []] (normalB $ getConsDoc name) []
-- Else, convert all the data inside the data types to an array
-- and store it in the document.
-- Example: if we have 'Foo = Foo String Int', 'Foo "francesco" 4'
-- will be converted to ["_cons" =: "Foo", "_data" =: ["francesco", 4]]
else do
fields <- mapM (\_ -> newName "f") types
clause [conP name (map varP fields)]
(normalB $ [| (merge $(getConsDoc name)) . (\f -> [dataField =: f]) $ $(listE (map varE fields)) |]) []
deriveToBson _ = inputError
-- deriveFromBson gets the _cons field, and guesses which
-- constructor to use. Fails if it can't match _cons with a
-- constructor of the data type.
deriveFromBson :: [Con] -> Q Exp
deriveFromBson conss = do
con <- newName "con"
docN <- newName "doc"
(SigE _ (ConT strtype)) <- runQ [| "" :: Text |]
let doc = varE docN
lamE [varP docN] $ doE
[ bindS (varP con) [| lookup consField $doc |]
, noBindS $ caseE (sigE (varE con) (conT strtype)) (map (genMatch doc) conss ++ noMatch)
]
noMatch = [match [p| _ |] (normalB [| fail "Couldn't find right constructor" |]) []]
-- Generate the case statements after we get the _cons field, to
-- match it and get the right constructor
genMatch :: Q Exp -> Con -> Q Match
genMatch doc (RecC name fields) =
-- Match the string literal that we got from the doc (_cons)
flip (match (litP $ StringL $ nameBase name)) [] $ do
(fields', stmts) <- genStmts (map (\(n, _, _) -> n) fields) doc
let ci = noBindS $ [| return $(recConE name fields') |]
normalB (doE $ stmts ++ [ci])
genMatch doc (NormalC name types) =
flip (match (litP $ StringL $ nameBase name)) [] $
if null types
then normalB [| return $(conE name) |]
else do
-- In the case of a normal constructor with types in it, we
-- have to get the _data field and apply it to the
-- constructor
-- This gets the data, checks that the length is equal to
-- the number of types in the data type, then pattern
-- matches the array that we got and applies it to the
-- constructor (the foldl).
data' <- newName "data"
let typesN = length types
types' <- mapM (\_ -> newName "t") types
let typesP = listP $ map varP types'
con = foldl (\e f -> (appE e (varE f))) (conE name) types'
normalB $ doE [ bindS (varP data') [| lookup dataField $doc |]
, noBindS [| if length $(varE data') /= $([| typesN |])
then fail "Wrong data for the constructor."
else $(doE [ letS [valD typesP (normalB $ varE data') []]
, noBindS [| return $con |]
])
|]
]
genMatch _ _ = inputError
-- genStmts generates the lookups on the document and also returns
-- the vars names that are used in the statements, coupled with
-- the original fields.
genStmts :: [Name] -> Q Exp -> Q ([Q (Name, Exp)], [Q Stmt])
genStmts [] _ = return ([], [])
genStmts (f : fs) doc = do
fvar <- newName "f"
let stmt = bindS (varP fvar) $ [| lookup (pack (nameBase f)) $doc |]
(fields, stmts) <- genStmts fs doc
return $ (return (f, VarE fvar) : fields, stmt : stmts)
dataField, consField :: Text
dataField = "_data"
consField = "_cons"
{-|
Select only certain fields in a document, see the code sample at the
top.
Please note that there is no checking for the names to be actual
fields of the bson document mapped to a datatype, so be careful.
-}
selectFields :: [Name] -> Q Exp
selectFields ns = do
d <- newName "d"
e <- gf d ns
lamE [varP d] (return e)
where
gf _ [] = [| [] |]
gf d (n : ns') = [| ((pack $(getLabel n)) =: $(varE n) $(varE d)) : $(gf d ns') |]
{-|
Get a document that identifies the data type - @getConsDoc ''Post@.
This is useful to select all documents mapped to a certain data type.
-}
getConsDoc :: Name -> Q Exp
getConsDoc n = [| [consField =: nameBase n] |]
-- | Simple function to select fields in a nested document.
subDocument :: Label -> Document -> Document
subDocument lab doc = [append lab (cons '.' l) := v | (l := v) <- doc]
getLabel :: Name -> Q Exp
getLabel n = [| (nameBase n) |]
{-|
Returns a function that gets a datatype and a value, and generates a 'Document' consisting of one field - the label provided - and the value of that datatype.
@$(getField 'time) post@ will generate @[\"time\" =: time post]@.
-}
getField :: Name -> Q Exp
getField n = [| \d -> $(getLabel n) =: $(varE n) d |]
|
bitonic/bson-mapping
|
src/Data/Bson/Mapping.hs
|
apache-2.0
| 9,004
| 6
| 25
| 2,725
| 1,995
| 1,073
| 922
| 115
| 12
|
{-# LANGUAGE NoMonomorphismRestriction, QuasiQuotes #-}
import Control.Arrow
import Control.Monad
import NeuralNetwork
import Numeric.LinearAlgebra.HMatrix
import Text.Printf.TH
import VisualizeFunction
andDataSet = map (vector *** vector) [
([0,0], [0]),
([0,1], [0]),
([1,0], [0]),
([1,1], [1])
]
xorDataSet = map (vector *** vector) [
([0,0], [0]),
([0,1], [1]),
([1,0], [1]),
([1,1], [0])
]
nn = randomlyWeightedNetwork 0 [2, 9, 1] logisticAF
trainOn dataset = iterate (stochasticGradientDescent dataset 0.25) nn
andNNs = trainOn andDataSet
xorNNs = trainOn xorDataSet
outputs dataset nns = map (\nn -> map (applyNN nn) (map fst dataset)) nns
andOutputs = outputs andDataSet andNNs
xorOutputs = outputs xorDataSet xorNNs
image = visualizeFunctionBMP (0,0) (1,1) (1024,1024) (0,1) . ((!0).) . applyNN
main = forM_ [0..10] $ \i -> do
saveImage ([s|neuralnetwork_and_%04d.bmp|] (2^i)) (image (andNNs !! (2^i)))
saveImage ([s|neuralnetwork_xor_%04d.bmp|] (2^i)) (image (xorNNs !! (2^i)))
|
aweinstock314/neural-networks
|
TestNeuralNetwork.hs
|
apache-2.0
| 1,043
| 4
| 15
| 185
| 506
| 289
| 217
| 28
| 1
|
-- |'nodeIx' is exported for the buildGraph function in ListM.
module Data.InductiveGraph.ListImpl (InductiveGraph, Node, newVertex, vertexValue, updateVertex, insertEdge, deleteEdge,
isEdgePresent, reverseEdges, vertexSuccs, graphFold, removeToEdges, emptyGraph, nodeIx, firstVertex,
combineVertices, foldVerticesM) where
import Framework
import Control.Monad
import Control.Monad.State.Strict
import Data.List (partition,delete,insertBy)
import qualified Data.Set as S
import qualified Data.Map as M
import qualified Data.Foldable as F
import qualified Data.Traversable as T
import Control.Applicative (liftA2,pure)
data Node = Node { nodeIx :: Int } deriving (Show,Ord,Eq)
data InductiveGraph a
= EmptyGraph
| InductiveGraph a Node [Node] {-edges to this node from the nodes in this list-}
[Node] {-edges from this node to the nodes in the list-} (InductiveGraph a)
deriving (Show)
------------------------------------------------------------------------------------------------------------------------
-- Utilities
-- |Returns the index of the next vertex to be inserted into a graph
nextVx :: InductiveGraph a -> Node
nextVx EmptyGraph = Node 0
nextVx (InductiveGraph _ (Node ix) _ _ _) = Node (ix+1)
-- |Inserts a vertex into an edge-list, in order
insVx :: Node -> [Node] -> [Node]
insVx vx vxs = insertWithoutDuplicatesBy (reverseCompare compare) vx vxs
-- |Merges two ordered edge-lists
mergeVxs :: [Node] -> [Node] -> [Node]
mergeVxs vxs1 vxs2 = mergeWithoutDuplicatesBy (reverseCompare compare) vxs1 vxs2
------------------------------------------------------------------------------------------------------------------------
-- Interface
emptyGraph :: InductiveGraph a
emptyGraph = EmptyGraph
firstVertex :: Node
firstVertex = nextVx EmptyGraph
newVertex :: a -> InductiveGraph a -> (InductiveGraph a,Node)
newVertex a gr = (InductiveGraph a (nextVx gr) [] [] gr, nextVx gr)
vertexValue :: Monad m => Node -> InductiveGraph a -> m a
vertexValue _ EmptyGraph = fail "vertexValue: empty graph"
vertexValue n (InductiveGraph a n' _ _ rest)
| n > n' = fail "vertexValue: nonexistant node"
| n == n' = return a
| otherwise = vertexValue n rest
-- |Updates the value of the specified vertex.
updateVertex :: Monad m => Node -> a -> InductiveGraph a -> m (InductiveGraph a)
updateVertex _ _ EmptyGraph = fail "updateVertex: emptyGraph"
updateVertex n' a' (InductiveGraph a n to from rest)
| n' > n = fail "updateVertex: nonexistant node"
| n' == n = return (InductiveGraph a' n to from rest)
| otherwise = updateVertex n' a' rest >>= \rest' -> return (InductiveGraph a n to from rest')
-- |Insert an edge from 'm' to 'n'.
insertEdge :: Monad m => Node -> Node -> InductiveGraph a -> m (InductiveGraph a)
insertEdge m n EmptyGraph = fail "insertEdge: vertices not found"
insertEdge m n (InductiveGraph a q to from rest)
-- at m, and n occurs in rest since m > n. Since we are adding an edge m-->n, n gets added to the from list here
| m >= n && m == q = return (InductiveGraph a q to (insVx n from) rest)
-- at m, and m < n. So, n occurs before. We should have caught this earlier.
| m < n && m == q = error "insertEdge: m < n, and we are at m (implementation bug)"
-- at n, and since m <= n, m is in rest. Since we are adding m-->n, we add m as an edge to this node.
| m <= n && n == q = return (InductiveGraph a q (insVx m to) from rest)
-- at n, and m > n. So, we should have encountered m earlier.
| m > n && n == q = error "insertEdge: m > n, and we are at n (implementation bug)"
| otherwise = insertEdge m n rest >>= \rest' -> return (InductiveGraph a q to from rest')
-- |Delete an edge from 'vx1' to 'vx2.'
deleteEdge :: Monad m => Node -> Node -> InductiveGraph a -> m (InductiveGraph a)
deleteEdge vx1 vx2 graph =
let isEdgeFrom = vx1 >= vx2 -- True if the edge appears on vx1's from-list
edge = if isEdgeFrom then vx2 else vx1
del _ EmptyGraph = fail "deleteEdge: empty graph"
del inVx (InductiveGraph a vx to from subgraph)
| inVx < vx = del inVx subgraph >>= \subgraph' -> return (InductiveGraph a vx to from subgraph')
| inVx > vx = fail "graph does not contain vx1"
| inVx == vx && isEdgeFrom =
if edge `elem` from
then return (InductiveGraph a vx to (delete edge from) subgraph)
else fail "deleteEdge: edge not found (in from list)"
| otherwise {- inVx == vx && not isEdgeFrom -} =
if edge `elem` to
then return (InductiveGraph a vx (delete edge to) from subgraph)
else fail "deleteEdge: edge not found (in to list)"
in if isEdgeFrom -- Is vx1 >= vx2?
-- Is so, we will find vx1 first and the edge will be *from* vx1 to vx2
then del vx1 graph
-- If not, we will find vx2 first and the edge will be *to* vx2 from vx1.
else del vx2 graph
-- |Fails if either 'm' or 'n' does not exist
isEdgePresent :: Node -> Node -> InductiveGraph a -> Bool
isEdgePresent m n EmptyGraph = False
isEdgePresent m n (InductiveGraph a q to from rest)
| m >= n && m == q = n `elem` from
| n >= m && n == q = m `elem` to
| m > q = error ("isEdgePresent: non-existant vertex as first argument: " ++ show m)
| n > q = error ("isEdgePresent: non-existant vertex as second argument: " ++ show n)
| otherwise = isEdgePresent m n rest
-- |Immediate successors of this vertex.
vertexSuccs :: Node -> InductiveGraph a -> [Node]
vertexSuccs n EmptyGraph = []
vertexSuccs n (InductiveGraph _ n' to from rest)
| n > n' = []
| n == n' = from
| n < n' && n `elem` to = n':(vertexSuccs n rest)
| otherwise = vertexSuccs n rest
graphFold :: ((a,Node,[Node],[Node]) -> b -> b) -> b -> InductiveGraph a -> b
graphFold f acc EmptyGraph = acc
graphFold f acc (InductiveGraph a n to from rest) = f (a,n,to,from) (graphFold f acc rest)
-- |Transforms the inductive graph, turning "to-edges" into "from-edges." This
-- breaks the inductive invariant, but is necessary to build a cyclic graph
-- structure.
removeToEdges :: InductiveGraph a -> InductiveGraph a
removeToEdges gr = remove' gr [] where
remove' EmptyGraph [] = EmptyGraph
remove' EmptyGraph extras =
error $ "InductiveGraph.ListImpl.removeToEdges : " ++ show (length extras) ++ " edges left"
remove' (InductiveGraph a vx to from rest) es =
let es' = map (\e -> (e,vx)) to -- edges from n' (others) to this--pass down the list
(fromEdges,es'') = partition (\(e,_) -> e == vx) es -- accumulated list of edges from others to this
-- edges from this node to others
from' = map snd fromEdges
in InductiveGraph a vx [] (from ++ from') (remove' rest (es' ++ es''))
-- |Reverses the edges of the graph.
reverseEdges :: InductiveGraph a -> InductiveGraph a
reverseEdges EmptyGraph = EmptyGraph
reverseEdges graph@(InductiveGraph a vxTop toVx fromVx inner) =
let -- vxTop is the outermost vertex. When the graph is reversed, it will become the innermost vertex with
-- nodeIx = 0.
transVx (Node ix) = Node (nodeIx vxTop - ix)
transVxs = map transVx
-- partitions the edge list, selecting edges from 'vx'
partitionFromVx vx vxs = partition (\(vx',_) -> vx' == vx) vxs
-- partitions the edge list, selecting edges to 'vx'
partitionToVx vx vxs = partition (\(_,vx') -> vx' == vx) vxs
makeTo vx' vxs = map (\vxTo -> (vx',transVx vxTo)) vxs
makeFrom vx' vxs = map (\vxFrom -> (transVx vxFrom,vx')) vxs
reverse' EmptyGraph [] [] inner = inner
reverse' EmptyGraph tos froms _ = error $ "reverseEdges : " ++ show (length $ froms ++ tos) ++ " edges left"
reverse' (InductiveGraph a vx toVx fromVx outer) tos froms inner =
let vx' = transVx vx
(toVx',otherTos) = partitionToVx vx' tos
(fromVx',otherFroms) = partitionFromVx vx' froms
in reverse' outer ((makeTo vx' toVx) ++ otherTos) ((makeFrom vx' fromVx) ++ otherFroms)
(InductiveGraph a vx' (map fst toVx') (map snd fromVx') inner)
in reverse' graph [] [] EmptyGraph
{-
filterVertices :: (a -> Bool) -> InductiveGraph a -> InductiveGraph a
filterVertices f graph = filter' graph ... where
filter' (InductiveGraph a vx toVx fromVx subgraph) | not (f a) =
let (edges,subgraph') = filter'
-}
foldVerticesM :: Monad m => ((a,Node,[Node],[Node]) -> b -> m b) -> b -> InductiveGraph a -> m b
foldVerticesM f acc EmptyGraph = return acc
foldVerticesM f acc (InductiveGraph a ix to from subgraph) = do
acc' <- f (a,ix,to,from) acc
foldVerticesM f acc' subgraph
-- |'f' must define an equivalence relation. The resultant graph has one node in each equivalence class. Which node is
-- chosen is not defined. 'f' is applied O(|V|^2) times.
combineVertices :: (a -> a -> Bool) -> InductiveGraph a -> InductiveGraph a
combineVertices f graph =
let -- collect ::
collect a repVx EmptyGraph = return ([],[],[],EmptyGraph)
collect a repVx (InductiveGraph a' vx to from rest)
| f a a' = do -- a' is equivalent to a, so must be filtered out
(equiv,to',from',rest') <- collect a repVx rest
vxMap <- get
put (M.insert vx repVx vxMap)
return (insVx vx equiv,mergeVxs to to',mergeVxs from from',rest')
| otherwise = do -- we keep this vertex
-- equivVxs are inner vertices equivalent to repVx.
(equivVxs,innerTo,innerFrom,rest') <- collect a repVx rest
-- Since,repVx > vx (this vertex). If from / to contains any of equivVxs, filter them out.
let (equivTo,otherTo) = partition (\vx -> vx `elem` equivVxs) to
let (equivFrom,otherFrom) = partition (\vx -> vx `elem` equivVxs) from
-- If we have an edge vx --> equivTo, replace it with an edge repVx --> vx (reversed), and vice versa.
let innerTo' = if null equivFrom then innerTo else insVx vx innerTo
let innerFrom' = if null equivTo then innerFrom else insVx vx innerFrom
return (equivVxs,innerTo',innerFrom',InductiveGraph a' vx otherTo otherFrom rest')
combine EmptyGraph = return EmptyGraph
combine (InductiveGraph a vx from to rest) = do
-- Since we reached this node, it is the representative for its equivalence class. Traverse rest for equivalent
-- nodes, collect their from/to lists and merge them with ours.
(equivs,from',to',rest') <- collect a vx rest -- nothing in rest' is equivalent to vx
-- Recurse.
rest'' <- combine rest' -- nodes in rest'' are not equivalent to each other
-- filter equivalent edges out
let filteredFrom = filter (\vx -> not (vx `elem` equivs)) from
let filteredTo = filter (\vx -> not (vx `elem` equivs)) to
return (InductiveGraph a vx (mergeVxs filteredFrom from') (mergeVxs filteredTo to') rest'')
-- After applying combine, the graph has a single representative of each equivalence class. However, the edge
-- lists contain edges to elements that were removed. We have a set of the vertices that were removed. Yay!
filterEquiv vxMap vx rest = case M.lookup vx vxMap of
-- by construction, if vxRep is the representative of vx, vxRep > vx and cannot be accounted for on this vertex
Just vxRep -> insVx vxRep rest
Nothing -> vx:rest
filterInvalidEdges _ EmptyGraph = EmptyGraph
filterInvalidEdges vxSet (InductiveGraph a vxRep from to rest) =
let from' = foldr (filterEquiv vxSet) [] from
to' = foldr (filterEquiv vxSet) [] to
in InductiveGraph a vxRep from' to' (filterInvalidEdges vxSet rest)
(graph',vxSet) = runState (combine graph) M.empty
graph'' = filterInvalidEdges vxSet graph'
in graph''
instance Functor InductiveGraph where
fmap _ EmptyGraph = EmptyGraph
fmap f (InductiveGraph a ix to from subgraph) = InductiveGraph (f a) ix to from (fmap f subgraph)
instance F.Foldable InductiveGraph where
foldr _ b EmptyGraph = b
foldr f b (InductiveGraph a _ _ _ subgraph) = F.foldr f (f a b) subgraph
instance T.Traversable InductiveGraph where
traverse f EmptyGraph = pure EmptyGraph
traverse f (InductiveGraph a ix vxTo vxFrom subgraph) =
liftA2 (\a' subgraph' -> InductiveGraph a' ix vxTo vxFrom subgraph') (f a) (T.traverse f subgraph)
------------------------------------------------------------------------------------------------------------------------
|
brownplt/ovid
|
src/Data/InductiveGraph/ListImpl.hs
|
bsd-2-clause
| 12,483
| 0
| 19
| 2,829
| 3,483
| 1,788
| 1,695
| 167
| 7
|
module Test.Day22 where
import Day22
import Data.Function (on)
import Data.List (minimumBy)
import Test.Tasty
import Test.Tasty.HUnit
day22 :: TestTree
day22 = testGroup "Wizard Simulator 20XX" [part1, part2]
part1 :: TestTree
part1 = testGroup "Part 1" [p1Tests, p1Puzzle]
spells1 :: [Spell]
spells1 = [Poison, Missile]
p11Start :: (Player, Boss)
p11Start = (Player 10 250 [], Boss 13 8 [])
p11End :: (Player, Boss)
p11End = (Player 2 24 [], Boss 0 8 [EPoison 3])
spells2 :: [Spell]
spells2 = [Recharge, Shield, Drain, Poison, Missile]
p12Start :: (Player, Boss)
p12Start = (Player 10 250 [], Boss 14 8 [])
p12End :: (Player, Boss)
p12End = (Player 1 114 [], Boss 0 8 [EPoison 3])
p1Tests :: TestTree
p1Tests = testGroup "Test Cases" [
testCase "Example 1" $ play p11Start spells1 @?= p11End
, testCase "Example 2" $ play p12Start spells2 @?= p12End
]
start :: (Player, Boss)
start = (Player 50 500 [], Boss 71 10 [])
isCandidate :: [Spell] -> Bool
isCandidate x = isGameOver x' && playerWins x'
where
x' = play start x
candidates :: [[Spell]]
candidates = filter isCandidate $ concatMap spells [10..12]
p1Puzzle :: TestTree
p1Puzzle = testGroup "Puzzle" [
testCase "Puzzle" $ 1824 @?= cost (minimumBy (compare `on` cost) candidates)
]
candidates' :: [[Spell]]
candidates' = filter isCandidate' $ concatMap spells [13]
isCandidate' :: [Spell] -> Bool
isCandidate' x = isGameOver x' && playerWins x'
where
x' = play' start x
part2 :: TestTree
part2 = testGroup "Part 2" [p2Puzzle]
p2Puzzle :: TestTree
p2Puzzle = testGroup "Puzzle" [
testCase "Puzzle" $ 1937 @?= cost (minimumBy (compare `on` cost) candidates')
]
|
taylor1791/adventofcode
|
2015/test/Test/Day22.hs
|
bsd-2-clause
| 1,726
| 0
| 12
| 375
| 654
| 358
| 296
| 46
| 1
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QLCDNumber_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:30
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QLCDNumber_h where
import Qtc.Enums.Base
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui_h
import Qtc.ClassTypes.Gui
import Foreign.Marshal.Array
instance QunSetUserMethod (QLCDNumber ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QLCDNumber_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QLCDNumber_unSetUserMethod" qtc_QLCDNumber_unSetUserMethod :: Ptr (TQLCDNumber a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QLCDNumberSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QLCDNumber_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QLCDNumber ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QLCDNumber_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QLCDNumberSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QLCDNumber_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QLCDNumber ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QLCDNumber_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QLCDNumberSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QLCDNumber_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QLCDNumber ()) (QLCDNumber x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QLCDNumber setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QLCDNumber_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QLCDNumber_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQLCDNumber x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QLCDNumber_setUserMethod" qtc_QLCDNumber_setUserMethod :: Ptr (TQLCDNumber a) -> CInt -> Ptr (Ptr (TQLCDNumber x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QLCDNumber :: (Ptr (TQLCDNumber x0) -> IO ()) -> IO (FunPtr (Ptr (TQLCDNumber x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QLCDNumber_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QLCDNumberSc a) (QLCDNumber x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QLCDNumber setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QLCDNumber_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QLCDNumber_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQLCDNumber x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QLCDNumber ()) (QLCDNumber x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QLCDNumber setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QLCDNumber_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QLCDNumber_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQLCDNumber x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QLCDNumber_setUserMethodVariant" qtc_QLCDNumber_setUserMethodVariant :: Ptr (TQLCDNumber a) -> CInt -> Ptr (Ptr (TQLCDNumber x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QLCDNumber :: (Ptr (TQLCDNumber x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQLCDNumber x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QLCDNumber_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QLCDNumberSc a) (QLCDNumber x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QLCDNumber setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QLCDNumber_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QLCDNumber_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQLCDNumber x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QLCDNumber ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QLCDNumber_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QLCDNumber_unSetHandler" qtc_QLCDNumber_unSetHandler :: Ptr (TQLCDNumber a) -> CWString -> IO (CBool)
instance QunSetHandler (QLCDNumberSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QLCDNumber_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QLCDNumber ()) (QLCDNumber x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QLCDNumber1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QLCDNumber1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QLCDNumber_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQLCDNumber x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qLCDNumberFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QLCDNumber_setHandler1" qtc_QLCDNumber_setHandler1 :: Ptr (TQLCDNumber a) -> CWString -> Ptr (Ptr (TQLCDNumber x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QLCDNumber1 :: (Ptr (TQLCDNumber x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQLCDNumber x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QLCDNumber1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QLCDNumberSc a) (QLCDNumber x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QLCDNumber1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QLCDNumber1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QLCDNumber_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQLCDNumber x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qLCDNumberFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qevent_h (QLCDNumber ()) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_event cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_event" qtc_QLCDNumber_event :: Ptr (TQLCDNumber a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent_h (QLCDNumberSc a) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_event cobj_x0 cobj_x1
instance QsetHandler (QLCDNumber ()) (QLCDNumber x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QLCDNumber2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QLCDNumber2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QLCDNumber_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQLCDNumber x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qLCDNumberFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QLCDNumber_setHandler2" qtc_QLCDNumber_setHandler2 :: Ptr (TQLCDNumber a) -> CWString -> Ptr (Ptr (TQLCDNumber x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QLCDNumber2 :: (Ptr (TQLCDNumber x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQLCDNumber x0) -> Ptr (TQEvent t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QLCDNumber2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QLCDNumberSc a) (QLCDNumber x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QLCDNumber2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QLCDNumber2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QLCDNumber_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQLCDNumber x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qLCDNumberFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QpaintEvent_h (QLCDNumber ()) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_paintEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_paintEvent" qtc_QLCDNumber_paintEvent :: Ptr (TQLCDNumber a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent_h (QLCDNumberSc a) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_paintEvent cobj_x0 cobj_x1
instance QsetHandler (QLCDNumber ()) (QLCDNumber x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QLCDNumber3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QLCDNumber3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QLCDNumber_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQLCDNumber x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qLCDNumberFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QLCDNumber_setHandler3" qtc_QLCDNumber_setHandler3 :: Ptr (TQLCDNumber a) -> CWString -> Ptr (Ptr (TQLCDNumber x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QLCDNumber3 :: (Ptr (TQLCDNumber x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQLCDNumber x0) -> IO (Ptr (TQSize t0))))
foreign import ccall "wrapper" wrapSetHandler_QLCDNumber3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QLCDNumberSc a) (QLCDNumber x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QLCDNumber3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QLCDNumber3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QLCDNumber_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQLCDNumber x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qLCDNumberFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqsizeHint_h (QLCDNumber ()) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLCDNumber_sizeHint cobj_x0
foreign import ccall "qtc_QLCDNumber_sizeHint" qtc_QLCDNumber_sizeHint :: Ptr (TQLCDNumber a) -> IO (Ptr (TQSize ()))
instance QqsizeHint_h (QLCDNumberSc a) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLCDNumber_sizeHint cobj_x0
instance QsizeHint_h (QLCDNumber ()) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLCDNumber_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QLCDNumber_sizeHint_qth" qtc_QLCDNumber_sizeHint_qth :: Ptr (TQLCDNumber a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint_h (QLCDNumberSc a) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLCDNumber_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QchangeEvent_h (QLCDNumber ()) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_changeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_changeEvent" qtc_QLCDNumber_changeEvent :: Ptr (TQLCDNumber a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent_h (QLCDNumberSc a) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_changeEvent cobj_x0 cobj_x1
instance QactionEvent_h (QLCDNumber ()) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_actionEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_actionEvent" qtc_QLCDNumber_actionEvent :: Ptr (TQLCDNumber a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent_h (QLCDNumberSc a) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_actionEvent cobj_x0 cobj_x1
instance QcloseEvent_h (QLCDNumber ()) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_closeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_closeEvent" qtc_QLCDNumber_closeEvent :: Ptr (TQLCDNumber a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent_h (QLCDNumberSc a) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_closeEvent cobj_x0 cobj_x1
instance QcontextMenuEvent_h (QLCDNumber ()) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_contextMenuEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_contextMenuEvent" qtc_QLCDNumber_contextMenuEvent :: Ptr (TQLCDNumber a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent_h (QLCDNumberSc a) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_contextMenuEvent cobj_x0 cobj_x1
instance QsetHandler (QLCDNumber ()) (QLCDNumber x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QLCDNumber4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QLCDNumber4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QLCDNumber_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQLCDNumber x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qLCDNumberFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QLCDNumber_setHandler4" qtc_QLCDNumber_setHandler4 :: Ptr (TQLCDNumber a) -> CWString -> Ptr (Ptr (TQLCDNumber x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QLCDNumber4 :: (Ptr (TQLCDNumber x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQLCDNumber x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QLCDNumber4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QLCDNumberSc a) (QLCDNumber x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QLCDNumber4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QLCDNumber4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QLCDNumber_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQLCDNumber x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qLCDNumberFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QdevType_h (QLCDNumber ()) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLCDNumber_devType cobj_x0
foreign import ccall "qtc_QLCDNumber_devType" qtc_QLCDNumber_devType :: Ptr (TQLCDNumber a) -> IO CInt
instance QdevType_h (QLCDNumberSc a) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLCDNumber_devType cobj_x0
instance QdragEnterEvent_h (QLCDNumber ()) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_dragEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_dragEnterEvent" qtc_QLCDNumber_dragEnterEvent :: Ptr (TQLCDNumber a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent_h (QLCDNumberSc a) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_dragEnterEvent cobj_x0 cobj_x1
instance QdragLeaveEvent_h (QLCDNumber ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_dragLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_dragLeaveEvent" qtc_QLCDNumber_dragLeaveEvent :: Ptr (TQLCDNumber a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent_h (QLCDNumberSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_dragLeaveEvent cobj_x0 cobj_x1
instance QdragMoveEvent_h (QLCDNumber ()) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_dragMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_dragMoveEvent" qtc_QLCDNumber_dragMoveEvent :: Ptr (TQLCDNumber a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent_h (QLCDNumberSc a) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_dragMoveEvent cobj_x0 cobj_x1
instance QdropEvent_h (QLCDNumber ()) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_dropEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_dropEvent" qtc_QLCDNumber_dropEvent :: Ptr (TQLCDNumber a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent_h (QLCDNumberSc a) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_dropEvent cobj_x0 cobj_x1
instance QenterEvent_h (QLCDNumber ()) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_enterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_enterEvent" qtc_QLCDNumber_enterEvent :: Ptr (TQLCDNumber a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent_h (QLCDNumberSc a) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_enterEvent cobj_x0 cobj_x1
instance QfocusInEvent_h (QLCDNumber ()) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_focusInEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_focusInEvent" qtc_QLCDNumber_focusInEvent :: Ptr (TQLCDNumber a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent_h (QLCDNumberSc a) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_focusInEvent cobj_x0 cobj_x1
instance QfocusOutEvent_h (QLCDNumber ()) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_focusOutEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_focusOutEvent" qtc_QLCDNumber_focusOutEvent :: Ptr (TQLCDNumber a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent_h (QLCDNumberSc a) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_focusOutEvent cobj_x0 cobj_x1
instance QsetHandler (QLCDNumber ()) (QLCDNumber x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QLCDNumber5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QLCDNumber5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QLCDNumber_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQLCDNumber x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qLCDNumberFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QLCDNumber_setHandler5" qtc_QLCDNumber_setHandler5 :: Ptr (TQLCDNumber a) -> CWString -> Ptr (Ptr (TQLCDNumber x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QLCDNumber5 :: (Ptr (TQLCDNumber x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQLCDNumber x0) -> CInt -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QLCDNumber5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QLCDNumberSc a) (QLCDNumber x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QLCDNumber5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QLCDNumber5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QLCDNumber_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQLCDNumber x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qLCDNumberFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QheightForWidth_h (QLCDNumber ()) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLCDNumber_heightForWidth cobj_x0 (toCInt x1)
foreign import ccall "qtc_QLCDNumber_heightForWidth" qtc_QLCDNumber_heightForWidth :: Ptr (TQLCDNumber a) -> CInt -> IO CInt
instance QheightForWidth_h (QLCDNumberSc a) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLCDNumber_heightForWidth cobj_x0 (toCInt x1)
instance QhideEvent_h (QLCDNumber ()) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_hideEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_hideEvent" qtc_QLCDNumber_hideEvent :: Ptr (TQLCDNumber a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent_h (QLCDNumberSc a) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_hideEvent cobj_x0 cobj_x1
instance QsetHandler (QLCDNumber ()) (QLCDNumber x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QLCDNumber6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QLCDNumber6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QLCDNumber_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQLCDNumber x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qLCDNumberFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QLCDNumber_setHandler6" qtc_QLCDNumber_setHandler6 :: Ptr (TQLCDNumber a) -> CWString -> Ptr (Ptr (TQLCDNumber x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QLCDNumber6 :: (Ptr (TQLCDNumber x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQLCDNumber x0) -> CLong -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QLCDNumber6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QLCDNumberSc a) (QLCDNumber x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QLCDNumber6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QLCDNumber6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QLCDNumber_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQLCDNumber x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qLCDNumberFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QinputMethodQuery_h (QLCDNumber ()) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLCDNumber_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QLCDNumber_inputMethodQuery" qtc_QLCDNumber_inputMethodQuery :: Ptr (TQLCDNumber a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery_h (QLCDNumberSc a) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLCDNumber_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
instance QkeyPressEvent_h (QLCDNumber ()) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_keyPressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_keyPressEvent" qtc_QLCDNumber_keyPressEvent :: Ptr (TQLCDNumber a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent_h (QLCDNumberSc a) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_keyPressEvent cobj_x0 cobj_x1
instance QkeyReleaseEvent_h (QLCDNumber ()) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_keyReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_keyReleaseEvent" qtc_QLCDNumber_keyReleaseEvent :: Ptr (TQLCDNumber a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent_h (QLCDNumberSc a) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_keyReleaseEvent cobj_x0 cobj_x1
instance QleaveEvent_h (QLCDNumber ()) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_leaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_leaveEvent" qtc_QLCDNumber_leaveEvent :: Ptr (TQLCDNumber a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent_h (QLCDNumberSc a) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_leaveEvent cobj_x0 cobj_x1
instance QqminimumSizeHint_h (QLCDNumber ()) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLCDNumber_minimumSizeHint cobj_x0
foreign import ccall "qtc_QLCDNumber_minimumSizeHint" qtc_QLCDNumber_minimumSizeHint :: Ptr (TQLCDNumber a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint_h (QLCDNumberSc a) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLCDNumber_minimumSizeHint cobj_x0
instance QminimumSizeHint_h (QLCDNumber ()) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLCDNumber_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QLCDNumber_minimumSizeHint_qth" qtc_QLCDNumber_minimumSizeHint_qth :: Ptr (TQLCDNumber a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint_h (QLCDNumberSc a) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLCDNumber_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QmouseDoubleClickEvent_h (QLCDNumber ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_mouseDoubleClickEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_mouseDoubleClickEvent" qtc_QLCDNumber_mouseDoubleClickEvent :: Ptr (TQLCDNumber a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent_h (QLCDNumberSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_mouseDoubleClickEvent cobj_x0 cobj_x1
instance QmouseMoveEvent_h (QLCDNumber ()) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_mouseMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_mouseMoveEvent" qtc_QLCDNumber_mouseMoveEvent :: Ptr (TQLCDNumber a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent_h (QLCDNumberSc a) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_mouseMoveEvent cobj_x0 cobj_x1
instance QmousePressEvent_h (QLCDNumber ()) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_mousePressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_mousePressEvent" qtc_QLCDNumber_mousePressEvent :: Ptr (TQLCDNumber a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent_h (QLCDNumberSc a) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_mousePressEvent cobj_x0 cobj_x1
instance QmouseReleaseEvent_h (QLCDNumber ()) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_mouseReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_mouseReleaseEvent" qtc_QLCDNumber_mouseReleaseEvent :: Ptr (TQLCDNumber a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent_h (QLCDNumberSc a) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_mouseReleaseEvent cobj_x0 cobj_x1
instance QmoveEvent_h (QLCDNumber ()) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_moveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_moveEvent" qtc_QLCDNumber_moveEvent :: Ptr (TQLCDNumber a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent_h (QLCDNumberSc a) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_moveEvent cobj_x0 cobj_x1
instance QsetHandler (QLCDNumber ()) (QLCDNumber x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QLCDNumber7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QLCDNumber7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QLCDNumber_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQLCDNumber x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qLCDNumberFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QLCDNumber_setHandler7" qtc_QLCDNumber_setHandler7 :: Ptr (TQLCDNumber a) -> CWString -> Ptr (Ptr (TQLCDNumber x0) -> IO (Ptr (TQPaintEngine t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QLCDNumber7 :: (Ptr (TQLCDNumber x0) -> IO (Ptr (TQPaintEngine t0))) -> IO (FunPtr (Ptr (TQLCDNumber x0) -> IO (Ptr (TQPaintEngine t0))))
foreign import ccall "wrapper" wrapSetHandler_QLCDNumber7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QLCDNumberSc a) (QLCDNumber x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QLCDNumber7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QLCDNumber7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QLCDNumber_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQLCDNumber x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qLCDNumberFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QpaintEngine_h (QLCDNumber ()) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLCDNumber_paintEngine cobj_x0
foreign import ccall "qtc_QLCDNumber_paintEngine" qtc_QLCDNumber_paintEngine :: Ptr (TQLCDNumber a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine_h (QLCDNumberSc a) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QLCDNumber_paintEngine cobj_x0
instance QresizeEvent_h (QLCDNumber ()) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_resizeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_resizeEvent" qtc_QLCDNumber_resizeEvent :: Ptr (TQLCDNumber a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent_h (QLCDNumberSc a) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_resizeEvent cobj_x0 cobj_x1
instance QsetHandler (QLCDNumber ()) (QLCDNumber x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QLCDNumber8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QLCDNumber8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QLCDNumber_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQLCDNumber x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qLCDNumberFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QLCDNumber_setHandler8" qtc_QLCDNumber_setHandler8 :: Ptr (TQLCDNumber a) -> CWString -> Ptr (Ptr (TQLCDNumber x0) -> CBool -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QLCDNumber8 :: (Ptr (TQLCDNumber x0) -> CBool -> IO ()) -> IO (FunPtr (Ptr (TQLCDNumber x0) -> CBool -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QLCDNumber8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QLCDNumberSc a) (QLCDNumber x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QLCDNumber8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QLCDNumber8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QLCDNumber_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQLCDNumber x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qLCDNumberFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetVisible_h (QLCDNumber ()) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLCDNumber_setVisible cobj_x0 (toCBool x1)
foreign import ccall "qtc_QLCDNumber_setVisible" qtc_QLCDNumber_setVisible :: Ptr (TQLCDNumber a) -> CBool -> IO ()
instance QsetVisible_h (QLCDNumberSc a) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QLCDNumber_setVisible cobj_x0 (toCBool x1)
instance QshowEvent_h (QLCDNumber ()) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_showEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_showEvent" qtc_QLCDNumber_showEvent :: Ptr (TQLCDNumber a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent_h (QLCDNumberSc a) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_showEvent cobj_x0 cobj_x1
instance QtabletEvent_h (QLCDNumber ()) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_tabletEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_tabletEvent" qtc_QLCDNumber_tabletEvent :: Ptr (TQLCDNumber a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent_h (QLCDNumberSc a) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_tabletEvent cobj_x0 cobj_x1
instance QwheelEvent_h (QLCDNumber ()) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_wheelEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QLCDNumber_wheelEvent" qtc_QLCDNumber_wheelEvent :: Ptr (TQLCDNumber a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent_h (QLCDNumberSc a) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QLCDNumber_wheelEvent cobj_x0 cobj_x1
instance QsetHandler (QLCDNumber ()) (QLCDNumber x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QLCDNumber9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QLCDNumber9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QLCDNumber_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQLCDNumber x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qLCDNumberFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QLCDNumber_setHandler9" qtc_QLCDNumber_setHandler9 :: Ptr (TQLCDNumber a) -> CWString -> Ptr (Ptr (TQLCDNumber x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QLCDNumber9 :: (Ptr (TQLCDNumber x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQLCDNumber x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QLCDNumber9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QLCDNumberSc a) (QLCDNumber x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QLCDNumber9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QLCDNumber9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QLCDNumber_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQLCDNumber x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qLCDNumberFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QeventFilter_h (QLCDNumber ()) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QLCDNumber_eventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QLCDNumber_eventFilter" qtc_QLCDNumber_eventFilter :: Ptr (TQLCDNumber a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter_h (QLCDNumberSc a) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QLCDNumber_eventFilter cobj_x0 cobj_x1 cobj_x2
|
uduki/hsQt
|
Qtc/Gui/QLCDNumber_h.hs
|
bsd-2-clause
| 56,978
| 0
| 18
| 12,269
| 18,819
| 9,078
| 9,741
| -1
| -1
|
module Main where
import Control.Applicative ((<$>))
import Data.Char
import Data.Bits
import Data.List (group)
newtype Bit = Bit Bool deriving (Eq)
instance Show Bit where
show (Bit True) = "0"
show (Bit False) = "00"
main :: IO ()
main = do input <- group . concatMap (reverse . bitsTo7Bit . ord) <$> getLine ::IO [[Bit]]
let output = concatMap (\x-> [show $ head x, replicate (length x) '0']) input
putStrLn $ unwords output
return ()
bitsTo7Bit :: Bits a => a -> [Bit]
bitsTo7Bit x = take 7 $ bitsToList x ++ repeat (Bit False)
bitsToList :: Bits a => a -> [Bit]
bitsToList x = if x == zero then []
else Bit (testBit x 0): bitsToList (x `shiftR` 1)
zero :: Bits a => a
zero = bit 1 `xor` bit 1
|
epsilonhalbe/Sammelsurium
|
Codingame/ChuckNorris/ChuckNorris.hs
|
bsd-3-clause
| 767
| 0
| 16
| 203
| 354
| 184
| 170
| 21
| 2
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
module Main where
import Protolude.Lifted hiding ((<>), catch, find, pred, try)
import Inspector
import Inspector.Cli.Args
import Options.Applicative hiding (header)
withInfo :: Parser a -> Text -> ParserInfo a
withInfo opts desc = info (helper <*> opts) $ progDesc (toS desc)
main :: IO ()
main = do
Options cmd <- execParser (parseOptions `withInfo` "Parse nginx cache files.")
case cmd of
Inspect path dumpBody -> inspect path dumpBody
Find path flags op shouldInspect -> do
let operand = fromMaybe And op
combine =
if operand == And
then allFlagsPredicate
else anyFlagsPredicate
pred = combine flags
finder =
if shouldInspect == Yes
then findInspect
else find
finder path pred
|
pbogdan/ngx-cache-inspector
|
app/Main.hs
|
bsd-3-clause
| 922
| 0
| 16
| 258
| 243
| 130
| 113
| 27
| 4
|
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Config.LXQt
-- Description : Config for integrating xmonad with LXQt.
-- Copyright : (c) Petr Shevtsov <petr.shevtsov@gmail.com>
-- License : BSD
--
-- Maintainer : none
-- Stability : unstable
-- Portability : unportable
--
-- This module provides a config suitable for use with the LXQt desktop
-- environment.
module XMonad.Config.LXQt (
-- * Usage
-- $usage
lxqtConfig,
desktopLayoutModifiers
) where
import XMonad
import XMonad.Config.Desktop
import qualified Data.Map as M
-- $usage
-- To use this module, start with the following @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad
-- > import XMonad.Config.LXQt
-- >
-- > main = xmonad lxqtConfig
--
-- For example of how to further customize @lxqtConfig@ see "XMonad.Config.Desktop".
lxqtConfig = desktopConfig
{ terminal = "qterminal"
, keys = lxqtKeys <+> keys desktopConfig }
lxqtKeys XConfig{modMask = modm} = M.fromList
[ ((modm, xK_p), spawn "lxqt-runner")
, ((modm .|. shiftMask, xK_q), spawn "lxqt-leave")
]
|
xmonad/xmonad-contrib
|
XMonad/Config/LXQt.hs
|
bsd-3-clause
| 1,207
| 0
| 9
| 242
| 145
| 97
| 48
| 13
| 1
|
-- | Main Program reads the command line options, checks the supplied
-- sif file, and pushes the dot version out to STDOUT.
{-# LANGUAGE DeriveDataTypeable #-}
module Main (main) where
import System.Console.CmdArgs
import System.Environment (getArgs, withArgs)
import System.IO
import System.FilePath
import System.Exit
import Text.Show.Pretty
import Text.PrettyPrint.Leijen as PP
import Ottar.Parser
import Ottar.Transform
-- | Get AST andn spit out a LaTeX representation.
main :: IO ()
main = do
args <- getArgs
opts <- (if null args
then withArgs ["--help"]
else id) $ cmdArgs ottarOptions
contents <- readFile $ head args
case parseOttarInput contents of
Left err -> do
putStrLn $ file opts ++ " failed to parse"
print err
exitWith (ExitFailure 1)
Right res -> do
if not (model opts)
then putStrLn ""
else do
-- if requested print the model
let fname = addExtension (file opts) ".model"
writeFile fname (ppShow res)
putStrLn $ "Model for: "
++ file opts
++ " has been written in "
++ fname
-- if requested save the output to file.
let outfmt = case null (to opts) of
True -> head ottarOuts
False -> (to opts)
case transformOttar outfmt res of
Left err -> do
print err
exitWith (ExitFailure 1)
Right (ext, doc) -> do
if null (output opts)
then print $ doc
else do
let fname = addExtension (output opts) ext
handle <- openFile fname WriteMode
hPutDoc handle doc
hClose handle
putStrLn $ "File: "
++ fname
++ " has been written."
exitSuccess
-- ----------------------------------------------------------------- [ Options ]
-- | Options the type checker takes.
data OttarOptions = OttarOptions {
to :: String, -- ^ The output format
output :: FilePath, -- ^ Output filename.
model :: Bool, -- ^ Print the resulting model
file :: FilePath -- ^ The input file.
} deriving (Show, Data, Typeable)
-- | Set default options
ottarOptions :: OttarOptions
ottarOptions = OttarOptions {
to = def
&= typ "FORMAT"
&= help "Format to output",
output = def
&= typ "FILENAME"
&= help "The name of file to write the output too.",
model = def
&= help "Save the Model",
file = def
&= typFile
&= argPos 0
}
&= summary "Ottar (C) Jan de Muijnck-Hughes 2013"
&= program "ottar"
&= details ["Ottar is a tool to parse informal security protocol narrations into other formats."
]
-- --------------------------------------------------------------------- [ EOF ]
|
jfdm/ottar
|
src/Main.hs
|
bsd-3-clause
| 3,297
| 0
| 25
| 1,344
| 629
| 318
| 311
| 74
| 7
|
module Game.Pong.Logic where
import System.Random
import Data.Maybe
import Game.Event
import Game.Vector
import Game.Pong.Core
shiftLineToEdgeOnAxis :: Vec2f -> Vec2f
-> (Vec2f,Vec2f) -> (Vec2f,Vec2f)
shiftLineToEdgeOnAxis axis size (cStart,cEnd) = (start,end)
where
start = cStart +. offset
end = cEnd +. offset
offset = factor *. diff
factor = axisSize / axisDiff
axisDiff = vmag $ diff `vproject` axis
axisSize = vmag $ (0.5*.size) `vproject` axis
diff = cEnd -. cStart
restrainTo60deg :: Vec2f -> Vec2f
restrainTo60deg v = if tooVert then corrected else v
where
-- tan(60 deg) = sqrt(3) = 0.8660254
tooVert = abs (tangent v) > 0.8660254
corrected = vmag v *. (vsgn v .*. (0.5,0.8660254))
tangent v = snd v / fst v
vsgn (x,y) = (signum x,signum y)
checkGoal :: Vec2f -> Vec2f -> Vec2f -> (Paddle,Paddle) -> Ball
-> Ball -> (Ball,Maybe Float,Maybe Side)
checkGoal ssize paddleSize ballSize (leftPaddle,rightPaddle)
startBall endBall
= (newBall,bounceFactor,scoreChange)
where
newBall
| scored = Ball (0.5 *. ssize) vzero
| bounced = Ball bounceLoc bounceVel -- Make this finish
-- the frame's
-- interpolation?
| otherwise = endBall
scored = case scoreChange of
Nothing -> False
_ -> True
scoreChange
| fst (ballLoc endBall) < fst (paddleLoc leftPaddle)
= Just RightSide
| fst (ballLoc endBall) > fst (paddleLoc rightPaddle)
= Just LeftSide
| bounced = Nothing
| otherwise = case drop 4 bounces of
[Nothing,Nothing] -> Nothing
[Nothing,_] -> Just LeftSide
_ -> Just RightSide
-- prevents bounces from being too vertical
bounceVel = restrainTo60deg bounceVelInit
bounceVelInit = (1.1*vmag (ballVel startBall))
*.vnorm (bounceLoc -. paddleLoc bouncePaddle)
bounceLoc = maybe (ballLoc endBall)
(interp (ballLoc startBall)
(ballLoc endBall))
bounceFactor
bounceFactor = listToMaybe $ catMaybes
$ zipWith check bounceds factors
check b m = if b then m else Nothing
firstJust = foldr $ flip fromMaybe
bouncePaddle = snd $ head $ filter fst
$ zip bounceds paddles
bounced = or bounceds
bounceds = map (==Just True) bounces
bounces = zipWith (fmap . onPaddle) paddles intLocs
paddles = [leftPaddle,rightPaddle,
leftPaddle,rightPaddle,
leftPaddle,rightPaddle]
onPaddle paddle (x,y) =
let py = snd $ paddleLoc paddle
h = snd paddleSize
bs = snd ballSize in
y + 0.5*bs >= py - h/2 && y - 0.5*bs <= py + h/2
intLocs = map (fmap $ interp (ballLoc startBall) (ballLoc endBall))
factors
interp start end t = start +. t *. (end -. start)
factors = zipWith ($) [edgeIntersect,edgeIntersect,
onLeftFact,onRightFact,
centerIntersect,centerIntersect]
[leftPaddleLine,rightPaddleLine,
undefined,undefined,
leftLine,rightLine]
onLeftFact = let (bx,_) = ballLoc endBall -. 0.5*.ballSize
(bvx,_) = ballVel startBall
(px,_) = paddleLoc leftPaddle
+. paddleHalfSize in
const (if bvx < 0 && bx < px then Just 1 else Nothing)
onRightFact = let (bx,_) = ballLoc endBall +. 0.5*.ballSize
(bvx,_) = ballVel startBall
(px,_) = paddleLoc rightPaddle
-. paddleHalfSize in
const (if bvx > 0 && bx > px then Just 1 else Nothing)
centerIntersect = segLineIntersect (ballLoc startBall)
(ballLoc endBall)
edgeIntersect = segLineIntersect edgeStart edgeEnd
(edgeStart,edgeEnd) = shiftLineToEdgeOnAxis
(1,0)
ballSize
(ballLoc startBall,
ballLoc endBall)
ballOffset = abs (ballSize `vdot` ballChange) *. ballChange
-- ballsgn = negate $ signum $ pBallSize p `vdot` ballChange
ballChange = ballLoc endBall -. ballLoc startBall
leftPaddleLine = Line (paddleLoc leftPaddle
+. (fst paddleHalfSize,0))
(1,0)
leftLine = Line (paddleLoc leftPaddle) (1,0)
rightPaddleLine = Line (paddleLoc rightPaddle
-. (fst paddleHalfSize,0))
(-1,0)
rightLine = Line (paddleLoc rightPaddle) (-1,0)
paddleHalfSize = 0.5 *. paddleSize
tickPong :: Float -> Pong -> Pong
tickPong _ p@Pong{pRunning=False} = p
tickPong dt p@Pong{pScreenSize=ssize,
pPaddleSize=psize,
pBallSize=bsize,
pBall=ball,
pLeftPaddle=lPaddle,
pRightPaddle=rPaddle,
pLeftDir=ldir,
pRightDir=rdir,
pLeftScore=lscore,
pRightScore=rscore,
pRandom=rand} = p{pBall=newBall,
pLeftPaddle=newLPaddle,
pRightPaddle=newRPaddle,
pLeftScore=newLScore,
pRightScore=newRScore,
pRandom=newRand,
pFactor = fact}
where
(newBall,newRand) = case score of
Nothing -> (scoredBall,rand)
_ -> let (vel,r) = randBallVel ssize rand in
(scoredBall{ballVel=vel},r)
newLScore = if score == Just LeftSide then lscore+1
else lscore
newRScore = if score == Just RightSide then rscore+1
else rscore
(scoredBall,fact,score) = checkGoal ssize psize bsize
(lPaddle,rPaddle) ball ball1
ball1 = boundBall vzero ssize (fst bsize) $ tickBall dt ball
newLPaddle = boundPaddle 0 h (snd psize)
$ tickPaddle ldir h dt lPaddle
newRPaddle = boundPaddle 0 h (snd psize)
$ tickPaddle rdir h dt rPaddle
h = snd ssize
|
Ginto8/Pong-Haskell
|
src/Game/Pong/Logic.hs
|
bsd-3-clause
| 7,138
| 0
| 19
| 3,132
| 1,848
| 992
| 856
| 141
| 7
|
module CallByName.Data where
import Control.Monad.Trans.State.Lazy
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
type Try = Either String
type Environment = M.Map String DenotedValue
empty :: Environment
empty = M.empty
initEnvironment :: [(String, DenotedValue)] -> Environment
initEnvironment = M.fromList
extend :: String -> DenotedValue -> Environment -> Environment
extend = M.insert
extendRec :: String -> [String] -> Expression -> Environment
-> StatedTry Environment
extendRec name params body = extendRecMany [(name, params, body)]
extendRecMany :: [(String, [String], Expression)] -> Environment
-> StatedTry Environment
extendRecMany lst env = do
refs <- allocMany (length lst)
let denoVals = fmap DenoRef refs
let names = fmap (\(n, _, _) -> n) lst
let newEnv = extendMany (zip names denoVals) env
extendRecMany' lst refs newEnv
where
extendRecMany' [] [] env = return env
extendRecMany' ((name, params, body):triples) (ref:refs) env = do
setRef ref (ExprProc $ Procedure params body env)
extendRecMany' triples refs env
allocMany 0 = return []
allocMany x = do
ref <- newRef (ExprBool False) -- dummy value false for allocating space
(ref:) <$> allocMany (x - 1)
apply :: Environment -> String -> Maybe DenotedValue
apply = flip M.lookup
extendMany :: [(String, DenotedValue)] -> Environment -> Environment
extendMany = flip (foldl func)
where
func env (var, val) = extend var val env
applyForce :: Environment -> String -> DenotedValue
applyForce env var = fromMaybe
(error $ "Var " `mappend` var `mappend` " is not in environment!")
(apply env var)
newtype Ref = Ref { addr::Integer } deriving(Show, Eq)
newtype Store = Store { refs::[ExpressedValue] } deriving(Show)
type StatedTry = StateT Store (Either String)
throwError :: String -> StatedTry a
throwError msg = StateT (\s -> Left msg)
initStore :: Store
initStore = Store []
newRef :: ExpressedValue -> StatedTry Ref
newRef val = do
store <- get
let refList = refs store
put $ Store (val:refList)
return . Ref . toInteger . length $ refList
deRef :: Ref -> StatedTry ExpressedValue
deRef (Ref r) = do
store <- get
let refList = refs store
findVal r (reverse refList)
where
findVal 0 (x:_) = return x
findVal 0 [] = throwError "Index out of bound when calling deref!"
findVal i (_:xs) = findVal (i - 1) xs
setRef :: Ref -> ExpressedValue -> StatedTry ()
setRef ref val = do
store <- get
let refList = refs store
let i = addr ref
newList <- reverse <$> setRefVal i (reverse refList) val
put $ Store newList
return ()
where
setRefVal _ [] _ = throwError "Index out of bound when calling setref!"
setRefVal 0 (_:xs) val = return (val:xs)
setRefVal i (x:xs) val = (x:) <$> setRefVal (i - 1) xs val
data Program = Prog Expression
deriving (Show, Eq)
data Expression =
ConstExpr ExpressedValue
| VarExpr String
| LetExpr [(String, Expression)] Expression
| BinOpExpr BinOp Expression Expression
| UnaryOpExpr UnaryOp Expression
| CondExpr [(Expression, Expression)]
| ProcExpr [String] Expression
| CallExpr Expression [Expression]
| LetRecExpr [(String, [String], Expression)] Expression
| BeginExpr [Expression]
| AssignExpr String Expression
deriving(Show, Eq)
data BinOp =
Add | Sub | Mul | Div | Gt | Le | Eq
deriving(Show, Eq)
data UnaryOp = Minus | IsZero
deriving(Show, Eq)
data Procedure = Procedure [String] Expression Environment
instance Show Procedure where
show _ = "<procedure>"
data Thunk = Thunk Expression Environment
instance Show Thunk where
show _ = "<thunk>"
data ExpressedValue = ExprNum Integer
| ExprBool Bool
| ExprProc Procedure
| ExprThunk Thunk
instance Show ExpressedValue where
show (ExprNum i) = show i
show (ExprBool b) = show b
show (ExprProc p) = show p
show (ExprThunk t) = show t
instance Eq ExpressedValue where
(ExprNum i1) == (ExprNum i2) = i1 == i2
(ExprBool b1) == (ExprBool b2) = b1 == b2
_ == _ = False
data DenotedValue = DenoRef Ref
instance Show DenotedValue where
show (DenoRef v) = show v
instance Eq DenotedValue where
DenoRef v1 == DenoRef v2 = v1 == v2
|
li-zhirui/EoplLangs
|
src/CallByName/Data.hs
|
bsd-3-clause
| 4,351
| 0
| 13
| 1,015
| 1,595
| 832
| 763
| 116
| 3
|
-- Find all incomplete tasks in my personal notes.
--
-- Original author: David Banas <capn.freako@gmail.com>
-- Original date: January 31, 2018
--
-- Copyright (c) 2018 David Banas; all rights reserved World wide.
{-# LANGUAGE RecordWildCards #-}
module Main where
import Control.Arrow ((&&&))
import Control.Exception
import Control.Monad (forM, forM_)
import Data.Semigroup ((<>))
import Options.Applicative
import System.Directory (doesFileExist, doesDirectoryExist, getDirectoryContents)
import System.FilePath ((</>))
data Opts = Opts
{ ext :: String
, srcd :: String
}
opts :: Parser Opts
opts = Opts
<$> strOption
( long "ext"
<> short 'e'
<> metavar "EXT"
<> showDefault
<> value "page"
<> help "File extension" )
<*> argument str
( metavar "FILE"
<> help "Source file/directory in which to search" )
main :: IO ()
main = findTasks =<< execParser opts'
where
opts' = info (opts <**> helper)
( fullDesc
<> progDesc "Extract incomplete tasks from personal notes."
<> header "get_tasks - a task fetcher/consolidator" )
findTasks :: Opts -> IO ()
findTasks Opts{..} = do
isFile <-doesFileExist srcd
isDir <-doesDirectoryExist srcd
if isFile then scanFile srcd
else if isDir then scanDir srcd
else error $ "Sorry, but " ++ show srcd ++ " does not exist."
scanFile :: FilePath -> IO ()
scanFile fp = catch (do
ft <- readFile fp
let strs = lines ft
tsks = filter (uncurry (&&) . (and &&& (\xs -> length xs > 4)) . zipWith (==) "- [ ]") strs
if length tsks > 0 then do putStrLn $ "\n" ++ show fp ++ ":"
putStr $ unlines tsks
else return ())
(\(SomeException _) -> return ())
scanDir :: FilePath -> IO ()
scanDir fp = do
fps <- getRecursiveContents fp
forM_ fps scanFile
-- From Ch. 9 in Real World Haskell
getRecursiveContents :: FilePath -> IO [FilePath]
getRecursiveContents topdir = do
names <- getDirectoryContents topdir
let properNames = filter (`notElem` [".", ".."]) names
paths <- forM properNames $ \name -> do
let path = topdir </> name
isDirectory <- doesDirectoryExist path
if isDirectory
then getRecursiveContents path
else return [path]
return (concat paths)
|
capn-freako/Haskell_Misc
|
NotesParse/get_tasks.hs
|
bsd-3-clause
| 2,398
| 0
| 21
| 662
| 684
| 350
| 334
| 61
| 3
|
-----------------------------------------------------------------------------
-- |
-- Module : TestSuite.Queries.Uninterpreted
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : erkokl@gmail.com
-- Stability : experimental
--
-- Testing uninterpreted value extraction
-----------------------------------------------------------------------------
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DeriveDataTypeable #-}
module TestSuite.Queries.Uninterpreted where
import Data.Generics
import Data.SBV.Control
import Utils.SBVTestFramework
-- Test suite
tests :: TestTree
tests =
testGroup "Queries.Uninterpreted"
[ goldenCapturedIO "qUninterp1" testQuery
]
testQuery :: FilePath -> IO ()
testQuery rf = do r <- runSMTWith defaultSMTCfg{verbose=True, redirectVerbose=Just rf} unint1
appendFile rf ("\n FINAL:" ++ r ++ "\nDONE!\n")
data L = A | B ()
deriving (Eq, Ord, Show, Read, Data)
instance SymWord L
instance HasKind L
instance SMTValue L
unint1 :: Symbolic String
unint1 = do (x :: SBV L) <- free_
query $ do _ <- checkSat
getUninterpretedValue x
|
josefs/sbv
|
SBVTestSuite/TestSuite/Queries/Uninterpreted.hs
|
bsd-3-clause
| 1,168
| 0
| 11
| 233
| 237
| 127
| 110
| 22
| 1
|
-- This handles the `!version` command.
module Network.Ribot.Irc.Part.Version
( versionPart
, versionCommand
) where
import Data.Version (showVersion)
import Network.IRC.Bot.BotMonad (BotMonad(..), maybeZero)
import Network.IRC.Bot.Commands (PrivMsg(..), askSenderNickName,
replyTo, sendCommand)
import Network.IRC.Bot.Log (LogLevel(Debug))
import Network.IRC.Bot.Parsec (botPrefix, parsecPart)
import Paths_ribot (version)
import Text.Parsec (ParsecT, (<|>), string, try)
-- This integrates this part into the bot.
versionPart :: BotMonad m => m ()
versionPart = parsecPart versionCommand
-- This handles parsing the command and responding.
versionCommand :: BotMonad m => ParsecT String () m ()
versionCommand = versionCommand' <|> return ()
where
versionCommand' :: BotMonad m => ParsecT String () m ()
versionCommand' = try $ do
botPrefix
string "version"
target <- maybeZero =<< replyTo
nick <- maybeZero =<< askSenderNickName
let version' = showVersion version
logM Debug $ "!version => " ++ version'
sendCommand . PrivMsg Nothing [target] $ nick ++ ", v" ++ version'
|
erochest/ribot
|
src/Network/Ribot/Irc/Part/Version.hs
|
bsd-3-clause
| 1,311
| 0
| 15
| 376
| 318
| 177
| 141
| 24
| 1
|
{-# LANGUAGE DeriveFunctor, CPP, Trustworthy, GeneralizedNewtypeDeriving #-}
-- | See "Data.Compositions.Snoc" for normal day-to-day use. This module contains the implementation of that module.
module Data.Compositions.Snoc.Internal where
import qualified Data.Compositions as C
import Prelude hiding (sum, drop, take, length, concatMap, splitAt)
import Data.Monoid
#if __GLASGOW_HASKELL__ == 708
import Data.Foldable
#endif
#if __GLASGOW_HASKELL__ >= 710
import Data.Foldable hiding (length)
#endif
{-# RULES
"drop/composed" [~2] forall n xs. composed (drop n xs) = dropComposed n xs
#-}
-- $setup
-- >>> :set -XScopedTypeVariables
-- >>> import Control.Applicative
-- >>> import Test.QuickCheck
-- >>> import qualified Data.List as List
-- >>> type Element = [Int]
-- >>> newtype C = Compositions (Compositions Element) deriving (Show, Eq)
-- >>> instance (Monoid a, Arbitrary a) => Arbitrary (Compositions a) where arbitrary = fromList <$> arbitrary
-- >>> instance Arbitrary C where arbitrary = Compositions <$> arbitrary
newtype Flip a = Flip { unflip :: a } deriving (Functor, Eq)
#if __GLASGOW_HASKELL__ >= 840
instance Semigroup a => Semigroup (Flip a) where
(Flip a) <> (Flip b) = Flip $ a <> b
instance Monoid a => Monoid (Flip a) where
mempty = Flip mempty
#else
instance Monoid a => Monoid (Flip a) where
mempty = Flip mempty
mappend (Flip a) (Flip b) = Flip (mappend b a)
#endif
-- | A /compositions list/ or /composition tree/ is a list data type
-- where the elements are monoids, and the 'mconcat' of any contiguous sublist can be
-- computed in logarithmic time.
-- A common use case of this type is in a wiki, version control system, or collaborative editor, where each change
-- or delta would be stored in a list, and it is sometimes necessary to compute the composed delta between any two versions.
--
-- This version of a composition list is strictly biased to left-associativity, in that we only support efficient snoccing
-- to the end of the list. This also means that the 'drop' operation can be inefficient. The append operation @a <> b@
-- performs O(b log (a + b)) element compositions, so you want the right-hand list @b@ to be as small as possible.
--
-- For a version biased to consing, see "Data.Compositions". This gives the opposite performance characteristics,
-- where 'take' is slow and 'drop' is fast.
--
-- __Monoid laws:__
--
-- prop> \(Compositions l) -> mempty <> l == l
-- prop> \(Compositions l) -> l <> mempty == l
-- prop> \(Compositions t) (Compositions u) (Compositions v) -> t <> (u <> v) == (t <> u) <> v
--
-- __'toList' is monoid morphism__:
--
-- prop> toList (mempty :: Compositions Element) == []
-- prop> \(Compositions a) (Compositions b) -> toList (a <> b) == toList a ++ toList b
--
newtype Compositions a = C { unC :: C.Compositions (Flip a) } deriving (Eq)
#if __GLASGOW_HASKELL__ >= 840
instance Semigroup a => Semigroup (Compositions a) where
(C a) <> (C b) = C $ b <> a
instance Monoid a => Monoid (Compositions a) where
mempyt = C mempty
#else
instance Monoid a => Monoid (Compositions a) where
mempty = C mempty
mappend (C a) (C b) = C $ b <> a
#endif
instance Foldable Compositions where
foldMap f (C x) = foldMap (f . unflip) . reverse $ toList x
instance Show a => Show (Compositions a) where
show ls = "fromList " ++ show (toList ls)
instance (Monoid a, Read a) => Read (Compositions a) where
readsPrec _ ('f':'r':'o':'m':'L':'i':'s':'t':' ':r) = map (\(a,s) -> (fromList a, s)) $ reads r
readsPrec _ _ = []
-- | Convert a compositions list into a list of elements. The other direction
-- is provided in the 'Data.Foldable.Foldable' instance. This will perform O(n log n) element compositions.
--
-- __Isomorphism to lists__:
--
-- prop> \(Compositions x) -> fromList (toList x) == x
-- prop> \(x :: [Element]) -> toList (fromList x) == x
--
-- __Is monoid morphism__:
--
-- prop> fromList ([] :: [Element]) == mempty
-- prop> \(a :: [Element]) b -> fromList (a ++ b) == fromList a <> fromList b
fromList :: Monoid a => [a] -> Compositions a
fromList = C . C.fromList . map Flip . reverse
-- | Construct a compositions list containing just one element.
--
-- prop> \(x :: Element) -> singleton x == snoc mempty x
-- prop> \(x :: Element) -> composed (singleton x) == x
-- prop> \(x :: Element) -> length (singleton x) == 1
--
-- __Refinement of singleton lists__:
--
-- prop> \(x :: Element) -> toList (singleton x) == [x]
-- prop> \(x :: Element) -> singleton x == fromList [x]
singleton :: Monoid a => a -> Compositions a
singleton = C . C.singleton . Flip
-- | Only valid if the function given is a monoid morphism
--
-- Otherwise, use @fromList . map f . toList@ (which is much slower).
unsafeMap :: (a -> b) -> Compositions a -> Compositions b
unsafeMap f = C . C.unsafeMap (fmap f) . unC
-- | Return the compositions list with the first /k/ elements removed.
-- In the worst case, performs __O(k log k)__ element compositions,
-- in order to maintain the left-associative bias. If you wish to run 'composed'
-- on the result of 'drop', use 'dropComposed' for better performance.
-- Rewrite @RULES@ are provided for compilers which support them.
--
-- prop> \(Compositions l) (Positive n) (Positive m) -> drop n (drop m l) == drop m (drop n l)
-- prop> \(Compositions l) (Positive n) (Positive m) -> drop n (drop m l) == drop (m + n) l
-- prop> \(Compositions l) (Positive n) -> length (drop n l) == max (length l - n) 0
-- prop> \(Compositions t) (Compositions u) -> drop (length t) (t <> u) == u
-- prop> \(Compositions l) -> drop 0 l == l
-- prop> \n -> drop n (mempty :: Compositions Element) == mempty
--
-- __Refinement of 'Data.List.drop'__:
--
-- prop> \(l :: [Element]) n -> drop n (fromList l) == fromList (List.drop n l)
-- prop> \(Compositions l) n -> toList (drop n l) == List.drop n (toList l)
drop :: Monoid a => Int -> Compositions a -> Compositions a
drop i (C x) = C $ C.take (C.length x - i) x
-- | Return the compositions list containing only the first /k/ elements
-- of the input, in O(log k) time.
--
-- prop> \(Compositions l) (Positive n) (Positive m) -> take n (take m l) == take m (take n l)
-- prop> \(Compositions l) (Positive n) (Positive m) -> take m (take n l) == take (m `min` n) l
-- prop> \(Compositions l) (Positive n) -> length (take n l) == min (length l) n
-- prop> \(Compositions l) -> take (length l) l == l
-- prop> \(Compositions l) (Positive n) -> take (length l + n) l == l
-- prop> \(Positive n) -> take n (mempty :: Compositions Element) == mempty
--
-- __Refinement of 'Data.List.take'__:
--
-- prop> \(l :: [Element]) n -> take n (fromList l) == fromList (List.take n l)
-- prop> \(Compositions l) n -> toList (take n l) == List.take n (toList l)
--
-- prop> \(Compositions l) (Positive n) -> take n l <> drop n l == l
take :: Monoid a => Int -> Compositions a -> Compositions a
take i (C x) = C $ C.drop (C.length x - i) x
-- | Returns the composition of the list with the first /k/ elements removed, doing only O(log k) compositions.
-- Faster than simply using 'drop' and then 'composed' separately.
--
-- prop> \(Compositions l) n -> dropComposed n l == composed (drop n l)
-- prop> \(Compositions l) -> dropComposed 0 l == composed l
dropComposed :: Monoid a => Int -> Compositions a -> a
dropComposed i (C x) = unflip $ C.takeComposed (C.length x - i) x
-- | A convenience alias for 'take' and 'drop'
--
-- prop> \(Compositions l) i -> splitAt i l == (take i l, drop i l)
{-# INLINE splitAt #-}
splitAt :: Monoid a => Int -> Compositions a -> (Compositions a, Compositions a)
splitAt i c = (take i c, drop i c)
-- | Compose every element in the compositions list. Performs only
-- O(log n) compositions.
--
-- __Refinement of 'mconcat'__:
--
-- prop> \(l :: [Element]) -> composed (fromList l) == mconcat l
-- prop> \(Compositions l) -> composed l == mconcat (toList l)
--
-- __Is a monoid morphism__:
--
-- prop> \(Compositions a) (Compositions b) -> composed (a <> b) == composed a <> composed b
-- prop> composed mempty == (mempty :: Element)
{-# INLINE[2] composed #-}
composed :: Monoid a => Compositions a -> a
composed = unflip . C.composed . unC
-- | Get the number of elements in the compositions list, in O(log n) time.
--
-- __Is a monoid morphism__:
--
-- prop> length (mempty :: Compositions Element) == 0
-- prop> \(Compositions a) (Compositions b) -> length (a <> b) == length a + length b
--
-- __Refinement of 'Data.List.length'__:
--
-- prop> \(x :: [Element]) -> length (fromList x) == List.length x
-- prop> \(Compositions x) -> length x == List.length (toList x)
length :: Compositions a -> Int
length = C.length . unC
-- | Add a new element to the end of a compositions list. Performs O(log n) element compositions.
--
-- prop> \(x :: Element) (Compositions xs) -> snoc xs x == xs <> singleton x
-- prop> \(x :: Element) (Compositions xs) -> length (snoc xs x) == length xs + 1
--
-- __Refinement of List snoc__:
--
-- prop> \(x :: Element) (xs :: [Element]) -> snoc (fromList xs) x == fromList (xs ++ [x])
-- prop> \(x :: Element) (Compositions xs) -> toList (snoc xs x) == toList xs ++ [x]
snoc :: Monoid a => Compositions a -> a -> Compositions a
snoc (C xs) x = C (C.cons (Flip x) xs)
|
liamoc/composition-tree
|
Data/Compositions/Snoc/Internal.hs
|
bsd-3-clause
| 9,218
| 0
| 16
| 1,759
| 1,138
| 651
| 487
| 44
| 1
|
{-# LANGUAGE RecordWildCards #-}
-- {-# LANGUAGE DeriveFunctor #-}
module Test.Cluster
( doCluster
, fsmw
)
where
import FV.Types ( VHMeas(..)
, HMeas(..)
, Prong(..)
, XMeas(..)
, xXMeas
, yXMeas
, XFit(..)
, Chi2(..)
, chi2Vertex
, zVertex
, rVertex
, z0Helix
)
import FV.Fit ( kAdd
, kAddF
, ksm'
, kChi2
, fit
)
import Data.Cov.Vec
import Test.Hist ( doHist )
--import Data.Text
import Prelude.Extended
import Data.Maybe ( mapMaybe
, catMaybes
)
import Data.List ( sortOn
, foldl'
, sort
)
import qualified Math.Gamma ( q )
import Text.Printf ( printf )
doCluster :: VHMeas -> IO String
doCluster vm' = do
let vm = cleanup vm'
v0 = vertex vm' -- beamspot
s =
"Test Cluster----------------------------------------------------" <> "\n"
<> "beam spot -> " <> show v0 <> "\n"
<> "# tracks -> " <> show (length <<< helices $ vm') <> "\n"
<> "# after cleanup-> " <> show (length <<< helices $ vm) <> "\n"
<> "zs " <> (show . concatMap to2fix . zs $ vm) <> "\n"
<> "rs " <> (show . concatMap to2fix . rs $ vm) <> "\n"
points xs = zip (zs xs) (rs xs)
_ <- doHist "vertices-z-r" . points $ vm
return s
-- let Node _ ht = vList vm
-- putStrLn "---------------------------------------------------------"
-- print $ vList vm
-- -- print . nProng $ p0
-- -- print . vertex . measurements $ p0
-- -- print . fitVertex $ p0
-- -- print . zip (fitChi2s p0) . map z0Helix . helices . measurements $ p0
-- case ht of
-- CEmpty -> putStrLn "CEmpty"
-- Node p1 _ -> print $ fitVertex p1
ftvtx :: Prong -> (Number, List Chi2)
ftvtx p = (zVertex . xFit . fitVertex $ p, fitChi2s p)
xFit :: XMeas -> XFit
xFit (XMeas v vv) = XFit v vv (Chi2 1e6)
gamma :: Chi2 -> Number
gamma (Chi2 c2) = Math.Gamma.q 1.0 c2
probs :: VHMeas -> [Number]
probs (VHMeas v hl) =
filter (> 0.01) $ map (gamma . chi2Vertex . kAddF (xFit v)) hl
zs :: VHMeas -> [Number]
zs (VHMeas v hl) =
filter (\x -> abs x < 10.0) $ map (zVertex . kAddF (xFit v)) hl
rs :: VHMeas -> [Number]
rs (VHMeas v hl) =
filter (\x -> abs x < 10.0) $ map (rVertex . kAddF (xFit v)) hl
cleanup :: VHMeas -> VHMeas
-- remove vm helices that are incompatible with vm vertex
cleanup (VHMeas v hl) = VHMeas v hl'
where hl' = sortOn z0Helix . mapMaybe (filtProb 0.01 v) $ hl
filtProb :: Number -> XMeas -> HMeas -> Maybe HMeas
filtProb cut v h = mh
where
-- check chi2 of this helix w/r to vertex position v
vf = kAddF (xFit v) h
zvf = zVertex vf
Chi2 chi2f = chi2Vertex vf
prob = gamma $ Chi2 (chi2f / 2.0) -- chi2 distribution with NDOF=2
good = (prob > cut) && abs zvf < 10.0
mh = if good then Just h else Nothing
-- Now the "v" parameter can be mapped over without any care for list invariants
data HList v = CEmpty | Node v (HList v) deriving (Show, Functor)
vList :: VHMeas -> HList Prong
vList vm = Node p vRight
where
(p, vmr) = cluster vm
vRight = case vmr of
Nothing -> CEmpty
Just vm' -> vList vm'
wght :: Number -> Chi2 -> Double -- weight function with Temperature t
wght t (Chi2 chi2) = w
where
chi2cut = 3.0
w = 1.0 / (1.0 + exp ((chi2 - chi2cut) / 2.0 / t))
-- cluster'' :: VHMeas -> (Prong, Maybe VHMeas)
-- cluster'' vm | trace ("--> cluster called with " <> (show . length . helices $ vm) <> " helices, initial vertex at " <> (show . vertex $ vm) ) False = undefined
-- cluster'' (VHMeas v hl) = trace (
-- "--> cluster debug:"
-- <> "\n--> cluster fit zs " <> show zs
-- <> "\n--> cluster fit vertex " <> show (fitVertex p)
-- <> "\n--> cluster # remaining helices " <> show ( length hlr) <> (show . fmap z0Helix . take 3 $ hlr)
-- ) ( p, r ) where
-- -- split off 10 h with lowest z and determine initial fit position with FSMW
-- (hl', hlr) = splitAt 10 . sortOn z0Helix $ hl
-- -- constract vertex v0 at z=z0 as starting point, using cov matrix from v
-- zs = sort <<< filter (\x -> abs x < 10.0) <<< map (zVertex <<< kAddF (xFit v)) $ hl'
-- z0 = fsmw (length zs) zs
-- XMeas _ cx0 = v
-- v0 = XMeas Vec {v= fromList [xXMeas v, yXMeas v, z0]} cx0
-- -- do the fit with v0
-- p = fit (VHMeas v0 hl')
-- r = case length hlr of
-- 0 -> Nothing
-- _ -> Just (VHMeas v hlr)
cluster :: VHMeas -> (Prong, Maybe VHMeas)
cluster vm
| trace
( "--> cluster called with "
<> (show . length . helices $ vm)
<> " helices, initial vertex at "
<> (show . vertex $ vm)
)
False
= undefined
cluster (VHMeas v hllll) = trace
( "--> cluster debug:"
<> "\n--> cluster zs=" <> take 160 (show zs)
<> "\n--> cluster z0=" <> to3fix (z0 :: Number)
<> "\n--> cluster v0=" <> show v0
<> "\n--> cluster fit v0 hl0 " <> (show . ftvtx . fit $ VHMeas v0 $ take 10 hl)
<> "\n--> cluster fit v0 hl0 " <> (show . ftvtx . fit $ VHMeas v0 $ take 10 $ drop 10 hl)
<> "\n--> cluster fit v0 hl0 " <> (show . ftvtx . fit $ VHMeas v0 $ take 10 $ drop 20 hl)
<> "\n--> cluster fit v0 hl0 " <> (show . ftvtx . fit $ VHMeas v0 $ take 10 $ drop 30 hl)
<> "\n--> cluster fit v0 hl0 " <> (show . ftvtx . fit $ VHMeas v0 $ take 10 $ drop 40 hl)
<> "\n--> cluster fit v0 hl0 " <> (show . ftvtx . fit $ VHMeas v0 $ take 10 $ drop 50 hl)
<> "\n--> cluster fit v0 hl0 " <> (show . ftvtx . fit $ VHMeas v0 $ take 10 $ drop 60 hl)
<> "\n--> cluster v1: #hl0=" <> (show . length . catMaybes $ hl0) <> " v1=" <> show v1
<> "\n--> cluster chi2s1" <> (take 160 . foldl (\s c -> s <> bDouble c) "") c21s
<> "\n--> cluster weights1" <> (take 160 . foldl (\s w -> s <> sDouble w) "") ws1
<> "\n--> cluster v2=" <> show v2
<> "\n--> cluster chi2s2" <> (take 160 . foldl (\s c -> s <> bDouble c) "") c22s
<> "\n--> cluster weights2" <> (take 160 . foldl (\s w -> s <> sDouble w) "") ws2
<> "\n--> cluster v3=" <> show v3
<> "\n--> cluster chi2s3" <> (take 160 . foldl (\s c -> s <> bDouble c) "") c23s
<> "\n--> cluster weights3" <> (take 160 . foldl (\s w -> s <> sDouble w) "") ws3
<> "\n--> cluster v4=" <> show v4
<> "\n--> cluster chi2s4" <> (take 160 . foldl (\s c -> s <> bDouble c) "") c24s
<> "\n--> cluster weights4" <> (take 160 . foldl (\s w -> s <> sDouble w) "") ws4
<> "\n--> cluster v5=" <> show v5
<> "\n-----------------------------------------------------------------"
<> "\n--> cluster #hl1=" <> (show . length . catMaybes $ hl1) <> " vv=" <> show vv
<> printf "\n--> cluster nothing=%5d just=%5d" (length hlnothing) (length hljust)
<> "\n--> cluster nProng=" <> show nProng
)
(p, r)
where
sDouble :: Double -> String
sDouble c = if c > 0.001 then to3fix c else " eps"
bDouble :: Chi2 -> String
bDouble (Chi2 c) = if c < 999.9 then to1fix c else " big"
hl = hllll
-- FSMW method to find initial z for primary vertex
zs = sort . filter (\x -> abs x < 10.0) . map (zVertex . kAddF (xFit v)) $ hl
z0 = fsmw (length zs) zs
-- constract vertex v0 at z=z0 as starting point, using cov matrix from v
XMeas _ cx0 = v
v0 = XMeas Vec {v = fromList [xXMeas v, yXMeas v, z0]} cx0
-- filter hl for v1, with starting point v0
hl0 :: [Maybe HMeas]
hl0 = map (filtProb 0.00001 v0) hl
v1 = foldl
(\v_ mh -> case mh of
Just h -> kAdd v_ h
Nothing -> v_
)
v0
hl0
kAddW' :: XMeas -> (Maybe HMeas, Number) -> XMeas
kAddW' v_ (mh, _) = case mh of
Just h -> kAdd v_ h
Nothing -> v_
annealingSchedule = [256.0, 64.0, 16.0, 4.0, 1.0]
t0 = head annealingSchedule
-- t1 = annealingSchedule !! 3
c21s = map
(\mh -> case mh of
Just h -> kChi2 v1 h
Nothing -> Chi2 0.0
)
hl0
ws1 = fmap (max 0.001 . wght t0) c21s
v2 = foldl kAddW' v1 $ zip hl0 ws1
c22s = map
(\mh -> case mh of
Just h -> kChi2 v2 h
Nothing -> Chi2 0.0
)
hl0
ws2 = fmap (max 0.001 . wght t0) c22s
v3 = foldl kAddW' v2 $ zip hl0 ws2
c23s = map
(\mh -> case mh of
Just h -> kChi2 v3 h
Nothing -> Chi2 0.0
)
hl0
ws3 = fmap (max 0.001 . wght 4.0) c23s
v4 = foldl kAddW' v3 $ zip hl0 ws3
c24s = map
(\mh -> case mh of
Just h -> kChi2 v4 h
Nothing -> Chi2 0.0
)
hl0
ws4 = fmap (max 0.001 . wght 1.0) c24s
v5 = foldl kAddW' v4 $ zip hl0 ws4
vv0 = v5
-- cut any track with prob < 0.001 w/r to v1
hl1 = map (filtProb 0.00001 vv0) hl
-- re-do filter with initial position and filtered helices
vv = foldl
(\v_ h -> case h of
Just h' -> kAdd v_ h'
Nothing -> v_
)
vv0
hl1
-- smooth with vv
ll = zip (map (ksm' vv) hl1) hl
hlnothing :: [HMeas]
hlnothing = [ h | (Nothing, h) <- ll ]
hljust :: [HMeas]
(qljust, c2just, hljust) = unzip3 [ (q, c, h) | (Just (q, c), h) <- ll ]
fitVertex = vv
fitMomenta = qljust
fitChi2s = c2just
nProng = length qljust
measurements = VHMeas v hljust
p = Prong {..}
nnn = fromIntegral (length hlnothing) `div` 3
r = if null hlnothing then Nothing else Just (VHMeas v (drop nnn hlnothing))
-- -------------------------------------------------------
-- use robust Mode finding to get initial vertex position
-- -------------------------------------------------------
-- Fraction-of Sample Mode with Weight method,
-- see Frühwirth & Waltenberger CMS Note 2007/008
--newtype WeightedPoint = WeightedPoint Number
type WeightedPoint = Number
fsmw :: Int -> List WeightedPoint -> WeightedPoint
fsmw 1 xs = head xs
fsmw 2 [x0, x1] = 0.5 * (x1 + x0)
fsmw 3 [x0, x1, x2] = case 2 * x1 - x0 - x2 of
xx | xx < 0 -> (x0 + x1) / 2.0
xx | xx > 0 -> (x1 + x2) / 2.0
_ -> x1
-- fsmw 4 [x0, x1, x2, x3] = x where
-- w = weightOfInterval [x0, x1, x2, x3]
-- w0 = weightOfInterval [x0, x1, x2]
-- w1 = weightOfInterval [x1, x2, x3]
-- x = if w0/w < w1/w then fsmw 3 [x0, x1, x2] else fsmw 3 [x1, x2, x3] `debug` (show w <> ", " <> show w0 <> ", " <> show w1)
fsmw n xs = h
where
h = if n > 6
then hsm n xs -- for large n, fall back to no-weight hsm formula
else fsmw n' xs'
where
alpha = 0.5 :: Number
n' = ceiling (fromIntegral n * alpha)
findMin
:: (WeightedPoint, Int) -> (WeightedPoint, Int) -> (WeightedPoint, Int)
findMin (w0, j0) (w, j) = if w < w0 || w0 < 0 then (w, j) else (w0, j0)
(_, j') =
foldl' findMin (-1.0, 0)
. zip
(map (\j -> weightOfInterval . take n' . drop j $ xs) [0 .. n - n'])
$ [0 ..]
xs' = take n' . drop j' $ xs -- `debug` ("fsmw--> " <> show n <> ", " <> show n' <> ", " <> show j' <> ", " <> show xs)
-- HalfSampleMode
-- see Bickel & Frühwirth, On a Fast, Robust Estimator of the Mode, 2006
-- http://ideas.repec.org/a/eee/csdana/v50y2006i12p3500-3530.html
hsm :: Int -> [WeightedPoint] -> WeightedPoint
hsm n xs = fsmw n' xs'
where
alpha = 0.5 :: Number
n' = ceiling (fromIntegral n * alpha)
xns = drop (n' - 1) xs
wmin = last xs - head xs
findMin
:: (WeightedPoint, Int) -> (WeightedPoint, Int) -> (WeightedPoint, Int)
findMin (w0, j0) (w, j) = if w < w0 then (w, j) else (w0, j0)
calcWeight :: WeightedPoint -> WeightedPoint -> WeightedPoint
calcWeight = (-)
(_, j') = foldl' findMin (wmin, 0) . zip (zipWith calcWeight xns xs) $ [0 ..]
xs' = take n' . drop j' $ xs --`debug` ("hsm---> " <> show n <> ", " <> show n' <> ", " <> show j' <> ", " <> show xs <> ", " <> show xns)
wDist :: WeightedPoint -> WeightedPoint -> WeightedPoint
wDist x0 x1 = 1.0 / sqrt (x1 - x0 + dmin) where dmin = 0.001 -- 10 µm
weightOfInterval :: [WeightedPoint] -> WeightedPoint
weightOfInterval xs = w
where --`debug` ("weightOfInterval--> " <> show xs <> ", " <> show ws <> ", " <> show w) where
ws = [ wDist x0 x1 | x0 <- xs, x1 <- xs, x1 > x0 ]
w = (last xs - head xs) / sum ws
{-
-- gamma function P(a, x) from https://wiki.haskell.org/Gamma_and_Beta_function
-- approximation is taken from [Lanczos, C. 1964 SIAM Journal on Numerical Analysis,
-- ser. B, vol. 1, pp. 86-96]
-- standard normal CDF https://www.johndcook.com/blog/haskell-erf/
erf :: Number -> Number
erf x = sign*y
where
a1 = 0.254829592
a2 = -0.284496736
a3 = 1.421413741
a4 = -1.453152027
a5 = 1.061405429
p = 0.3275911
-- Abramowitz and Stegun formula 7.1.26
sign = if x > 0
then 1
else -1
t = 1.0/(1.0 + p* abs x)
y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x)
test_erf :: Bool
test_erf = maximum [ abs(erf x - y) | (x, y) <- zip xs ys ] < epsilon
where
epsilon = 1.5e-7 -- accuracy promised by A&S
xs = [-3, -1, 0.0, 0.5, 2.1 ]
ys = [-0.999977909503,
-0.842700792950,
0.0,
0.520499877813,
0.997020533344]
-- standard normal CDF https://www.johndcook.com/blog/haskell-phi/
phi :: Number -> Number
phi x = y
where
a1 = 0.254829592
a2 = -0.284496736
a3 = 1.421413741
a4 = -1.453152027
a5 = 1.061405429
p = 0.3275911
-- Abramowitz and Stegun formula 7.1.26
sign = if x > 0
then 1
else -1
t = 1.0/(1.0 + p * abs x / sqrt 2.0)
e = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x/2.0)
y = 0.5*(sign*e + 1.0)
test_phi :: Bool
test_phi = maximum [ abs(phi x - y) | (x, y) <- zip xs ys ] < epsilon
where
epsilon = 1.5e-7 -- accuracy promised by A&S
xs = [-3, -1, 0.0, 0.5, 2.1 ]
ys = [0.00134989803163,
0.158655253931,
0.5,
0.691462461274,
0.982135579437]
-- returns the number of samples and the mean,
-- but does not directly return variance, skewness and kurtosis.
-- Instead it returns moments from which these statistics can easily be calculated
-- using the mvks function
moments (n, m1, m2, m3, m4) x = (n', m1', m2', m3', m4')
where
n' = n + 1
delta = x - m1
delta_n = delta / n'
delta_n2 = delta_n**2
t = delta*delta_n*n
m1' = m1 + delta_n
m4' = m4 + t*delta_n2*(n'*n' - 3*n' + 3) + 6*delta_n2*m2 - 4*delta_n*m3
m3' = m3 + t*delta_n*(n' - 2) - 3*delta_n*m2
m2' = m2 + t
mvsk (n, m1, m2, m3, m4) = (m1, m2/(n-1.0), (sqrt n)*m3/m2**1.5, n*m4/m2**2 - 3.0)
-}
|
LATBauerdick/fv.hs
|
src/Test/Cluster.hs
|
bsd-3-clause
| 15,886
| 0
| 64
| 5,576
| 3,872
| 2,033
| 1,839
| 235
| 11
|
module Colors (RGBColor (RGBTuple, RGBString),
toggleRGBdescription) where
data RGBColor = RGBTuple (Float, Float, Float)
| RGBString String deriving Show
toggleRGBdescription :: RGBColor -> RGBColor
toggleRGBdescription (RGBTuple (x, y, z)) =
RGBString $ "#" ++ to2digitHex x
++ to2digitHex y
++ to2digitHex z
toggleRGBdescription (RGBString s) =
let xh = [(s !! 1), (s !! 2)]
yh = [(s !! 3), (s !! 4)]
zh = [(s !! 5), (s !! 6)]
in RGBTuple (from2digitHex xh,
from2digitHex yh,
from2digitHex zh)
hexDigits :: Int -> Char
hexDigits = (!!) "0123456789abcdef"
decimalDigits :: Char -> Int
decimalDigits c = case c of
'0' -> 0
'1' -> 1
'2' -> 2
'3' -> 3
'4' -> 4
'5' -> 5
'6' -> 6
'7' -> 7
'8' -> 8
'9' -> 9
'a' -> 10
'b' -> 11
'c' -> 12
'd' -> 13
'e' -> 14
'f' -> 15
_ -> 0
-- the following function are unsafe and an implementation detail, nobody
-- should see!
-- | string must have at least 2 character and should not have more than 2.
from2digitHex :: String -> Float
from2digitHex s =
let digit1 = decimalDigits $ s !! 0
digit2 = decimalDigits $ s !! 1
in (fromIntegral digit1 * 16 + fromIntegral digit2) / 255
-- | accept only a number in [0, 1]
to2digitHex :: Float -> String
to2digitHex n =
let byte = round $ 255 * n::Int
digit1 = hexDigits (byte `div` 16)
digit2 = hexDigits (byte `mod` 16)
in [digit1, digit2]
|
garykl/Horg
|
Colors.hs
|
bsd-3-clause
| 1,887
| 0
| 11
| 821
| 512
| 278
| 234
| 50
| 17
|
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Ordinal.CA.Corpus
( corpus ) where
import Data.String
import Prelude
import Duckling.Locale
import Duckling.Ordinal.Types
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {locale = makeLocale CA Nothing}, testOptions, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (OrdinalData 1)
[ "primer"
, "primera"
, "primers"
, "primeres"
]
, examples (OrdinalData 2)
[ "segon"
, "segona"
, "segons"
, "segones"
]
, examples (OrdinalData 3)
[ "tercer"
, "tercera"
, "tercers"
, "terceres"
]
, examples (OrdinalData 4)
[ "quart"
, "quarta"
, "quarts"
, "quartes"
]
, examples (OrdinalData 5)
[ "cinquè"
, "cinquena"
, "cinquens"
, "cinquenes"
]
, examples (OrdinalData 6)
[ "sisè"
, "sisena"
, "sisens"
, "sisenes"
]
, examples (OrdinalData 7)
[ "setè"
, "setena"
, "setens"
, "setenes"
]
, examples (OrdinalData 8)
[ "vuitè"
, "vuitena"
, "vuitens"
, "vuitenes"
]
, examples (OrdinalData 9)
[ "novè"
, "novena"
, "novens"
, "novenes"
]
, examples (OrdinalData 10)
[ "desè"
, "desena"
, "desens"
, "desenes"
]
, examples (OrdinalData 11)
[ "onzè"
, "onzena"
]
, examples (OrdinalData 12)
[ "dotzè"
, "dotzena"
]
, examples (OrdinalData 13)
[ "tretzè"
, "tretzena"
]
, examples (OrdinalData 14)
[ "catorzè"
, "catorzena"
]
, examples (OrdinalData 15)
[ "quinzè"
, "quinzena"
]
, examples (OrdinalData 16)
[ "setzè"
, "setzena"
]
, examples (OrdinalData 17)
[ "dissetè"
, "dissetena"
]
, examples (OrdinalData 18)
[ "divuitè"
, "divuitena"
]
, examples (OrdinalData 19)
[ "dinovè"
, "dinovena"
]
, examples (OrdinalData 20)
[ "vintè"
, "vintena"
]
]
|
facebookincubator/duckling
|
Duckling/Ordinal/CA/Corpus.hs
|
bsd-3-clause
| 3,071
| 0
| 9
| 1,492
| 557
| 322
| 235
| 93
| 1
|
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.SGIX.PixelTiles
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/SGIX/pixel_tiles.txt SGIX_pixel_tiles> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.SGIX.PixelTiles (
-- * Enums
gl_PIXEL_TILE_BEST_ALIGNMENT_SGIX,
gl_PIXEL_TILE_CACHE_INCREMENT_SGIX,
gl_PIXEL_TILE_CACHE_SIZE_SGIX,
gl_PIXEL_TILE_GRID_DEPTH_SGIX,
gl_PIXEL_TILE_GRID_HEIGHT_SGIX,
gl_PIXEL_TILE_GRID_WIDTH_SGIX,
gl_PIXEL_TILE_HEIGHT_SGIX,
gl_PIXEL_TILE_WIDTH_SGIX
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
|
phaazon/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/SGIX/PixelTiles.hs
|
bsd-3-clause
| 886
| 0
| 4
| 99
| 58
| 45
| 13
| 10
| 0
|
{-# LANGUAGE CPP, ScopedTypeVariables, GADTs, RecordWildCards, TemplateHaskell, MultiParamTypeClasses #-}
module Llvm.Pass.DataUsage where
import Data.Maybe
import qualified Data.Set as S
import qualified Data.Map.Strict as M
import Llvm.Query.HirCxt
import qualified Compiler.Hoopl as H
import Compiler.Hoopl
import Llvm.Hir.Data
import Llvm.Hir.Print
import Llvm.ErrorLoc
import Llvm.Hir.Mangle
import Data.List(foldl')
#define FLC (FileLoc $(srcLoc))
{-|
This is a backward analysis that collects how data/ssa variables are
used, including but not limited to how pointers are passed around.
The information is needed for many analyses, so I generalize it as a
pass. The field names in DataUsage should be stable such that the
consumers of this pass won't be broken when we extend this pass to
collect different data/ssa variable usage aspects. Because of this
backward compatibility requirement, I use a very elaborate and
descriptive naming conventions:
[stack_]addrs[_storing_<what>|_captured|passed_to_va_start]
-}
data Summary g = Summary
{ -- | The addresses that store function parameters that are pointers
addrs_storing_ptr_params :: S.Set (Value g)
-- | The local addresses that store pointer parameters
, stack_addrs_storing_ptr_params :: S.Set Lname
-- | An address is captured if it's stored on stack or heap
, addrs_captured :: S.Set (Value g)
-- | An address of a local variable is stored on stack or heap
, stack_addrs_captured :: S.Set Lname
-- | The stack or heap addresses that store another addresses
, addrs_storing_ptrs :: S.Set (Value g)
-- | The addresses of local variables that stores another addresses
, stack_addrs_storing_ptrs :: S.Set Lname
-- | The addresses are passed to va_start
, addrs_passed_to_va_start :: S.Set (Value g)
-- | The addresses of a local variables that are passed to va_start
, stack_addrs_passed_to_va_start :: S.Set Lname
-- | The addresses of all stores
, addrs_storing_values :: S.Set (Value g)
-- | The addresses of local variable that store values
, stack_addrs_storing_values :: S.Set Lname
-- | The addresses that are involved in pointer arithmatic
, addrs_involving_pointer_arithmatic :: S.Set (Value g)
-- | The stack addresses that are involved in pointer arithmatic
, stack_addrs_involving_pointer_arithmatic :: S.Set Lname
-- | The constants used in a function
, constants :: S.Set (Const g)
-- | The values used as pointers
, addrs :: S.Set (Value g)
, stack_addrs :: S.Set Lname
-- | The call function info set
, callFunInfoSet :: S.Set (FunPtr g, CallFunInterface g)
, invokeFunInfoSet :: S.Set (FunPtr g, InvokeFunInterface g)
, callAsmInfoSet :: S.Set (AsmCode, CallAsmInterface g)
} deriving (Eq, Ord, Show)
data DuFact g = DuFact { summary :: Summary g
, liveness :: S.Set Lname
} deriving (Eq, Ord, Show)
data DataUsage g = DataUsage { usageSummary :: Summary g
, livenessFact :: LabelMap (S.Set Lname)
} deriving (Eq, Ord, Show)
class DataUsageUpdator g a where
update :: a -> DuFact g -> DuFact g
instance DataUsageUpdator Gname () where
update _ = id
addAddrStoringPtrParam :: Ord g => Value g -> DuFact g -> DuFact g
addAddrStoringPtrParam v du@DuFact{ summary = ds@Summary {..} } =
du { summary = ds {addrs_storing_ptr_params = S.insert v addrs_storing_ptr_params} }
addStackAddrStoringPtrParam :: Lname -> DuFact g -> DuFact g
addStackAddrStoringPtrParam v du@DuFact{ summary = ds@Summary {..} } =
du { summary = ds {stack_addrs_storing_ptr_params = S.insert v stack_addrs_storing_ptr_params} }
addAddrCaptured :: Ord g => Value g -> DuFact g -> DuFact g
addAddrCaptured v du@DuFact{ summary = ds@Summary{..} } =
du { summary = ds { addrs_captured = S.insert v addrs_captured } }
addStackAddrCaptured :: Lname -> DuFact g -> DuFact g
addStackAddrCaptured v du@DuFact{ summary = ds@Summary{..} } =
du { summary = ds {stack_addrs_captured = S.insert v stack_addrs_captured } }
addAddrStoringPtr :: Ord g => Value g -> DuFact g -> DuFact g
addAddrStoringPtr v du@DuFact{ summary = ds@Summary{..} } =
du { summary = ds {addrs_storing_ptrs = S.insert v addrs_storing_ptrs }}
addStackAddrStoringPtr :: Lname -> DuFact g -> DuFact g
addStackAddrStoringPtr v du@DuFact{ summary = ds@Summary{..}} =
du { summary = ds {stack_addrs_storing_ptrs = S.insert v stack_addrs_storing_ptrs }}
addAddrPassedToVaStart :: Ord g => Value g -> DuFact g -> DuFact g
addAddrPassedToVaStart v du@DuFact{ summary = ds@Summary{..}} =
du { summary = ds {addrs_passed_to_va_start = S.insert v addrs_passed_to_va_start }}
addStackAddrPassedToVaStart :: Lname -> DuFact g -> DuFact g
addStackAddrPassedToVaStart v du@DuFact{ summary = ds@Summary{..}} =
du { summary = ds {stack_addrs_passed_to_va_start = S.insert v stack_addrs_passed_to_va_start }}
addAddrStoringValue :: Ord g => Value g -> DuFact g -> DuFact g
addAddrStoringValue v du@DuFact{ summary = ds@Summary{..}} =
du { summary = ds {addrs_storing_values = S.insert v addrs_storing_values }}
addStackAddrStoringValue :: Lname -> DuFact g -> DuFact g
addStackAddrStoringValue v du@DuFact{ summary = ds@Summary{..}} =
du { summary = ds {stack_addrs_storing_values = S.insert v stack_addrs_storing_values }}
addAddr :: Ord g => Value g -> DuFact g -> DuFact g
addAddr v du@DuFact{ summary = ds@Summary{..}} =
du { summary = ds {addrs = S.insert v addrs}}
addStackAddr :: Lname -> DuFact g -> DuFact g
addStackAddr v du@DuFact{ summary = ds@Summary{..}} =
du { summary = ds {stack_addrs = S.insert v stack_addrs }}
addAddrInvolvingPtrArithm :: Ord g => Value g -> DuFact g -> DuFact g
addAddrInvolvingPtrArithm v du@DuFact{ summary = ds@Summary{..}} =
du { summary = ds {addrs_involving_pointer_arithmatic = S.insert v addrs_involving_pointer_arithmatic }}
addStackAddrInvolvingPtrArithm :: Lname -> DuFact g -> DuFact g
addStackAddrInvolvingPtrArithm v du@DuFact{ summary = ds@Summary{..}} =
du { summary = ds {stack_addrs_involving_pointer_arithmatic = S.insert v stack_addrs_involving_pointer_arithmatic }}
addConst :: Ord g => Value g -> DuFact g -> DuFact g
addConst (Val_const c) du@DuFact{ summary = ds@Summary{..}} =
case c of
C_u8 _ -> du
C_u16 _ -> du
C_u32 _ -> du
C_u64 _ -> du
C_u96 _ -> du
C_u128 _ -> du
C_s8 _ -> du
C_s16 _ -> du
C_s32 _ -> du
C_s64 _ -> du
C_s96 _ -> du
C_s128 _ -> du
C_int _ -> du
C_uhex_int _ -> du
C_shex_int _ -> du
C_float _ -> du
C_null -> du
C_true -> du
C_false -> du
_ -> du { summary = ds {constants = S.insert c constants }}
addConst (Val_ssa _) du = du
addLive :: Ord g => Value g -> DuFact g -> DuFact g
addLive (Val_ssa lid) du@DuFact{..} =
if S.member lid liveness then
du
else
du { liveness = S.insert lid liveness }
addLive _ du = du
killLive :: Ord g => Lname -> DuFact g -> DuFact g
killLive lid du@DuFact{..} =
if S.member lid liveness then
du { liveness = S.delete lid liveness }
else
du
addMaybeConst :: Ord g => Maybe (Value g) -> DuFact g -> DuFact g
addMaybeConst (Just c) du = addConst c du
addMaybeConst Nothing du = du
aTv :: (Value g -> DuFact g -> DuFact g) -> T t (Value g) -> DuFact g -> DuFact g
aTv f (T _ v) du = f v du
aTvs :: (Value g -> DuFact g -> DuFact g) -> [T t (Value g)] -> DuFact g -> DuFact g
aTvs f l du = foldl' (\p e -> aTv f e p) du l
aTvE :: [Value g -> DuFact g -> DuFact g] -> T t (Value g) -> DuFact g -> DuFact g
aTvE fs tv du = foldl' (\p f -> aTv f tv p) du fs
aTvsE :: [Value g -> DuFact g -> DuFact g] -> [T t (Value g)] -> DuFact g -> DuFact g
aTvsE fs l du = foldl' (\p e -> foldl' (\pp f -> aTv f e pp) p fs) du l
foldlvs :: (Value g -> DuFact g -> DuFact g) -> [Value g] -> DuFact g -> DuFact g
foldlvs f vs du = foldl' (\p e -> f e p) du vs
foldlvsE :: [Value g -> DuFact g -> DuFact g] -> [Value g] -> DuFact g -> DuFact g
foldlvsE fs vs du = foldl' (\du0 f -> foldl' (\p e -> f e p) du0 vs) du fs
foldlE :: [Value g -> DuFact g -> DuFact g] -> Value g -> DuFact g -> DuFact g
foldlE fs v du = foldl' (\du0 f -> f v du0) du fs
applyToMaybe :: (a -> DuFact g -> DuFact g) -> Maybe a -> DuFact g -> DuFact g
applyToMaybe f (Just x) du = f x du
applyToMaybe f Nothing du = du
applyToEither :: (a -> DuFact g -> DuFact g) -> (b -> DuFact g -> DuFact g)
-> Either a b -> DuFact g -> DuFact g
applyToEither fl fr (Left x) du = fl x du
applyToEither fl fr (Right x) du = fr x du
bubbleUp :: Ord x => x -> x -> S.Set x -> S.Set x
bubbleUp dest src s = if S.member dest s then S.insert src s else s
filterAlloca :: Ord g => Lname -> (Summary g -> S.Set (Value g))
-> (Lname -> DuFact g -> DuFact g) -> DuFact g -> DuFact g
filterAlloca ssa src addf du = if S.member (Val_ssa ssa) (src $ summary du) then addf ssa du else du
bubbleUp2 :: Ord g => Value g -> (Summary g -> S.Set (Value g))
-> Value g -> (Value g -> DuFact g -> DuFact g) -> DuFact g -> DuFact g
bubbleUp2 dest setf src addf du = if S.member dest (setf $ summary du) then addf src du else du
propogateUpPtrUsage :: Ord g => Lname -> Value g -> DuFact g -> DuFact g
propogateUpPtrUsage dest src du =
bubbleUp2 (Val_ssa dest) addrs_storing_ptr_params src addAddrStoringPtrParam
$ bubbleUp2 (Val_ssa dest) addrs_captured src addAddrCaptured
$ bubbleUp2 (Val_ssa dest) addrs_storing_ptrs src addAddrStoringPtr
$ bubbleUp2 (Val_ssa dest) addrs_passed_to_va_start src addAddrPassedToVaStart
$ bubbleUp2 (Val_ssa dest) addrs_storing_ptrs src addAddrStoringPtr
$ bubbleUp2 (Val_ssa dest) addrs_storing_values src addAddrStoringValue
$ bubbleUp2 (Val_ssa dest) addrs_involving_pointer_arithmatic src addAddrInvolvingPtrArithm
$ bubbleUp2 (Val_ssa dest) addrs src addAddr
du
emptyDuFact :: DuFact g
emptyDuFact =
DuFact { summary = Summary
S.empty S.empty S.empty S.empty S.empty
S.empty S.empty S.empty S.empty S.empty
S.empty S.empty S.empty S.empty S.empty
S.empty S.empty S.empty
, liveness = S.empty
}
instance (IrPrint t1, IrPrint t2, IrPrint t3) => IrPrint (t1, t2, t3) where
printIr (t1, t2, t3) = parens (printIr t1 <+> printIr t2 <+> printIr t3)
instance IrPrint g => IrPrint (Summary g) where
printIr Summary{..} =
text "addrs_storing_ptr_params:" <+> printIr addrs_storing_ptr_params
$+$ text "stack_addrs_storing_ptr_params:" <+> printIr stack_addrs_storing_ptr_params
$+$ text "addrs_captured:" <+> printIr addrs_captured
$+$ text "stack_addrs_captured:" <+> printIr stack_addrs_captured
$+$ text "addrs_storing_ptrs:" <+> printIr addrs_storing_ptrs
$+$ text "stack_addrs_storing_ptrs:" <+> printIr stack_addrs_storing_ptrs
$+$ text "addrs_passed_to_va_start:" <+> printIr addrs_passed_to_va_start
$+$ text "stack_addrs_passed_to_va_start:" <+> printIr stack_addrs_passed_to_va_start
$+$ text "addrs_storing_values:" <+> printIr addrs_storing_values
$+$ text "stack_addrs_storing_values:" <+> printIr stack_addrs_storing_values
$+$ text "addrs_involving_pointer_arithmatic:" <+> printIr addrs_involving_pointer_arithmatic
$+$ text "stack_addrs_involving_pointer_arithmatic:" <+> printIr stack_addrs_involving_pointer_arithmatic
$+$ text "constants:" <+> printIr constants
$+$ text "addrs:" <+> printIr addrs
$+$ text "stack_addrs:" <+> printIr stack_addrs
$+$ text "callInfoSet:" <+> printIr callFunInfoSet
$+$ text "callAsmSet:" <+> printIr callAsmInfoSet
instance IrPrint g => IrPrint (DuFact g) where
printIr DuFact{..} = text "summary:" <+> printIr summary
$+$ text "liveness:" <+> printIr liveness
instance IrPrint g => IrPrint (DataUsage g) where
printIr DataUsage{..} = text "usageSummary:" <+> printIr usageSummary
$+$ text "livenessFact:" <+> printIr livenessFact
usageLattice :: Ord g => H.DataflowLattice (DuFact g)
usageLattice = H.DataflowLattice
{ H.fact_name = "Data and Ssa variable Usage"
, H.fact_bot = emptyDuFact
, H.fact_join = add
}
where add _ (H.OldFact old) (H.NewFact new) =
if old == new then
(NoChange, old)
else
(SomeChange, unionDuFact old new)
unionDuFact :: Ord g => (DuFact g) -> (DuFact g) -> (DuFact g)
unionDuFact old new =
if old == emptyDuFact then
new
else if summary old == summary new then
DuFact (summary old) ((liveness old) `sUnion` (liveness new))
else
DuFact (unionSummary (summary old) (summary new)) ((liveness old) `sUnion` (liveness new))
unionSummary :: Ord g => Summary g -> Summary g -> Summary g
unionSummary old_du@(Summary s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15 s16 s17 s18)
new_du@(Summary t1 t2 t3 t4 t5 t6 t7 t8 t9 t10 t11 t12 t13 t14 t15 t16 t17 t18)
= Summary
(s1 `sUnion` t1) (s2 `sUnion` t2) (s3 `sUnion` t3)
(s4 `sUnion` t4) (s5 `sUnion` t5) (s6 `sUnion` t6)
(s7 `sUnion` t7) (s8 `sUnion` t8) (s9 `sUnion` t9)
(s10 `sUnion` t10) (s11 `sUnion` t11) (s12 `sUnion` t12)
(s13 `sUnion` t13) (s14 `sUnion` t14) (s15 `sUnion` t15)
(s16 `sUnion` t16) (s17 `sUnion` t17) (s18 `sUnion` t18)
sUnion :: (Ord v, Eq v) => S.Set v -> S.Set v -> S.Set v
sUnion s1 s2 = if S.isSubsetOf s1 s2 then
s2
else if S.isSubsetOf s2 s1 then
s1
else lUnion s2 s1
where lUnion l r = S.foldl' (\p e ->
if S.member e p then
p
else
S.insert e p
) l r
bwdScan :: forall g.forall a.forall m. (Show g, Ord g, Show a, DataUsageUpdator g a, H.FuelMonad m) =>
S.Set Lname -> H.BwdPass m (Node g a) (DuFact g)
bwdScan formalParams = H.BwdPass { H.bp_lattice = usageLattice
, H.bp_transfer = H.mkBTransfer (bwdTran formalParams)
, H.bp_rewrite = H.noBwdRewrite
}
where
bwdTran :: (Show g, Ord g) => S.Set Lname -> Node g a e x -> H.Fact x (DuFact g) -> DuFact g
bwdTran fp n f = case n of
Tnode tinst _ ->
let f0 = foldl' (\p l -> p `unionDuFact` (fromMaybe emptyDuFact $ H.lookupFact l f))
emptyDuFact (H.successors n)
in case tinst of
T_ret_void -> f0
T_return vs -> aTvsE [addConst, addLive] vs f0
T_invoke{..} ->
let vals = getValuesFromParams (fs_params $ ifi_signature invoke_fun_interface)
in applyToMaybe killLive invoke_return
$ foldlvsE [addConst, addAddrCaptured, addAddrStoringPtr, addAddrStoringValue, addLive]
(S.toList vals)
(f0 { summary = (summary f0) {invokeFunInfoSet = S.insert (invoke_ptr, invoke_fun_interface) (invokeFunInfoSet $ summary f0) }})
T_invoke_asm{..} ->
let vals = getValuesFromParams (cai_actualParams invoke_asm_interface)
in applyToMaybe killLive invoke_return
$ foldlvsE [addConst, addAddrCaptured, addAddrStoringPtr, addAddrStoringValue, addLive]
(S.toList vals)
(f0 { summary = (summary f0) { callAsmInfoSet = S.insert (invoke_asmcode, invoke_asm_interface) (callAsmInfoSet $ summary f0)}})
_ -> f0
Lnode _ -> f
Pnode (Pinst{..}) _ ->
killLive flowout
$ foldl' (\p (e,_) -> foldlE [addLive,addConst,propogateUpPtrUsage flowout] e p)
f flowins
Enode x _ -> update x f
Comment _ -> f
Cnode comp _ -> case comp of
I_alloca{..} ->
killLive result
$ applyToMaybe (\a du -> aTvE [addConst,addLive] a du) size
$ addStackAddr result
$ killLive result
$ filterAlloca result addrs_storing_ptr_params addStackAddrStoringPtrParam
$ filterAlloca result addrs_storing_ptrs addStackAddrStoringPtr
$ filterAlloca result addrs_storing_values addStackAddrStoringValue
$ filterAlloca result addrs_captured addStackAddrCaptured
$ filterAlloca result addrs_passed_to_va_start addStackAddrPassedToVaStart
$ filterAlloca result addrs_involving_pointer_arithmatic addStackAddrInvolvingPtrArithm f
I_load{..} ->
killLive result
$ aTvE [addConst, addAddrStoringValue, addAddr, addLive] pointer
f
I_loadatomic{..} ->
killLive result
$ aTvE [addConst, addAddrStoringValue, addAddr, addLive] pointer
f
I_store{..} ->
aTvE [addConst,addLive] storedvalue
$ aTvE [addConst,addAddrStoringValue,addAddr, addLive] pointer
$ case storedvalue of
T (DtypeScalarP _) sv ->
case sv of
Val_ssa v | S.member v fp -> aTv addAddrStoringPtrParam pointer $ addAddrCaptured sv f
_ -> aTv addAddrStoringPtr pointer $ addAddrCaptured sv f
_ -> f
I_storeatomic{..} ->
aTvE [addLive,addConst] storedvalue
$ aTvE [addLive,addConst, addAddrStoringValue, addAddr] pointer
$ case storedvalue of
T (DtypeScalarP _) sv ->
case sv of
Val_ssa v | S.member v fp -> aTv addAddrStoringPtrParam pointer $ addAddrCaptured sv f
_ -> aTv addAddrStoringPtr pointer $ addAddrCaptured sv f
_ -> f
I_fence{..} -> f
I_cmpxchg_I{..} -> killLive result
$ aTvE [addLive,addConst] pointer
$ aTvsE [addLive,addConst, propogateUpPtrUsage result] [cmpi,newi]
f
I_cmpxchg_F{..} -> killLive result
$ aTvE [addLive,addConst] pointer
$ aTvsE [addLive,addConst] [cmpf,newf]
f
I_cmpxchg_P{..} -> killLive result
$ aTvE [addLive,addConst] pointer
$ aTvsE [addLive,addConst, propogateUpPtrUsage result] [cmpp,newp]
f
I_atomicrmw{..} -> killLive result
$ aTvE [addLive,addConst,addAddrStoringPtr,addAddr] pointer
$ aTvE [addLive,addConst, propogateUpPtrUsage result] val
f
I_extractelement_I {..} -> killLive result
$ aTvE [addLive,addConst, propogateUpPtrUsage result] vectorI
f
I_extractelement_F {..} -> killLive result
$ aTvE [addLive,addConst] vectorF
f
I_extractelement_P {..} -> killLive result
$ aTvE [addLive,addConst,propogateUpPtrUsage result] vectorP
f
I_insertelement_I {..} -> killLive result
$ aTvE [addLive,addConst, propogateUpPtrUsage result] vectorI
$ aTvE [addLive,addConst, propogateUpPtrUsage result] elementI
f
I_insertelement_F {..} -> killLive result
$ aTvE [addLive,addConst] vectorF
$ aTvE [addLive,addConst] elementF
f
I_insertelement_P {..} -> killLive result
$ aTvE [addLive,addConst] vectorP
$ aTvE [addLive,addConst,propogateUpPtrUsage result] elementP
f
I_shufflevector_I{..} -> killLive result
$ aTvsE [addLive,addConst,propogateUpPtrUsage result] [vector1I,vector2I]
f
I_shufflevector_F{..} -> killLive result
$ aTvsE [addLive,addConst] [vector1F,vector2F]
f
I_shufflevector_P{..} -> killLive result
$ aTvsE [addLive,addConst, propogateUpPtrUsage result] [vector1P,vector2P]
f
I_extractvalue{..} -> killLive result
$ aTvE [addLive,addConst, propogateUpPtrUsage result] record
f
I_insertvalue{..} -> killLive result
$ aTvE [addLive,addConst,propogateUpPtrUsage result] record
$ aTvE [addLive,addConst,propogateUpPtrUsage result] element
f
I_landingpad{..} -> f
I_getelementptr{..} -> killLive result
$ aTvE [addLive,addConst,propogateUpPtrUsage result] pointer
$ addAddrInvolvingPtrArithm (Val_ssa result)
f
I_getelementptr_V{..} -> killLive result
$ aTvE [addLive,addConst,propogateUpPtrUsage result] vpointer
$ addAddrInvolvingPtrArithm (Val_ssa result)
f
I_icmp{..} -> killLive result
$ foldlvsE [addLive,addConst] [operand1, operand2]
f
I_icmp_V{..} -> killLive result
$ foldlvsE [addLive,addConst] [operand1, operand2]
f
I_fcmp{..} -> killLive result
$ foldlvsE [addLive,addConst] [operand1,operand2]
f
I_fcmp_V{..} -> killLive result
$ foldlvsE [addLive,addConst] [operand1,operand2]
f
I_add{..} -> killLive result
$ foldlvsE [addLive,addConst, propogateUpPtrUsage result] [operand1, operand2]
f
I_sub{..} -> killLive result
$ foldlvsE [addLive,addConst, propogateUpPtrUsage result] [operand1, operand2]
f
I_mul{..} -> killLive result
$ foldlvsE [addLive,addConst, propogateUpPtrUsage result] [operand1, operand2]
f
I_udiv{..} -> killLive result
$ foldlvsE [addLive,addConst, propogateUpPtrUsage result] [operand1, operand2]
f
I_sdiv{..} -> killLive result
$ foldlvsE [addLive,addConst, propogateUpPtrUsage result] [operand1, operand2]
f
I_urem{..} -> killLive result
$ foldlvsE [addLive,addConst, propogateUpPtrUsage result] [operand1, operand2]
f
I_srem{..} -> killLive result
$ foldlvsE [addLive,addConst,propogateUpPtrUsage result] [operand1, operand2]
f
I_shl{..} -> killLive result
$ foldlvsE [addLive,addConst,propogateUpPtrUsage result] [operand1, operand2]
f
I_lshr{..} -> killLive result
$ foldlvsE [addLive,addConst,propogateUpPtrUsage result] [operand1, operand2]
f
I_ashr{..} -> killLive result
$ foldlvsE [addLive,addConst,propogateUpPtrUsage result] [operand1, operand2]
f
I_and{..} -> killLive result
$ foldlvsE [addLive,addConst,propogateUpPtrUsage result] [operand1, operand2]
f
I_or{..} -> killLive result
$ foldlvsE [addLive,addConst,propogateUpPtrUsage result] [operand1, operand2]
f
I_xor{..} -> killLive result
$ foldlvsE [addLive,addConst,propogateUpPtrUsage result] [operand1, operand2]
f
I_add_V{..} -> killLive result
$ foldlvsE [addLive,addConst,propogateUpPtrUsage result] [operand1, operand2]
f
I_sub_V{..} -> killLive result
$ foldlvsE [addLive,addConst,propogateUpPtrUsage result] [operand1, operand2]
f
I_mul_V{..} -> killLive result
$ foldlvsE [addLive,addConst,propogateUpPtrUsage result] [operand1, operand2]
f
I_udiv_V{..} -> killLive result
$ foldlvsE [addLive,addConst,propogateUpPtrUsage result] [operand1, operand2]
f
I_sdiv_V{..} -> killLive result
$ foldlvsE [addLive,addConst,propogateUpPtrUsage result] [operand1, operand2]
f
I_urem_V{..} -> killLive result
$ foldlvsE [addLive,addConst,propogateUpPtrUsage result] [operand1, operand2]
f
I_srem_V{..} -> killLive result
$ foldlvsE [addLive,addConst,propogateUpPtrUsage result] [operand1, operand2]
f
I_shl_V{..} -> killLive result
$ foldlvsE [addLive,addConst,propogateUpPtrUsage result] [operand1, operand2]
f
I_lshr_V{..} -> killLive result
$ foldlvsE [addLive,addConst,propogateUpPtrUsage result] [operand1, operand2]
f
I_ashr_V{..} -> killLive result
$ foldlvsE [addLive,addConst,propogateUpPtrUsage result] [operand1, operand2]
f
I_and_V{..} -> killLive result
$ foldlvsE [addLive,addConst,propogateUpPtrUsage result] [operand1, operand2]
f
I_or_V{..} -> killLive result
$ foldlvsE [addLive,addConst,propogateUpPtrUsage result] [operand1, operand2]
f
I_xor_V{..} -> killLive result
$ foldlvsE [addLive,addConst,propogateUpPtrUsage result] [operand1, operand2]
f
I_fadd{..} -> killLive result
$ foldlvsE [addLive,addConst] [operand1, operand2]
f
I_fsub{..} -> killLive result
$ foldlvsE [addLive,addConst] [operand1, operand2]
f
I_fmul{..} -> killLive result
$ foldlvsE [addLive,addConst] [operand1, operand2]
f
I_fdiv{..} -> killLive result
$ foldlvsE [addLive,addConst] [operand1, operand2]
f
I_frem{..} -> killLive result
$ foldlvsE [addLive,addConst] [operand1, operand2]
f
I_fadd_V{..} -> killLive result
$ foldlvsE [addLive,addConst] [operand1, operand2]
f
I_fsub_V{..} -> killLive result
$ foldlvsE [addLive,addConst] [operand1, operand2]
f
I_fmul_V{..} -> killLive result
$ foldlvsE [addLive,addConst] [operand1, operand2]
f
I_fdiv_V{..} -> killLive result
$ foldlvsE [addLive,addConst] [operand1, operand2]
f
I_frem_V{..} -> killLive result
$ foldlvsE [addLive,addConst] [operand1, operand2]
f
I_trunc{..} -> killLive result
$ aTvE [addLive,addConst] srcI f
I_zext{..} -> killLive result
$ aTvE [addLive, addConst] srcI f
I_sext{..} -> killLive result
$ aTvE [addLive,addConst] srcI f
I_fptrunc{..} -> killLive result
$ aTvE [addLive, addConst] srcF f
I_fpext{..} -> killLive result
$ aTvE [addLive, addConst] srcF f
I_fptoui{..} -> killLive result
$ aTvE [addLive, addConst] srcF f
I_fptosi{..} -> killLive result
$ aTvE [addLive, addConst] srcF f
I_uitofp{..} -> killLive result
$ aTvE [addLive, addConst] srcI f
I_sitofp{..} -> killLive result
$ aTvE [addLive, addConst] srcI f
I_ptrtoint{..} -> killLive result
$ aTvE [addLive, addConst, propogateUpPtrUsage result] srcP
f
I_inttoptr{..} -> killLive result
$ aTvE [addLive, addConst, propogateUpPtrUsage result] srcI
f
I_addrspacecast{..} -> killLive result
$ aTvE [addLive, addConst, propogateUpPtrUsage result] srcP
f
I_bitcast{..} -> killLive result
$ aTvE [addLive, addConst, propogateUpPtrUsage result] srcP
f
I_bitcast_D{..} -> killLive result
$ aTvE [addLive, addConst, propogateUpPtrUsage result] srcD
f
I_trunc_V{..} -> killLive result $ aTvE [addLive, addConst] srcVI f
I_zext_V{..} -> killLive result $ aTvE [addLive, addConst] srcVI f
I_sext_V{..} -> killLive result $ aTvE [addLive, addConst] srcVI f
I_fptrunc_V{..} -> killLive result $ aTvE [addLive, addConst] srcVF f
I_fpext_V{..} -> killLive result $ aTvE [addLive, addConst] srcVF f
I_fptoui_V{..} -> killLive result $ aTvE [addLive, addConst] srcVF f
I_fptosi_V{..} -> killLive result $ aTvE [addLive, addConst] srcVF f
I_uitofp_V{..} -> killLive result $ aTvE [addLive, addConst] srcVI f
I_sitofp_V{..} -> killLive result $ aTvE [addLive, addConst] srcVI f
I_ptrtoint_V{..} -> killLive result
$ aTvE [addLive, addConst, propogateUpPtrUsage result] srcVP f
I_inttoptr_V{..} -> killLive result
$ aTvE [addLive, addConst, propogateUpPtrUsage result] srcVI f
I_addrspacecast_V{..} -> killLive result
$ aTvE [addLive, addConst, propogateUpPtrUsage result] srcVP f
I_select_I{..} -> killLive result
$ aTvE [addLive,addConst] cond
$ aTvsE [addLive,addConst,propogateUpPtrUsage result] [trueI,falseI]
f
I_select_F{..} -> killLive result
$ aTvE [addLive,addConst] cond
$ aTvsE [addLive, addConst] [trueF,falseF]
f
I_select_P{..} -> killLive result
$ aTvE [addLive,addConst] cond
$ aTvsE [addLive,addConst, propogateUpPtrUsage result] [trueP, falseP]
f
I_select_First{..} -> killLive result
$ aTvE [addLive,addConst] cond
$ aTvsE [addLive,addConst, propogateUpPtrUsage result] [trueFirst, falseFirst]
f
I_select_VI{..} -> killLive result
$ applyToEither (aTvE [addLive,addConst]) (aTvE [addLive,addConst]) condVI
$ aTvsE [addLive,addConst, propogateUpPtrUsage result] [trueVI,falseVI]
f
I_select_VF{..} -> killLive result
$ applyToEither (aTvE [addLive,addConst]) (aTvE [addLive,addConst]) condVF
$ aTvsE [addLive,addConst] [trueVF, falseVF]
f
I_select_VP{..} -> killLive result
$ applyToEither (aTvE [addLive,addConst]) (aTvE [addLive,addConst]) condV
$ aTvsE [addLive,addConst, propogateUpPtrUsage result] [trueVP, falseVP]
f
I_call_fun{..} ->
let vals = getValuesFromParams (fs_params $ cfi_signature call_fun_interface)
in applyToMaybe killLive call_return
$ foldlvsE [addConst,addAddrCaptured,addAddrStoringPtr,addAddrStoringValue,addLive]
(S.toList vals)
(f { summary = (summary f) { callFunInfoSet = S.insert (call_ptr, call_fun_interface) (callFunInfoSet $ summary f) }})
I_call_asm{..} ->
let vals = getValuesFromParams (cai_actualParams call_asm_interface)
in applyToMaybe killLive call_return
$ foldlvsE [addConst, addAddrCaptured, addAddrStoringPtr, addAddrStoringValue, addLive]
(S.toList vals)
(f { summary = (summary f) { callAsmInfoSet = S.insert (call_asmcode, call_asm_interface) (callAsmInfoSet $ summary f)}})
I_va_arg{..} -> aTvE [addLive, addConst, addAddrPassedToVaStart] dv f
I_llvm_va_start v -> foldlE [addLive, addConst, addAddrPassedToVaStart] v f
I_llvm_va_end v -> foldlE [addLive, addConst, addAddrPassedToVaStart] v f
I_llvm_va_copy{..} -> foldlvsE [addLive,addConst, addAddrPassedToVaStart] [srcarglist,destarglist] f
I_llvm_memcpy{..} -> aTvsE [addLive,addConst, addAddrCaptured] [src,dest]
$ aTv addAddrStoringValue dest
f
I_llvm_memmove{..} -> aTvsE [addLive,addConst, addAddrCaptured] [src,dest]
$ aTv addAddrStoringValue dest
f
I_llvm_memset{..} -> aTvE [addLive,addConst, addAddrCaptured,addAddrStoringValue] dest
$ aTvE [addLive,addConst] setValue
f
I_llvm_read_register{..} -> f
I_llvm_write_register{..} -> f
I_llvm_stacksave{..} -> f
I_llvm_stackrestore{..} -> f
I_llvm_libm_una{..} -> f
I_llvm_libm_bin{..} -> f
I_llvm_powi{..} -> f
I_llvm_ctpop { dv = d } -> aTvE [addLive, addConst] d f
I_llvm_lifetime_start { objsize = os, pointer = ptr } -> aTvE [addLive, addConst] os
$ aTvE [addLive, addConst] ptr f
I_llvm_lifetime_end { objsize = os, pointer = ptr } -> aTvE [addLive, addConst] os
$ aTvE [addLive, addConst] ptr f
_ -> errorLoc FLC $ show n ++ " is not supported."
Mnode _ _ -> f
#ifdef DEBUG
_ -> errorLoc FLC $ show n
#endif
getValuesFromParams :: [FunOperand (Value g)] -> S.Set (Value g)
getValuesFromParams ls = foldl' (\p e -> case e of
FunOperandAsRet _ _ _ v -> S.insert v p
FunOperandData _ _ _ v -> S.insert v p
FunOperandByVal _ _ _ v -> S.insert v p
_ -> p
) S.empty ls
scanGraph :: (H.CheckpointMonad m, H.FuelMonad m, Show g, Ord g, Show a, DataUsageUpdator g a) => S.Set Lname
-> Label -> H.Graph (Node g a) H.C H.C -> m (DataUsage g)
scanGraph fm entry graph =
do { (_, a, _) <- H.analyzeAndRewriteBwd (bwdScan fm) (H.JustC [entry]) graph H.mapEmpty
; let entryD = fromJust (H.lookupFact entry a)
; return (DataUsage { usageSummary = summary entryD
, livenessFact = mapMap liveness a
}
)
}
scanDefine :: (CheckpointMonad m, FuelMonad m, Show g, Ord g, Show a, DataUsageUpdator g a) => IrCxt g
-> TlDefine g a -> m (DataUsage g)
scanDefine s (TlDefine fn entry graph) = scanGraph formalParamIds entry graph
where formalParamIds :: S.Set Lname
formalParamIds = let FunSignature { fs_params = r} = fi_signature fn
in foldl' (\p x -> case x of
FunOperandAsRet (DtypeScalarP _) _ _ v -> S.insert v p
FunOperandData (DtypeScalarP _) _ _ v -> S.insert v p
FunOperandByVal (DtypeScalarP _) _ _ v -> S.insert v p
_ -> p
) S.empty r
scanModule :: (H.CheckpointMonad m, H.FuelMonad m, Show g, Ord g, Show a, DataUsageUpdator g a) =>
Module g a -> IrCxt g -> m (M.Map (FunctionInterface g) (DataUsage g))
scanModule (Module l) ic =
do { l0 <- mapM (\x -> case x of
ToplevelDefine def@(TlDefine fn _ _) ->
do { fct <- scanDefine ic def
; return (M.insert fn fct M.empty)
}
_ -> return M.empty
) l
; return $ M.unions l0
}
|
mlite/hLLVM
|
src/Llvm/Pass/DataUsage.hs
|
bsd-3-clause
| 37,166
| 0
| 39
| 12,666
| 11,383
| 5,819
| 5,564
| 639
| 134
|
#!/usr/bin/env runhaskell
module Main where
import Control.Monad (forever)
import Data.List (sortOn)
import Lib
import System.Environment
import System.IO (hFlush, stdout)
alphabet :: String
alphabet = ['a'..'z']
main :: IO ()
main = do
args <- getArgs
dict <- getDict args
case length args of
2 -> printOrdered words
where chars = args !! 1
words = spellableWords chars alphabet dict
_ -> interactive dict alphabet
getDict :: [FilePath] -> IO [String]
getDict args =
case length args of
0 -> readDict "/usr/share/dict/words"
_ -> readDict $ head args
readDict :: FilePath -> IO [String]
readDict fileName = do
file <- readFile fileName
return $ lines file
printOrdered :: [String] -> IO ()
printOrdered words =
mapM_ putStrLn $ lengthOrdered words
lengthOrdered :: [[a]] -> [[a]]
lengthOrdered = sortOn length
interactive :: [String] -> String -> IO b
interactive dict alphabet = forever $ do
putStr "> "
hFlush stdout
chars <- getLine
showRes chars alphabet dict
putStrLn $ concat $ replicate (length chars) "-"
putStrLn chars
showRes :: String -> String -> [String] -> IO ()
showRes chars alphabet dict = do
let spellable = spellableWords chars alphabet dict
case length $ words chars of
1 -> printOrdered spellable
_ -> printOrderedAndPrioritizedWords chars (head $ words chars) spellable
printOrderedAndPrioritizedWords :: String -> String -> [String] -> IO ()
printOrderedAndPrioritizedWords chars prioritized spellable = do
let lOrdered = lengthOrdered spellable
mapM_ (printOrderedAndPrioritizedWord chars prioritized) lOrdered
printOrderedAndPrioritizedWord :: String -> String -> String -> IO ()
printOrderedAndPrioritizedWord chars prioritized word = do
putStr word
putStrLn
(if hasAllChars word prioritized then
concat (replicate (32 - length word) " ") ++ word
else "")
|
rashack/alpha-words.hs
|
app/Main.hs
|
bsd-3-clause
| 1,890
| 0
| 16
| 376
| 649
| 319
| 330
| 56
| 2
|
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
module NHorn.NaturalHornExts (
AxiomRule,
Trans,
axim,
trans
) where
import Text.PrettyPrint.Leijen
import NHorn.LaCarte
import NHorn.Sequent
import NHorn.NaturalHorn
import NHorn.NaturalHornPretty
import Term
data Trans a s f ala = Trans ala ala
data AxiomRule a s f ala = AxiomRule (a s f)
instance (Theory a s f) => Functor (Trans a s f) where
fmap f (Trans x y) = Trans (f x) (f y)
instance (Theory a s f) => Functor (AxiomRule a s f) where
fmap f (AxiomRule a) = AxiomRule a
instance Theory a s f => Proof Trans a s f where
proofA (Trans rl rr) = do
(Seq vs1 x1 (a :== c1)) <- rl
(Seq vs2 x2 (c2 :== b)) <- rr
check x1 x2
if c1 == c2 then createSeq x1 (a :== b)
else Left $ "Trans doesn't apply " ++ show c1 ++ " and " ++ show c2
where check x1 x2 | x1 == x2 = Right ()
| otherwise = Left $ "Contexts in trans must be the same: " ++ show x1 ++ " and " ++ show x2
instance (Theory a s f) => Proof AxiomRule a s f where
proofA (AxiomRule s) = do
a <- axiom s
typeCheckSeq a
varsCheckS a
return a
axim :: (AxiomRule :<: e) a s f => a s f -> Expr (e a s f)
axim ax = In $ inj $ AxiomRule ax
trans :: (Trans :<: e) a s f => Expr (e a s f) -> Expr (e a s f) -> Expr (e a s f)
trans a b = In $ inj $ Trans a b
instance Theory a s f => Prettier Trans a s f where
pretty' (Trans l r) = text "trans" <> parens (pretty l <> comma <+> pretty r)
instance Theory a s f => Prettier AxiomRule a s f where
pretty' (AxiomRule ax) = text $ name ax
|
esengie/algebraic-checker
|
src/NHorn/NaturalHornExts.hs
|
bsd-3-clause
| 1,784
| 2
| 12
| 525
| 743
| 372
| 371
| 45
| 1
|
module Cryptol.ModuleM
( ModuleM
, liftCmd
, io
, runModuleM
, checkExpr
, evalExpr
, satProve
, loadModuleByPath
, loadPrelude
, getEvalEnv
, getPrimMap
, renameInteractive
, typeCheckInteractive
) where
import Cryptol.ModuleSystem (ModuleCmd, initialModuleEnv)
import Cryptol.ModuleSystem.Base (TCAction(TCAction, tcAction, tcLinter, tcPrims), evalExpr, exprLinter, getPrimMap, rename, typecheck)
import Cryptol.ModuleSystem.Monad (ImportSource(FromModule), ModuleM, ModuleT(ModuleT), getEvalEnv, io)
import Cryptol.ModuleSystem.Renamer (RenameM)
import Cryptol.Symbolic (ProverCommand, ProverResult)
import Cryptol.TypeCheck (tcExpr)
import Cryptol.Utils.Ident (preludeName, interactiveName)
import MonadLib (get, inBase, put, raise, set)
import qualified Cryptol.ModuleSystem as Cmd
import qualified Cryptol.ModuleSystem.Monad as Base
import qualified Cryptol.Parser.AST as P
import qualified Cryptol.Symbolic as Symbolic
import qualified Cryptol.TypeCheck.AST as TC
liftCmd :: ModuleCmd a -> ModuleM a
liftCmd f = ModuleT $ do
env <- get
(res, ws) <- inBase (f env)
put ws
case res of
Left err -> raise err
Right (val, env') -> val <$ set env'
checkExpr :: P.Expr P.PName -> ModuleM (TC.Expr, TC.Schema)
checkExpr parsed = (\(_, e, s) -> (e, s)) <$> liftCmd (Cmd.checkExpr parsed)
satProve :: ProverCommand -> ModuleM ProverResult
satProve = liftCmd . Symbolic.satProve
findModule :: P.ModName -> ModuleM FilePath
findModule = liftCmd . Cmd.findModule
loadModuleByPath :: FilePath -> ModuleM TC.Module
loadModuleByPath = liftCmd . Cmd.loadModuleByPath
runModuleM :: ModuleM a -> IO (Cmd.ModuleRes a)
runModuleM act = do
env <- initialModuleEnv
Base.runModuleM env act
loadPrelude :: ModuleM ()
loadPrelude = findModule preludeName >>= loadModuleByPath >> return ()
renameInteractive :: RenameM a -> ModuleM a
renameInteractive act = do
(_, namingEnv, _) <- Base.getFocusedEnv
rename interactiveName namingEnv act
typeCheckInteractive :: P.Expr TC.Name -> ModuleM (TC.Expr, TC.Schema)
typeCheckInteractive expr = do
pm <- getPrimMap
(ifaceDecls, _, _) <- Base.getFocusedEnv
let act = TCAction { tcAction = tcExpr, tcLinter = exprLinter, tcPrims = pm }
Base.loading (FromModule interactiveName) (typecheck act expr ifaceDecls)
|
GaloisInc/cryfsm
|
Cryptol/ModuleM.hs
|
bsd-3-clause
| 2,329
| 0
| 12
| 384
| 736
| 412
| 324
| 59
| 2
|
module Shared.String
( substring
) where
substring :: String -> String -> Bool
substring _ [] = False
substring xs ys
| prefix xs ys = True
| substring xs (tail ys) = True
| otherwise = False
prefix :: String -> String -> Bool
prefix [] _ = True
prefix _ [] = False
prefix (x:xs) (y:ys) = (x == y) && prefix xs ys
|
Rydgel/advent-of-code-2016
|
src/Shared/String.hs
|
bsd-3-clause
| 330
| 0
| 10
| 82
| 163
| 82
| 81
| 12
| 1
|
import Control.Monad (replicateM_)
import qualified Network.Transport.TCP as TCP
import Control.Distributed.Process
import Control.Distributed.Process.Internal.Types (NodeId(..))
import Control.Distributed.Process.Node
import Control.Concurrent (newEmptyMVar, takeMVar, putMVar)
import Control.Concurrent.Async
import Pipes
import qualified Pipes.Prelude as PP
import TPar.Server
import TPar.Server.Types
import TPar.Types
singleNode :: IO ()
singleNode = do
Right transport <- TCP.createTransport "localhost" "0" TCP.defaultTCPParameters
node <- newLocalNode transport initRemoteTable
runProcess node $ do
iface <- runServer
replicateM_ 1 $ spawnLocal $ runRemoteWorker iface
replicateM_ 100 $ do
prod <- enqueueAndFollow iface jobReq
runEffect $ prod >-> PP.drain
jobReq = JobRequest { jobName = JobName "hello"
, jobPriority = Priority 0
, jobCommand = "echo"
, jobArgs = ["hello", "world"]
, jobCwd = "."
, jobEnv = Nothing
}
multiNode :: IO ()
multiNode = do
Right transport1 <- TCP.createTransport "localhost" "9000" TCP.defaultTCPParameters
node1 <- newLocalNode transport1 initRemoteTable
ifaceVar <- newEmptyMVar
doneVar <- newEmptyMVar
async $ runProcess node1 $ do
iface <- runServer
liftIO $ putMVar ifaceVar iface
liftIO $ takeMVar doneVar
iface <- takeMVar ifaceVar
let nid = NodeId (TCP.encodeEndPointAddress "localhost" "9000" 0)
Right transport2 <- TCP.createTransport "localhost" "0" TCP.defaultTCPParameters
node2 <- newLocalNode transport2 initRemoteTable
async $ runProcess node2 $ do
(sq, rq) <- newChan :: Process (SendPort ServerIface, ReceivePort ServerIface)
nsendRemote nid "tpar" sq
iface <- receiveChan rq
replicateM_ 1 $ spawnLocal $ runRemoteWorker iface
Right transport3 <- TCP.createTransport "localhost" "0" TCP.defaultTCPParameters
node3 <- newLocalNode transport3 initRemoteTable
runProcess node3 $ do
replicateM_ 100 $ do
prod <- enqueueAndFollow iface jobReq
runEffect $ prod >-> PP.print
putMVar doneVar ()
main :: IO ()
main = multiNode
|
bgamari/tpar
|
Benchmark.hs
|
bsd-3-clause
| 2,329
| 2
| 14
| 603
| 634
| 308
| 326
| 56
| 1
|
module Main where
import System.Environment
import Zipper
import Execution
sourceToList :: [Char] -> [Term]
sourceToList source = foldr charToTermList [] source
where charToTermList :: Char -> [Term] -> [Term]
charToTermList '+' tail' = (Incr : tail')
charToTermList '-' tail' = (Decr : tail')
charToTermList '>' tail' = (Next : tail')
charToTermList '<' tail' = (Prev : tail')
charToTermList '.' tail' = (Read : tail')
charToTermList ',' tail' = (Write : tail')
charToTermList '[' tail' = (Open : tail')
charToTermList ']' tail' = (Close : tail')
charToTermList _ tail' = tail'
main :: IO ()
main =
do
args <- getArgs
program <- getProgName
case length args of
0 -> putStrLn ("Usage: " ++ program ++ " <source.hs>")
_ ->
do
let sourceFile = head args
source <- readFile sourceFile
_ <- process (zipperFromList (sourceToList source)) (zipper 0)
pure ()
|
rodneyp290/Brainfunc
|
app/Main.hs
|
bsd-3-clause
| 1,022
| 0
| 17
| 308
| 339
| 173
| 166
| 29
| 9
|
-----------------------------------------------------------------------------
-- |
-- Copyright : (c) 2012 Duncan Coutts, Bernie Pope, Mikolaj Konarski
-- License : BSD-style
-- Maintainer : florbitous@gmail.com
-- Stability : experimental
-- Portability : ghc
--
-- A tool to help profiling a Haskell program using Linux 'perf',
-- ghc-events and, eventually, Threadscope.
--
-- The ghc-events-perf tool has a couple of commands
-- for obtaining 'perf' performance data for a Haskell program,
-- translating it to the ghc-events format, synchronizing and merging
-- with the standard ghc-events eventlog for the Haskell program,
-- and so making the data ready for display in Threadscope.
--
-- Usage:
--
-- > ghc-events-perf command command-args
--
-- Getting help:
--
-- > ghc-events-perf help
-- > ghc-events-perf help command
-----------------------------------------------------------------------------
module Main where
import System.Posix.Process
import System.Environment
import System.Exit
import System.FilePath
import System.Process
import System.IO (hPutStrLn, stderr)
import Control.Monad
main :: IO ()
main = getArgs >>= command
command :: [String] -> IO ()
command [helpString] | helpString `elem` ["-h", "--help", "help"] =
putStrLn usage
command ["help", "help"] =
putStrLn "Helps."
command ["help", "record"] = do
let args = ["+GhcEventsPerf", "-h"]
executeFile "ghc-events-perf-record" True args Nothing
command ["help", "convert"] =
putStr $ unlines $
[ "Usage: ghc-events-perf convert program-name [out-file perf-file eventlog-file]"
, " program-name the name of the profiled Haskell program"
, " out-file where to save the resulting compound eventlog"
, " perf-file path to the perf data file for the Haskell program"
, " eventlog-file path to the GHC RTS eventlog of the Haskell program"
]
command ("record" : args) = do
myPath <- getExecutablePath
let commonPath = fst $ splitFileName myPath
-- We assume ghc-events-perf-record is in the same directory
-- as ghc-events-perf. Needed for 'sudo', because root needn't
-- have user's ~/.cabal/bin in his PATH.
recordPath = combine commonPath "ghc-events-perf-record"
recordArgs = "--RTS" : args
executeFile recordPath True recordArgs Nothing
command ["convert", program_name, out_file, perf_file, eventlog_file] = do
let sync_eventlog_file = program_name ++ ".perf.eventlog"
syncArgs = [ program_name
, perf_file
, sync_eventlog_file
]
putStrLn "Translating and synchronizing..."
syncHandle <- runProcess "ghc-events-perf-sync" syncArgs
Nothing Nothing Nothing Nothing Nothing
void $ waitForProcess syncHandle
let mergeArgs = [ "merge"
, out_file
, eventlog_file
, sync_eventlog_file
]
putStrLn "Merging with the standard eventlog..."
executeFile "ghc-events" True mergeArgs Nothing
command ["convert", program_name] = do
let out_file = program_name ++ ".total.eventlog"
perf_file = "data.perf" -- the same as defaultPerfOutputFile in record
eventlog_file = program_name ++ ".eventlog"
command ["convert", program_name, out_file, perf_file, eventlog_file]
command _ = putStrLn usage >> die "Unrecognized command"
usage :: String
usage = "Usage: ghc-events-perf command command-args\n\nThe available commands are: record convert help.\n\nSee 'ghc-events-perf help command' for more information on a specific command."
-- Exit the program with an error message.
die :: String -> IO a
die s = hPutStrLn stderr s >> exitWith (ExitFailure 1)
|
Mikolaj/haskell-linux-perf
|
ghc-events-perf/ghc-events-perf.hs
|
bsd-3-clause
| 3,706
| 0
| 11
| 759
| 569
| 314
| 255
| 56
| 1
|
module Test.SymExec where
import Program.List (nil, revAcco, reverso)
import Program.Programs (doubleAppendo)
import Syntax
import Transformer.SymbolicExecution
dA = Program doubleAppendo $ fresh ["x", "y", "z", "r"] (call "doubleAppendo" [V "x", V "y", V "z", V "r"])
revAcco' = Program revAcco $ fresh ["x", "y"] (call "revacco" [V "x", nil, V "y"])
rev = Program reverso $ fresh ["x", "y"] (call "reverso" [V "x", V "y"])
unit_symExec = do
transform 5 "da" dA
transform 5 "rev" rev
transform 5 "revAcco" revAcco'
|
kajigor/uKanren_transformations
|
test/auto/Test/SymExec.hs
|
bsd-3-clause
| 596
| 0
| 10
| 159
| 225
| 118
| 107
| 12
| 1
|
{-
(c) The University of Glasgow 2006-2012
(c) The GRASP Project, Glasgow University, 1992-1998
-}
-- | This module defines classes and functions for pretty-printing. It also
-- exports a number of helpful debugging and other utilities such as 'trace' and 'panic'.
--
-- The interface to this module is very similar to the standard Hughes-PJ pretty printing
-- module, except that it exports a number of additional functions that are rarely used,
-- and works over the 'SDoc' type.
module Outputable (
-- * Type classes
Outputable(..), OutputableBndr(..),
-- * Pretty printing combinators
SDoc, runSDoc, initSDocContext,
docToSDoc,
interppSP, interpp'SP,
pprQuotedList, pprWithCommas, quotedListWithOr, quotedListWithNor,
pprWithBars,
empty, isEmpty, nest,
char,
text, ftext, ptext, ztext,
int, intWithCommas, integer, float, double, rational, doublePrec,
parens, cparen, brackets, braces, quotes, quote,
doubleQuotes, angleBrackets, paBrackets,
semi, comma, colon, dcolon, space, equals, dot, vbar,
arrow, larrow, darrow, arrowt, larrowt, arrowtt, larrowtt,
lparen, rparen, lbrack, rbrack, lbrace, rbrace, underscore,
blankLine, forAllLit, kindStar, bullet,
(<>), (<+>), hcat, hsep,
($$), ($+$), vcat,
sep, cat,
fsep, fcat,
hang, hangNotEmpty, punctuate, ppWhen, ppUnless,
speakNth, speakN, speakNOf, plural, isOrAre, doOrDoes,
unicodeSyntax,
coloured, keyword,
-- * Converting 'SDoc' into strings and outputing it
printSDoc, printSDocLn, printForUser, printForUserPartWay,
printForC, bufLeftRenderSDoc,
pprCode, mkCodeStyle,
showSDoc, showSDocUnsafe, showSDocOneLine,
showSDocForUser, showSDocDebug, showSDocDump, showSDocDumpOneLine,
showSDocUnqual, showPpr,
renderWithStyle,
pprInfixVar, pprPrefixVar,
pprHsChar, pprHsString, pprHsBytes,
primFloatSuffix, primCharSuffix, primWordSuffix, primDoubleSuffix,
primInt64Suffix, primWord64Suffix, primIntSuffix,
pprPrimChar, pprPrimInt, pprPrimWord, pprPrimInt64, pprPrimWord64,
pprFastFilePath,
-- * Controlling the style in which output is printed
BindingSite(..),
PprStyle, CodeStyle(..), PrintUnqualified(..),
QueryQualifyName, QueryQualifyModule, QueryQualifyPackage,
reallyAlwaysQualify, reallyAlwaysQualifyNames,
alwaysQualify, alwaysQualifyNames, alwaysQualifyModules,
neverQualify, neverQualifyNames, neverQualifyModules,
alwaysQualifyPackages, neverQualifyPackages,
QualifyName(..), queryQual,
sdocWithDynFlags, sdocWithPlatform,
getPprStyle, withPprStyle, withPprStyleDoc, setStyleColoured,
pprDeeper, pprDeeperList, pprSetDepth,
codeStyle, userStyle, debugStyle, dumpStyle, asmStyle,
qualName, qualModule, qualPackage,
mkErrStyle, defaultErrStyle, defaultDumpStyle, mkDumpStyle, defaultUserStyle,
mkUserStyle, cmdlineParserStyle, Depth(..),
ifPprDebug, whenPprDebug, getPprDebug,
-- * Error handling and debugging utilities
pprPanic, pprSorry, assertPprPanic, pprPgmError,
pprTrace, pprTraceDebug, pprTraceIt, warnPprTrace, pprSTrace,
pprTraceException,
trace, pgmError, panic, sorry, assertPanic,
pprDebugAndThen, callStackDoc,
) where
import GhcPrelude
import {-# SOURCE #-} DynFlags( DynFlags, hasPprDebug, hasNoDebugOutput,
targetPlatform, pprUserLength, pprCols,
useUnicode, useUnicodeSyntax,
shouldUseColor, unsafeGlobalDynFlags )
import {-# SOURCE #-} Module( UnitId, Module, ModuleName, moduleName )
import {-# SOURCE #-} OccName( OccName )
import BufWrite (BufHandle)
import FastString
import qualified Pretty
import Util
import Platform
import qualified PprColour as Col
import Pretty ( Doc, Mode(..) )
import Panic
import GHC.Serialized
import GHC.LanguageExtensions (Extension)
import Control.Exception (finally)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.Char
import qualified Data.Map as M
import Data.Int
import qualified Data.IntMap as IM
import Data.Set (Set)
import qualified Data.Set as Set
import Data.String
import Data.Word
import System.IO ( Handle )
import System.FilePath
import Text.Printf
import Numeric (showFFloat)
import Data.Graph (SCC(..))
import Data.List (intersperse)
import GHC.Fingerprint
import GHC.Show ( showMultiLineString )
import GHC.Stack ( callStack, prettyCallStack )
import Control.Monad.IO.Class
import Exception
{-
************************************************************************
* *
\subsection{The @PprStyle@ data type}
* *
************************************************************************
-}
data PprStyle
= PprUser PrintUnqualified Depth Coloured
-- Pretty-print in a way that will make sense to the
-- ordinary user; must be very close to Haskell
-- syntax, etc.
-- Assumes printing tidied code: non-system names are
-- printed without uniques.
| PprDump PrintUnqualified
-- For -ddump-foo; less verbose than PprDebug, but more than PprUser
-- Does not assume tidied code: non-external names
-- are printed with uniques.
| PprDebug -- Full debugging output
| PprCode CodeStyle
-- Print code; either C or assembler
data CodeStyle = CStyle -- The format of labels differs for C and assembler
| AsmStyle
data Depth = AllTheWay
| PartWay Int -- 0 => stop
data Coloured
= Uncoloured
| Coloured
-- -----------------------------------------------------------------------------
-- Printing original names
-- | When printing code that contains original names, we need to map the
-- original names back to something the user understands. This is the
-- purpose of the triple of functions that gets passed around
-- when rendering 'SDoc'.
data PrintUnqualified = QueryQualify {
queryQualifyName :: QueryQualifyName,
queryQualifyModule :: QueryQualifyModule,
queryQualifyPackage :: QueryQualifyPackage
}
-- | given an /original/ name, this function tells you which module
-- name it should be qualified with when printing for the user, if
-- any. For example, given @Control.Exception.catch@, which is in scope
-- as @Exception.catch@, this function will return @Just "Exception"@.
-- Note that the return value is a ModuleName, not a Module, because
-- in source code, names are qualified by ModuleNames.
type QueryQualifyName = Module -> OccName -> QualifyName
-- | For a given module, we need to know whether to print it with
-- a package name to disambiguate it.
type QueryQualifyModule = Module -> Bool
-- | For a given package, we need to know whether to print it with
-- the component id to disambiguate it.
type QueryQualifyPackage = UnitId -> Bool
-- See Note [Printing original names] in HscTypes
data QualifyName -- Given P:M.T
= NameUnqual -- It's in scope unqualified as "T"
-- OR nothing called "T" is in scope
| NameQual ModuleName -- It's in scope qualified as "X.T"
| NameNotInScope1 -- It's not in scope at all, but M.T is not bound
-- in the current scope, so we can refer to it as "M.T"
| NameNotInScope2 -- It's not in scope at all, and M.T is already bound in
-- the current scope, so we must refer to it as "P:M.T"
instance Outputable QualifyName where
ppr NameUnqual = text "NameUnqual"
ppr (NameQual _mod) = text "NameQual" -- can't print the mod without module loops :(
ppr NameNotInScope1 = text "NameNotInScope1"
ppr NameNotInScope2 = text "NameNotInScope2"
reallyAlwaysQualifyNames :: QueryQualifyName
reallyAlwaysQualifyNames _ _ = NameNotInScope2
-- | NB: This won't ever show package IDs
alwaysQualifyNames :: QueryQualifyName
alwaysQualifyNames m _ = NameQual (moduleName m)
neverQualifyNames :: QueryQualifyName
neverQualifyNames _ _ = NameUnqual
alwaysQualifyModules :: QueryQualifyModule
alwaysQualifyModules _ = True
neverQualifyModules :: QueryQualifyModule
neverQualifyModules _ = False
alwaysQualifyPackages :: QueryQualifyPackage
alwaysQualifyPackages _ = True
neverQualifyPackages :: QueryQualifyPackage
neverQualifyPackages _ = False
reallyAlwaysQualify, alwaysQualify, neverQualify :: PrintUnqualified
reallyAlwaysQualify
= QueryQualify reallyAlwaysQualifyNames
alwaysQualifyModules
alwaysQualifyPackages
alwaysQualify = QueryQualify alwaysQualifyNames
alwaysQualifyModules
alwaysQualifyPackages
neverQualify = QueryQualify neverQualifyNames
neverQualifyModules
neverQualifyPackages
defaultUserStyle :: DynFlags -> PprStyle
defaultUserStyle dflags = mkUserStyle dflags neverQualify AllTheWay
defaultDumpStyle :: DynFlags -> PprStyle
-- Print without qualifiers to reduce verbosity, unless -dppr-debug
defaultDumpStyle dflags
| hasPprDebug dflags = PprDebug
| otherwise = PprDump neverQualify
mkDumpStyle :: DynFlags -> PrintUnqualified -> PprStyle
mkDumpStyle dflags print_unqual
| hasPprDebug dflags = PprDebug
| otherwise = PprDump print_unqual
defaultErrStyle :: DynFlags -> PprStyle
-- Default style for error messages, when we don't know PrintUnqualified
-- It's a bit of a hack because it doesn't take into account what's in scope
-- Only used for desugarer warnings, and typechecker errors in interface sigs
-- NB that -dppr-debug will still get into PprDebug style
defaultErrStyle dflags = mkErrStyle dflags neverQualify
-- | Style for printing error messages
mkErrStyle :: DynFlags -> PrintUnqualified -> PprStyle
mkErrStyle dflags qual =
mkUserStyle dflags qual (PartWay (pprUserLength dflags))
cmdlineParserStyle :: DynFlags -> PprStyle
cmdlineParserStyle dflags = mkUserStyle dflags alwaysQualify AllTheWay
mkUserStyle :: DynFlags -> PrintUnqualified -> Depth -> PprStyle
mkUserStyle dflags unqual depth
| hasPprDebug dflags = PprDebug
| otherwise = PprUser unqual depth Uncoloured
setStyleColoured :: Bool -> PprStyle -> PprStyle
setStyleColoured col style =
case style of
PprUser q d _ -> PprUser q d c
_ -> style
where
c | col = Coloured
| otherwise = Uncoloured
instance Outputable PprStyle where
ppr (PprUser {}) = text "user-style"
ppr (PprCode {}) = text "code-style"
ppr (PprDump {}) = text "dump-style"
ppr (PprDebug {}) = text "debug-style"
{-
Orthogonal to the above printing styles are (possibly) some
command-line flags that affect printing (often carried with the
style). The most likely ones are variations on how much type info is
shown.
The following test decides whether or not we are actually generating
code (either C or assembly), or generating interface files.
************************************************************************
* *
\subsection{The @SDoc@ data type}
* *
************************************************************************
-}
-- | Represents a pretty-printable document.
--
-- To display an 'SDoc', use 'printSDoc', 'printSDocLn', 'bufLeftRenderSDoc',
-- or 'renderWithStyle'. Avoid calling 'runSDoc' directly as it breaks the
-- abstraction layer.
newtype SDoc = SDoc { runSDoc :: SDocContext -> Doc }
data SDocContext = SDC
{ sdocStyle :: !PprStyle
, sdocLastColour :: !Col.PprColour
-- ^ The most recently used colour. This allows nesting colours.
, sdocDynFlags :: !DynFlags
}
instance IsString SDoc where
fromString = text
initSDocContext :: DynFlags -> PprStyle -> SDocContext
initSDocContext dflags sty = SDC
{ sdocStyle = sty
, sdocLastColour = Col.colReset
, sdocDynFlags = dflags
}
withPprStyle :: PprStyle -> SDoc -> SDoc
withPprStyle sty d = SDoc $ \ctxt -> runSDoc d ctxt{sdocStyle=sty}
-- | This is not a recommended way to render 'SDoc', since it breaks the
-- abstraction layer of 'SDoc'. Prefer to use 'printSDoc', 'printSDocLn',
-- 'bufLeftRenderSDoc', or 'renderWithStyle' instead.
withPprStyleDoc :: DynFlags -> PprStyle -> SDoc -> Doc
withPprStyleDoc dflags sty d = runSDoc d (initSDocContext dflags sty)
pprDeeper :: SDoc -> SDoc
pprDeeper d = SDoc $ \ctx -> case ctx of
SDC{sdocStyle=PprUser _ (PartWay 0) _} -> Pretty.text "..."
SDC{sdocStyle=PprUser q (PartWay n) c} ->
runSDoc d ctx{sdocStyle = PprUser q (PartWay (n-1)) c}
_ -> runSDoc d ctx
-- | Truncate a list that is longer than the current depth.
pprDeeperList :: ([SDoc] -> SDoc) -> [SDoc] -> SDoc
pprDeeperList f ds
| null ds = f []
| otherwise = SDoc work
where
work ctx@SDC{sdocStyle=PprUser q (PartWay n) c}
| n==0 = Pretty.text "..."
| otherwise =
runSDoc (f (go 0 ds)) ctx{sdocStyle = PprUser q (PartWay (n-1)) c}
where
go _ [] = []
go i (d:ds) | i >= n = [text "...."]
| otherwise = d : go (i+1) ds
work other_ctx = runSDoc (f ds) other_ctx
pprSetDepth :: Depth -> SDoc -> SDoc
pprSetDepth depth doc = SDoc $ \ctx ->
case ctx of
SDC{sdocStyle=PprUser q _ c} ->
runSDoc doc ctx{sdocStyle = PprUser q depth c}
_ ->
runSDoc doc ctx
getPprStyle :: (PprStyle -> SDoc) -> SDoc
getPprStyle df = SDoc $ \ctx -> runSDoc (df (sdocStyle ctx)) ctx
sdocWithDynFlags :: (DynFlags -> SDoc) -> SDoc
sdocWithDynFlags f = SDoc $ \ctx -> runSDoc (f (sdocDynFlags ctx)) ctx
sdocWithPlatform :: (Platform -> SDoc) -> SDoc
sdocWithPlatform f = sdocWithDynFlags (f . targetPlatform)
qualName :: PprStyle -> QueryQualifyName
qualName (PprUser q _ _) mod occ = queryQualifyName q mod occ
qualName (PprDump q) mod occ = queryQualifyName q mod occ
qualName _other mod _ = NameQual (moduleName mod)
qualModule :: PprStyle -> QueryQualifyModule
qualModule (PprUser q _ _) m = queryQualifyModule q m
qualModule (PprDump q) m = queryQualifyModule q m
qualModule _other _m = True
qualPackage :: PprStyle -> QueryQualifyPackage
qualPackage (PprUser q _ _) m = queryQualifyPackage q m
qualPackage (PprDump q) m = queryQualifyPackage q m
qualPackage _other _m = True
queryQual :: PprStyle -> PrintUnqualified
queryQual s = QueryQualify (qualName s)
(qualModule s)
(qualPackage s)
codeStyle :: PprStyle -> Bool
codeStyle (PprCode _) = True
codeStyle _ = False
asmStyle :: PprStyle -> Bool
asmStyle (PprCode AsmStyle) = True
asmStyle _other = False
dumpStyle :: PprStyle -> Bool
dumpStyle (PprDump {}) = True
dumpStyle _other = False
debugStyle :: PprStyle -> Bool
debugStyle PprDebug = True
debugStyle _other = False
userStyle :: PprStyle -> Bool
userStyle (PprUser {}) = True
userStyle _other = False
getPprDebug :: (Bool -> SDoc) -> SDoc
getPprDebug d = getPprStyle $ \ sty -> d (debugStyle sty)
ifPprDebug :: SDoc -> SDoc -> SDoc
-- ^ Says what to do with and without -dppr-debug
ifPprDebug yes no = getPprDebug $ \ dbg -> if dbg then yes else no
whenPprDebug :: SDoc -> SDoc -- Empty for non-debug style
-- ^ Says what to do with -dppr-debug; without, return empty
whenPprDebug d = ifPprDebug d empty
-- | The analog of 'Pretty.printDoc_' for 'SDoc', which tries to make sure the
-- terminal doesn't get screwed up by the ANSI color codes if an exception
-- is thrown during pretty-printing.
printSDoc :: Mode -> DynFlags -> Handle -> PprStyle -> SDoc -> IO ()
printSDoc mode dflags handle sty doc =
Pretty.printDoc_ mode cols handle (runSDoc doc ctx)
`finally`
Pretty.printDoc_ mode cols handle
(runSDoc (coloured Col.colReset empty) ctx)
where
cols = pprCols dflags
ctx = initSDocContext dflags sty
-- | Like 'printSDoc' but appends an extra newline.
printSDocLn :: Mode -> DynFlags -> Handle -> PprStyle -> SDoc -> IO ()
printSDocLn mode dflags handle sty doc =
printSDoc mode dflags handle sty (doc $$ text "")
printForUser :: DynFlags -> Handle -> PrintUnqualified -> SDoc -> IO ()
printForUser dflags handle unqual doc
= printSDocLn PageMode dflags handle
(mkUserStyle dflags unqual AllTheWay) doc
printForUserPartWay :: DynFlags -> Handle -> Int -> PrintUnqualified -> SDoc
-> IO ()
printForUserPartWay dflags handle d unqual doc
= printSDocLn PageMode dflags handle
(mkUserStyle dflags unqual (PartWay d)) doc
-- | Like 'printSDocLn' but specialized with 'LeftMode' and
-- @'PprCode' 'CStyle'@. This is typically used to output C-- code.
printForC :: DynFlags -> Handle -> SDoc -> IO ()
printForC dflags handle doc =
printSDocLn LeftMode dflags handle (PprCode CStyle) doc
-- | An efficient variant of 'printSDoc' specialized for 'LeftMode' that
-- outputs to a 'BufHandle'.
bufLeftRenderSDoc :: DynFlags -> BufHandle -> PprStyle -> SDoc -> IO ()
bufLeftRenderSDoc dflags bufHandle sty doc =
Pretty.bufLeftRender bufHandle (runSDoc doc (initSDocContext dflags sty))
pprCode :: CodeStyle -> SDoc -> SDoc
pprCode cs d = withPprStyle (PprCode cs) d
mkCodeStyle :: CodeStyle -> PprStyle
mkCodeStyle = PprCode
-- Can't make SDoc an instance of Show because SDoc is just a function type
-- However, Doc *is* an instance of Show
-- showSDoc just blasts it out as a string
showSDoc :: DynFlags -> SDoc -> String
showSDoc dflags sdoc = renderWithStyle dflags sdoc (defaultUserStyle dflags)
-- showSDocUnsafe is unsafe, because `unsafeGlobalDynFlags` might not be
-- initialised yet.
showSDocUnsafe :: SDoc -> String
showSDocUnsafe sdoc = showSDoc unsafeGlobalDynFlags sdoc
showPpr :: Outputable a => DynFlags -> a -> String
showPpr dflags thing = showSDoc dflags (ppr thing)
showSDocUnqual :: DynFlags -> SDoc -> String
-- Only used by Haddock
showSDocUnqual dflags sdoc = showSDoc dflags sdoc
showSDocForUser :: DynFlags -> PrintUnqualified -> SDoc -> String
-- Allows caller to specify the PrintUnqualified to use
showSDocForUser dflags unqual doc
= renderWithStyle dflags doc (mkUserStyle dflags unqual AllTheWay)
showSDocDump :: DynFlags -> SDoc -> String
showSDocDump dflags d = renderWithStyle dflags d (defaultDumpStyle dflags)
showSDocDebug :: DynFlags -> SDoc -> String
showSDocDebug dflags d = renderWithStyle dflags d PprDebug
renderWithStyle :: DynFlags -> SDoc -> PprStyle -> String
renderWithStyle dflags sdoc sty
= let s = Pretty.style{ Pretty.mode = PageMode,
Pretty.lineLength = pprCols dflags }
in Pretty.renderStyle s $ runSDoc sdoc (initSDocContext dflags sty)
-- This shows an SDoc, but on one line only. It's cheaper than a full
-- showSDoc, designed for when we're getting results like "Foo.bar"
-- and "foo{uniq strictness}" so we don't want fancy layout anyway.
showSDocOneLine :: DynFlags -> SDoc -> String
showSDocOneLine dflags d
= let s = Pretty.style{ Pretty.mode = OneLineMode,
Pretty.lineLength = pprCols dflags } in
Pretty.renderStyle s $
runSDoc d (initSDocContext dflags (defaultUserStyle dflags))
showSDocDumpOneLine :: DynFlags -> SDoc -> String
showSDocDumpOneLine dflags d
= let s = Pretty.style{ Pretty.mode = OneLineMode,
Pretty.lineLength = irrelevantNCols } in
Pretty.renderStyle s $
runSDoc d (initSDocContext dflags (defaultDumpStyle dflags))
irrelevantNCols :: Int
-- Used for OneLineMode and LeftMode when number of cols isn't used
irrelevantNCols = 1
isEmpty :: DynFlags -> SDoc -> Bool
isEmpty dflags sdoc = Pretty.isEmpty $ runSDoc sdoc dummySDocContext
where dummySDocContext = initSDocContext dflags PprDebug
docToSDoc :: Doc -> SDoc
docToSDoc d = SDoc (\_ -> d)
empty :: SDoc
char :: Char -> SDoc
text :: String -> SDoc
ftext :: FastString -> SDoc
ptext :: LitString -> SDoc
ztext :: FastZString -> SDoc
int :: Int -> SDoc
integer :: Integer -> SDoc
float :: Float -> SDoc
double :: Double -> SDoc
rational :: Rational -> SDoc
empty = docToSDoc $ Pretty.empty
char c = docToSDoc $ Pretty.char c
text s = docToSDoc $ Pretty.text s
{-# INLINE text #-} -- Inline so that the RULE Pretty.text will fire
ftext s = docToSDoc $ Pretty.ftext s
ptext s = docToSDoc $ Pretty.ptext s
ztext s = docToSDoc $ Pretty.ztext s
int n = docToSDoc $ Pretty.int n
integer n = docToSDoc $ Pretty.integer n
float n = docToSDoc $ Pretty.float n
double n = docToSDoc $ Pretty.double n
rational n = docToSDoc $ Pretty.rational n
-- | @doublePrec p n@ shows a floating point number @n@ with @p@
-- digits of precision after the decimal point.
doublePrec :: Int -> Double -> SDoc
doublePrec p n = text (showFFloat (Just p) n "")
parens, braces, brackets, quotes, quote,
paBrackets, doubleQuotes, angleBrackets :: SDoc -> SDoc
parens d = SDoc $ Pretty.parens . runSDoc d
braces d = SDoc $ Pretty.braces . runSDoc d
brackets d = SDoc $ Pretty.brackets . runSDoc d
quote d = SDoc $ Pretty.quote . runSDoc d
doubleQuotes d = SDoc $ Pretty.doubleQuotes . runSDoc d
angleBrackets d = char '<' <> d <> char '>'
paBrackets d = text "[:" <> d <> text ":]"
cparen :: Bool -> SDoc -> SDoc
cparen b d = SDoc $ Pretty.maybeParens b . runSDoc d
-- 'quotes' encloses something in single quotes...
-- but it omits them if the thing begins or ends in a single quote
-- so that we don't get `foo''. Instead we just have foo'.
quotes d =
sdocWithDynFlags $ \dflags ->
if useUnicode dflags
then char '‘' <> d <> char '’'
else SDoc $ \sty ->
let pp_d = runSDoc d sty
str = show pp_d
in case (str, snocView str) of
(_, Just (_, '\'')) -> pp_d
('\'' : _, _) -> pp_d
_other -> Pretty.quotes pp_d
semi, comma, colon, equals, space, dcolon, underscore, dot, vbar :: SDoc
arrow, larrow, darrow, arrowt, larrowt, arrowtt, larrowtt :: SDoc
lparen, rparen, lbrack, rbrack, lbrace, rbrace, blankLine :: SDoc
blankLine = docToSDoc $ Pretty.text ""
dcolon = unicodeSyntax (char '∷') (docToSDoc $ Pretty.text "::")
arrow = unicodeSyntax (char '→') (docToSDoc $ Pretty.text "->")
larrow = unicodeSyntax (char '←') (docToSDoc $ Pretty.text "<-")
darrow = unicodeSyntax (char '⇒') (docToSDoc $ Pretty.text "=>")
arrowt = unicodeSyntax (char '⤚') (docToSDoc $ Pretty.text ">-")
larrowt = unicodeSyntax (char '⤙') (docToSDoc $ Pretty.text "-<")
arrowtt = unicodeSyntax (char '⤜') (docToSDoc $ Pretty.text ">>-")
larrowtt = unicodeSyntax (char '⤛') (docToSDoc $ Pretty.text "-<<")
semi = docToSDoc $ Pretty.semi
comma = docToSDoc $ Pretty.comma
colon = docToSDoc $ Pretty.colon
equals = docToSDoc $ Pretty.equals
space = docToSDoc $ Pretty.space
underscore = char '_'
dot = char '.'
vbar = char '|'
lparen = docToSDoc $ Pretty.lparen
rparen = docToSDoc $ Pretty.rparen
lbrack = docToSDoc $ Pretty.lbrack
rbrack = docToSDoc $ Pretty.rbrack
lbrace = docToSDoc $ Pretty.lbrace
rbrace = docToSDoc $ Pretty.rbrace
forAllLit :: SDoc
forAllLit = unicodeSyntax (char '∀') (text "forall")
kindStar :: SDoc
kindStar = unicodeSyntax (char '★') (char '*')
bullet :: SDoc
bullet = unicode (char '•') (char '*')
unicodeSyntax :: SDoc -> SDoc -> SDoc
unicodeSyntax unicode plain = sdocWithDynFlags $ \dflags ->
if useUnicode dflags && useUnicodeSyntax dflags
then unicode
else plain
unicode :: SDoc -> SDoc -> SDoc
unicode unicode plain = sdocWithDynFlags $ \dflags ->
if useUnicode dflags
then unicode
else plain
nest :: Int -> SDoc -> SDoc
-- ^ Indent 'SDoc' some specified amount
(<>) :: SDoc -> SDoc -> SDoc
-- ^ Join two 'SDoc' together horizontally without a gap
(<+>) :: SDoc -> SDoc -> SDoc
-- ^ Join two 'SDoc' together horizontally with a gap between them
($$) :: SDoc -> SDoc -> SDoc
-- ^ Join two 'SDoc' together vertically; if there is
-- no vertical overlap it "dovetails" the two onto one line
($+$) :: SDoc -> SDoc -> SDoc
-- ^ Join two 'SDoc' together vertically
nest n d = SDoc $ Pretty.nest n . runSDoc d
(<>) d1 d2 = SDoc $ \sty -> (Pretty.<>) (runSDoc d1 sty) (runSDoc d2 sty)
(<+>) d1 d2 = SDoc $ \sty -> (Pretty.<+>) (runSDoc d1 sty) (runSDoc d2 sty)
($$) d1 d2 = SDoc $ \sty -> (Pretty.$$) (runSDoc d1 sty) (runSDoc d2 sty)
($+$) d1 d2 = SDoc $ \sty -> (Pretty.$+$) (runSDoc d1 sty) (runSDoc d2 sty)
hcat :: [SDoc] -> SDoc
-- ^ Concatenate 'SDoc' horizontally
hsep :: [SDoc] -> SDoc
-- ^ Concatenate 'SDoc' horizontally with a space between each one
vcat :: [SDoc] -> SDoc
-- ^ Concatenate 'SDoc' vertically with dovetailing
sep :: [SDoc] -> SDoc
-- ^ Separate: is either like 'hsep' or like 'vcat', depending on what fits
cat :: [SDoc] -> SDoc
-- ^ Catenate: is either like 'hcat' or like 'vcat', depending on what fits
fsep :: [SDoc] -> SDoc
-- ^ A paragraph-fill combinator. It's much like sep, only it
-- keeps fitting things on one line until it can't fit any more.
fcat :: [SDoc] -> SDoc
-- ^ This behaves like 'fsep', but it uses '<>' for horizontal conposition rather than '<+>'
hcat ds = SDoc $ \sty -> Pretty.hcat [runSDoc d sty | d <- ds]
hsep ds = SDoc $ \sty -> Pretty.hsep [runSDoc d sty | d <- ds]
vcat ds = SDoc $ \sty -> Pretty.vcat [runSDoc d sty | d <- ds]
sep ds = SDoc $ \sty -> Pretty.sep [runSDoc d sty | d <- ds]
cat ds = SDoc $ \sty -> Pretty.cat [runSDoc d sty | d <- ds]
fsep ds = SDoc $ \sty -> Pretty.fsep [runSDoc d sty | d <- ds]
fcat ds = SDoc $ \sty -> Pretty.fcat [runSDoc d sty | d <- ds]
hang :: SDoc -- ^ The header
-> Int -- ^ Amount to indent the hung body
-> SDoc -- ^ The hung body, indented and placed below the header
-> SDoc
hang d1 n d2 = SDoc $ \sty -> Pretty.hang (runSDoc d1 sty) n (runSDoc d2 sty)
-- | This behaves like 'hang', but does not indent the second document
-- when the header is empty.
hangNotEmpty :: SDoc -> Int -> SDoc -> SDoc
hangNotEmpty d1 n d2 =
SDoc $ \sty -> Pretty.hangNotEmpty (runSDoc d1 sty) n (runSDoc d2 sty)
punctuate :: SDoc -- ^ The punctuation
-> [SDoc] -- ^ The list that will have punctuation added between every adjacent pair of elements
-> [SDoc] -- ^ Punctuated list
punctuate _ [] = []
punctuate p (d:ds) = go d ds
where
go d [] = [d]
go d (e:es) = (d <> p) : go e es
ppWhen, ppUnless :: Bool -> SDoc -> SDoc
ppWhen True doc = doc
ppWhen False _ = empty
ppUnless True _ = empty
ppUnless False doc = doc
-- | Apply the given colour\/style for the argument.
--
-- Only takes effect if colours are enabled.
coloured :: Col.PprColour -> SDoc -> SDoc
coloured col sdoc =
sdocWithDynFlags $ \dflags ->
if shouldUseColor dflags
then SDoc $ \ctx@SDC{ sdocLastColour = lastCol } ->
case ctx of
SDC{ sdocStyle = PprUser _ _ Coloured } ->
let ctx' = ctx{ sdocLastColour = lastCol `mappend` col } in
Pretty.zeroWidthText (Col.renderColour col)
Pretty.<> runSDoc sdoc ctx'
Pretty.<> Pretty.zeroWidthText (Col.renderColourAfresh lastCol)
_ -> runSDoc sdoc ctx
else sdoc
keyword :: SDoc -> SDoc
keyword = coloured Col.colBold
{-
************************************************************************
* *
\subsection[Outputable-class]{The @Outputable@ class}
* *
************************************************************************
-}
-- | Class designating that some type has an 'SDoc' representation
class Outputable a where
ppr :: a -> SDoc
pprPrec :: Rational -> a -> SDoc
-- 0 binds least tightly
-- We use Rational because there is always a
-- Rational between any other two Rationals
ppr = pprPrec 0
pprPrec _ = ppr
instance Outputable Char where
ppr c = text [c]
instance Outputable Bool where
ppr True = text "True"
ppr False = text "False"
instance Outputable Ordering where
ppr LT = text "LT"
ppr EQ = text "EQ"
ppr GT = text "GT"
instance Outputable Int32 where
ppr n = integer $ fromIntegral n
instance Outputable Int64 where
ppr n = integer $ fromIntegral n
instance Outputable Int where
ppr n = int n
instance Outputable Integer where
ppr n = integer n
instance Outputable Word16 where
ppr n = integer $ fromIntegral n
instance Outputable Word32 where
ppr n = integer $ fromIntegral n
instance Outputable Word where
ppr n = integer $ fromIntegral n
instance Outputable () where
ppr _ = text "()"
instance (Outputable a) => Outputable [a] where
ppr xs = brackets (fsep (punctuate comma (map ppr xs)))
instance (Outputable a) => Outputable (Set a) where
ppr s = braces (fsep (punctuate comma (map ppr (Set.toList s))))
instance (Outputable a, Outputable b) => Outputable (a, b) where
ppr (x,y) = parens (sep [ppr x <> comma, ppr y])
instance Outputable a => Outputable (Maybe a) where
ppr Nothing = text "Nothing"
ppr (Just x) = text "Just" <+> ppr x
instance (Outputable a, Outputable b) => Outputable (Either a b) where
ppr (Left x) = text "Left" <+> ppr x
ppr (Right y) = text "Right" <+> ppr y
-- ToDo: may not be used
instance (Outputable a, Outputable b, Outputable c) => Outputable (a, b, c) where
ppr (x,y,z) =
parens (sep [ppr x <> comma,
ppr y <> comma,
ppr z ])
instance (Outputable a, Outputable b, Outputable c, Outputable d) =>
Outputable (a, b, c, d) where
ppr (a,b,c,d) =
parens (sep [ppr a <> comma,
ppr b <> comma,
ppr c <> comma,
ppr d])
instance (Outputable a, Outputable b, Outputable c, Outputable d, Outputable e) =>
Outputable (a, b, c, d, e) where
ppr (a,b,c,d,e) =
parens (sep [ppr a <> comma,
ppr b <> comma,
ppr c <> comma,
ppr d <> comma,
ppr e])
instance (Outputable a, Outputable b, Outputable c, Outputable d, Outputable e, Outputable f) =>
Outputable (a, b, c, d, e, f) where
ppr (a,b,c,d,e,f) =
parens (sep [ppr a <> comma,
ppr b <> comma,
ppr c <> comma,
ppr d <> comma,
ppr e <> comma,
ppr f])
instance (Outputable a, Outputable b, Outputable c, Outputable d, Outputable e, Outputable f, Outputable g) =>
Outputable (a, b, c, d, e, f, g) where
ppr (a,b,c,d,e,f,g) =
parens (sep [ppr a <> comma,
ppr b <> comma,
ppr c <> comma,
ppr d <> comma,
ppr e <> comma,
ppr f <> comma,
ppr g])
instance Outputable FastString where
ppr fs = ftext fs -- Prints an unadorned string,
-- no double quotes or anything
instance (Outputable key, Outputable elt) => Outputable (M.Map key elt) where
ppr m = ppr (M.toList m)
instance (Outputable elt) => Outputable (IM.IntMap elt) where
ppr m = ppr (IM.toList m)
instance Outputable Fingerprint where
ppr (Fingerprint w1 w2) = text (printf "%016x%016x" w1 w2)
instance Outputable a => Outputable (SCC a) where
ppr (AcyclicSCC v) = text "NONREC" $$ (nest 3 (ppr v))
ppr (CyclicSCC vs) = text "REC" $$ (nest 3 (vcat (map ppr vs)))
instance Outputable Serialized where
ppr (Serialized the_type bytes) = int (length bytes) <+> text "of type" <+> text (show the_type)
instance Outputable Extension where
ppr = text . show
{-
************************************************************************
* *
\subsection{The @OutputableBndr@ class}
* *
************************************************************************
-}
-- | 'BindingSite' is used to tell the thing that prints binder what
-- language construct is binding the identifier. This can be used
-- to decide how much info to print.
-- Also see Note [Binding-site specific printing] in PprCore
data BindingSite
= LambdaBind -- ^ The x in (\x. e)
| CaseBind -- ^ The x in case scrut of x { (y,z) -> ... }
| CasePatBind -- ^ The y,z in case scrut of x { (y,z) -> ... }
| LetBind -- ^ The x in (let x = rhs in e)
-- | When we print a binder, we often want to print its type too.
-- The @OutputableBndr@ class encapsulates this idea.
class Outputable a => OutputableBndr a where
pprBndr :: BindingSite -> a -> SDoc
pprBndr _b x = ppr x
pprPrefixOcc, pprInfixOcc :: a -> SDoc
-- Print an occurrence of the name, suitable either in the
-- prefix position of an application, thus (f a b) or ((+) x)
-- or infix position, thus (a `f` b) or (x + y)
bndrIsJoin_maybe :: a -> Maybe Int
bndrIsJoin_maybe _ = Nothing
-- When pretty-printing we sometimes want to find
-- whether the binder is a join point. You might think
-- we could have a function of type (a->Var), but Var
-- isn't available yet, alas
{-
************************************************************************
* *
\subsection{Random printing helpers}
* *
************************************************************************
-}
-- We have 31-bit Chars and will simply use Show instances of Char and String.
-- | Special combinator for showing character literals.
pprHsChar :: Char -> SDoc
pprHsChar c | c > '\x10ffff' = char '\\' <> text (show (fromIntegral (ord c) :: Word32))
| otherwise = text (show c)
-- | Special combinator for showing string literals.
pprHsString :: FastString -> SDoc
pprHsString fs = vcat (map text (showMultiLineString (unpackFS fs)))
-- | Special combinator for showing bytestring literals.
pprHsBytes :: ByteString -> SDoc
pprHsBytes bs = let escaped = concatMap escape $ BS.unpack bs
in vcat (map text (showMultiLineString escaped)) <> char '#'
where escape :: Word8 -> String
escape w = let c = chr (fromIntegral w)
in if isAscii c
then [c]
else '\\' : show w
-- Postfix modifiers for unboxed literals.
-- See Note [Printing of literals in Core] in `basicTypes/Literal.hs`.
primCharSuffix, primFloatSuffix, primIntSuffix :: SDoc
primDoubleSuffix, primWordSuffix, primInt64Suffix, primWord64Suffix :: SDoc
primCharSuffix = char '#'
primFloatSuffix = char '#'
primIntSuffix = char '#'
primDoubleSuffix = text "##"
primWordSuffix = text "##"
primInt64Suffix = text "L#"
primWord64Suffix = text "L##"
-- | Special combinator for showing unboxed literals.
pprPrimChar :: Char -> SDoc
pprPrimInt, pprPrimWord, pprPrimInt64, pprPrimWord64 :: Integer -> SDoc
pprPrimChar c = pprHsChar c <> primCharSuffix
pprPrimInt i = integer i <> primIntSuffix
pprPrimWord w = integer w <> primWordSuffix
pprPrimInt64 i = integer i <> primInt64Suffix
pprPrimWord64 w = integer w <> primWord64Suffix
---------------------
-- Put a name in parens if it's an operator
pprPrefixVar :: Bool -> SDoc -> SDoc
pprPrefixVar is_operator pp_v
| is_operator = parens pp_v
| otherwise = pp_v
-- Put a name in backquotes if it's not an operator
pprInfixVar :: Bool -> SDoc -> SDoc
pprInfixVar is_operator pp_v
| is_operator = pp_v
| otherwise = char '`' <> pp_v <> char '`'
---------------------
pprFastFilePath :: FastString -> SDoc
pprFastFilePath path = text $ normalise $ unpackFS path
{-
************************************************************************
* *
\subsection{Other helper functions}
* *
************************************************************************
-}
pprWithCommas :: (a -> SDoc) -- ^ The pretty printing function to use
-> [a] -- ^ The things to be pretty printed
-> SDoc -- ^ 'SDoc' where the things have been pretty printed,
-- comma-separated and finally packed into a paragraph.
pprWithCommas pp xs = fsep (punctuate comma (map pp xs))
pprWithBars :: (a -> SDoc) -- ^ The pretty printing function to use
-> [a] -- ^ The things to be pretty printed
-> SDoc -- ^ 'SDoc' where the things have been pretty printed,
-- bar-separated and finally packed into a paragraph.
pprWithBars pp xs = fsep (intersperse vbar (map pp xs))
-- | Returns the separated concatenation of the pretty printed things.
interppSP :: Outputable a => [a] -> SDoc
interppSP xs = sep (map ppr xs)
-- | Returns the comma-separated concatenation of the pretty printed things.
interpp'SP :: Outputable a => [a] -> SDoc
interpp'SP xs = sep (punctuate comma (map ppr xs))
-- | Returns the comma-separated concatenation of the quoted pretty printed things.
--
-- > [x,y,z] ==> `x', `y', `z'
pprQuotedList :: Outputable a => [a] -> SDoc
pprQuotedList = quotedList . map ppr
quotedList :: [SDoc] -> SDoc
quotedList xs = fsep (punctuate comma (map quotes xs))
quotedListWithOr :: [SDoc] -> SDoc
-- [x,y,z] ==> `x', `y' or `z'
quotedListWithOr xs@(_:_:_) = quotedList (init xs) <+> text "or" <+> quotes (last xs)
quotedListWithOr xs = quotedList xs
quotedListWithNor :: [SDoc] -> SDoc
-- [x,y,z] ==> `x', `y' nor `z'
quotedListWithNor xs@(_:_:_) = quotedList (init xs) <+> text "nor" <+> quotes (last xs)
quotedListWithNor xs = quotedList xs
{-
************************************************************************
* *
\subsection{Printing numbers verbally}
* *
************************************************************************
-}
intWithCommas :: Integral a => a -> SDoc
-- Prints a big integer with commas, eg 345,821
intWithCommas n
| n < 0 = char '-' <> intWithCommas (-n)
| q == 0 = int (fromIntegral r)
| otherwise = intWithCommas q <> comma <> zeroes <> int (fromIntegral r)
where
(q,r) = n `quotRem` 1000
zeroes | r >= 100 = empty
| r >= 10 = char '0'
| otherwise = text "00"
-- | Converts an integer to a verbal index:
--
-- > speakNth 1 = text "first"
-- > speakNth 5 = text "fifth"
-- > speakNth 21 = text "21st"
speakNth :: Int -> SDoc
speakNth 1 = text "first"
speakNth 2 = text "second"
speakNth 3 = text "third"
speakNth 4 = text "fourth"
speakNth 5 = text "fifth"
speakNth 6 = text "sixth"
speakNth n = hcat [ int n, text suffix ]
where
suffix | n <= 20 = "th" -- 11,12,13 are non-std
| last_dig == 1 = "st"
| last_dig == 2 = "nd"
| last_dig == 3 = "rd"
| otherwise = "th"
last_dig = n `rem` 10
-- | Converts an integer to a verbal multiplicity:
--
-- > speakN 0 = text "none"
-- > speakN 5 = text "five"
-- > speakN 10 = text "10"
speakN :: Int -> SDoc
speakN 0 = text "none" -- E.g. "he has none"
speakN 1 = text "one" -- E.g. "he has one"
speakN 2 = text "two"
speakN 3 = text "three"
speakN 4 = text "four"
speakN 5 = text "five"
speakN 6 = text "six"
speakN n = int n
-- | Converts an integer and object description to a statement about the
-- multiplicity of those objects:
--
-- > speakNOf 0 (text "melon") = text "no melons"
-- > speakNOf 1 (text "melon") = text "one melon"
-- > speakNOf 3 (text "melon") = text "three melons"
speakNOf :: Int -> SDoc -> SDoc
speakNOf 0 d = text "no" <+> d <> char 's'
speakNOf 1 d = text "one" <+> d -- E.g. "one argument"
speakNOf n d = speakN n <+> d <> char 's' -- E.g. "three arguments"
-- | Determines the pluralisation suffix appropriate for the length of a list:
--
-- > plural [] = char 's'
-- > plural ["Hello"] = empty
-- > plural ["Hello", "World"] = char 's'
plural :: [a] -> SDoc
plural [_] = empty -- a bit frightening, but there you are
plural _ = char 's'
-- | Determines the form of to be appropriate for the length of a list:
--
-- > isOrAre [] = text "are"
-- > isOrAre ["Hello"] = text "is"
-- > isOrAre ["Hello", "World"] = text "are"
isOrAre :: [a] -> SDoc
isOrAre [_] = text "is"
isOrAre _ = text "are"
-- | Determines the form of to do appropriate for the length of a list:
--
-- > doOrDoes [] = text "do"
-- > doOrDoes ["Hello"] = text "does"
-- > doOrDoes ["Hello", "World"] = text "do"
doOrDoes :: [a] -> SDoc
doOrDoes [_] = text "does"
doOrDoes _ = text "do"
{-
************************************************************************
* *
\subsection{Error handling}
* *
************************************************************************
-}
callStackDoc :: HasCallStack => SDoc
callStackDoc =
hang (text "Call stack:")
4 (vcat $ map text $ lines (prettyCallStack callStack))
pprPanic :: HasCallStack => String -> SDoc -> a
-- ^ Throw an exception saying "bug in GHC"
pprPanic s doc = panicDoc s (doc $$ callStackDoc)
pprSorry :: String -> SDoc -> a
-- ^ Throw an exception saying "this isn't finished yet"
pprSorry = sorryDoc
pprPgmError :: String -> SDoc -> a
-- ^ Throw an exception saying "bug in pgm being compiled" (used for unusual program errors)
pprPgmError = pgmErrorDoc
pprTraceDebug :: String -> SDoc -> a -> a
pprTraceDebug str doc x
| debugIsOn && hasPprDebug unsafeGlobalDynFlags = pprTrace str doc x
| otherwise = x
pprTrace :: String -> SDoc -> a -> a
-- ^ If debug output is on, show some 'SDoc' on the screen
pprTrace str doc x
| hasNoDebugOutput unsafeGlobalDynFlags = x
| otherwise =
pprDebugAndThen unsafeGlobalDynFlags trace (text str) doc x
-- | @pprTraceIt desc x@ is equivalent to @pprTrace desc (ppr x) x@
pprTraceIt :: Outputable a => String -> a -> a
pprTraceIt desc x = pprTrace desc (ppr x) x
-- | @pprTraceException desc x action@ runs action, printing a message
-- if it throws an exception.
pprTraceException :: ExceptionMonad m => String -> SDoc -> m a -> m a
pprTraceException heading doc =
handleGhcException $ \exc -> liftIO $ do
putStrLn $ showSDocDump unsafeGlobalDynFlags (sep [text heading, nest 2 doc])
throwGhcExceptionIO exc
-- | If debug output is on, show some 'SDoc' on the screen along
-- with a call stack when available.
pprSTrace :: HasCallStack => SDoc -> a -> a
pprSTrace doc = pprTrace "" (doc $$ callStackDoc)
warnPprTrace :: Bool -> String -> Int -> SDoc -> a -> a
-- ^ Just warn about an assertion failure, recording the given file and line number.
-- Should typically be accessed with the WARN macros
warnPprTrace _ _ _ _ x | not debugIsOn = x
warnPprTrace _ _file _line _msg x
| hasNoDebugOutput unsafeGlobalDynFlags = x
warnPprTrace False _file _line _msg x = x
warnPprTrace True file line msg x
= pprDebugAndThen unsafeGlobalDynFlags trace heading msg x
where
heading = hsep [text "WARNING: file", text file <> comma, text "line", int line]
-- | Panic with an assertation failure, recording the given file and
-- line number. Should typically be accessed with the ASSERT family of macros
assertPprPanic :: HasCallStack => String -> Int -> SDoc -> a
assertPprPanic _file _line msg
= pprPanic "ASSERT failed!" msg
pprDebugAndThen :: DynFlags -> (String -> a) -> SDoc -> SDoc -> a
pprDebugAndThen dflags cont heading pretty_msg
= cont (showSDocDump dflags doc)
where
doc = sep [heading, nest 2 pretty_msg]
|
shlevy/ghc
|
compiler/utils/Outputable.hs
|
bsd-3-clause
| 44,912
| 0
| 20
| 11,499
| 10,622
| 5,669
| 4,953
| -1
| -1
|
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RecordWildCards #-}
module Development.Shake.Install.Utils where
import Control.Lens
import Control.Monad (when)
import Development.Shake as Shake (Action, traced)
import Development.Shake.Install.PersistedEnvironment as Shake
import Development.Shake.Install.RequestResponse (requestOf)
import qualified Development.Shake.Install.PackageDescription as Shake
import Distribution.PackageDescription
import System.Directory
import System.Exit
import System.FilePath
import System.Process
systemWithDirectory
:: String
-> String
-> [String]
-> Shake.Action ()
systemWithDirectory command cwd args = do
traced command $ do
let cp = (proc command args){cwd = Just cwd}
putStrLn $ unwords (cwd:command:args)
(_, _, _, h) <- createProcess cp
-- putLoud command
-- res <- traced ("system " ++ cmd) $ rawSystem path2 args
res <- waitForProcess h
when (res /= ExitSuccess) $
error $ "System command failed:\n" ++ "foo"
fixupGenericPaths
:: FilePath
-> GenericPackageDescription
-> GenericPackageDescription
fixupGenericPaths filePath gdesc@GenericPackageDescription{packageDescription} =
gdesc{packageDescription = makePackageDescriptionPathsAbsolute filePath packageDescription}
fixupHsSourceDirs :: FilePath -> GenericPackageDescription -> GenericPackageDescription
fixupHsSourceDirs sourceDirectory = lbi . ebi . tbi . bmi where
lbi = Shake.libraryBuildInfo . Shake._hsSourceDirs %~ makeAbsolute
ebi = Shake.executableBuildInfos . Shake._hsSourceDirs %~ makeAbsolute
tbi = Shake.testSuiteBuildInfos . Shake._hsSourceDirs %~ makeAbsolute
bmi = Shake.benchmarkBuildInfos . Shake._hsSourceDirs %~ makeAbsolute
makeAbsolute fileName
| Prelude.null fileName = fileName
| otherwise = combine sourceDirectory fileName
makePackageDescriptionPathsAbsolute
:: FilePath
-> PackageDescription
-> PackageDescription
makePackageDescriptionPathsAbsolute sourceDirectory desc@PackageDescription{..} = hookedDescription where
hookedDescription = updatePackageDescription hooked updatedDescription
commonBuildInfo = emptyBuildInfo{hsSourceDirs = [sourceDirectory]}
hooked = (Just commonBuildInfo, []) -- TODO: array should have exe names and buildInfo
updatedDescription = desc
{ library = fmap updLib library
, executables = fmap updExe executables
, licenseFile = makeAbsolute licenseFile
, dataDir = makeAbsolute dataDir
}
updLib lib@Library{libBuildInfo} = lib{libBuildInfo = fixupDirectoryPaths libBuildInfo}
updExe exe@Executable{buildInfo} = exe{buildInfo = fixupDirectoryPaths buildInfo}
fixupDirectoryPaths bi@BuildInfo{cSources, extraLibDirs, includeDirs, hsSourceDirs} = bi
{ cSources = fmap makeAbsolute cSources
, extraLibDirs = fmap makeAbsolute extraLibDirs
, Distribution.PackageDescription.includeDirs = fmap makeAbsolute includeDirs
, hsSourceDirs = fmap makeAbsolute hsSourceDirs ++ [sourceDirectory]
}
makeAbsolute fileName
| Prelude.null fileName = fileName
| otherwise = combine sourceDirectory fileName
findDirectoryBounds
:: IO (FilePath, FilePath)
findDirectoryBounds = step1 =<< getCurrentDirectory where
step1 dir = do
fileFound <- doesFileExist (dir </> "Shakefile.hs")
dbFound <- doesFileExist (dir </> ".shake.database")
let parentDir = takeDirectory dir
case (fileFound, dbFound) of
(_, True) -> return (dir, dir)
(True, _) -> step2 (dir, dir) parentDir
(False, _) | dir /= parentDir -> step1 parentDir
-- No Shakefile.hs found in any parent directories, assume
-- the .cabal files are specified on the command line
-- or that we're going to recurse the source tree
-- searching for them
_ -> do
cwd <- getCurrentDirectory
return (cwd, cwd)
step2 best@(_, top) dir = do
fileFound <- doesFileExist (dir </> "Shakefile.hs")
dbFound <- doesFileExist (dir </> ".shake.database")
let parentDir = takeDirectory dir
case (fileFound, dbFound) of
(_, True) -> return (dir, top)
(True, _) | dir /= parentDir -> step2 (dir, top) parentDir
| otherwise -> return (dir, top)
_ -> return best
|
alphaHeavy/shake-install
|
Development/Shake/Install/Utils.hs
|
bsd-3-clause
| 4,343
| 0
| 15
| 882
| 1,078
| 574
| 504
| -1
| -1
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- | This module is improved version of Nettle.OpenFlow.StrictPut
-- I hope we'll merge changes someday.
--
-- This module provides a monad for serializing data into byte strings.
-- It provides mostly the same interface that Data.Binary.Put does.
-- However, the implementation is different. It allows for the data to be
-- serialized into an existing array of Word8 values. This differs from the Data.Binary.Put
-- data type, which allocates a Word8 array every time a value is serialized.
-- This module's implementation is useful if you want to reuse the Word8 array for many serializations.
-- In the case of an OpenFlow server, we can reuse a buffer to send messages, since we have no use
-- for the the Word8 array, except to pass it to an IO procedure to write the data to a socket or file.
module Network.Openflow.StrictPut (
PutM,
Put,
runPut,
runPutToByteString,
putWord8,
putWord16be,
putWord32be,
putWord64be,
putByteString,
putZeros,
-- * Markers
Marker,
marker,
toAddr,
toPtr,
toMarker,
distance,
shrink,
-- * Delay
DelayedPut,
undelay,
-- contramap,
delayedWord8,
delayedWord16be,
Word16be(..),
RPut(..),
-- * Buffer
runPutToBuffer,
Buffer,
mkBuffer,
extract,
bufferSize,
reuse
) where
import qualified Data.ByteString as S
import qualified Data.ByteString.Internal as S
import GHC.Word
import Foreign hiding (void, unsafeForeignPtrToPtr)
import Control.Monad (void)
import GHC.Exts
import System.IO.Unsafe
import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
-- A state monad with state being the pointer to write location.
newtype PutM a = PutM (Ptr Word8 -> IO (a, Ptr Word8))
type Put = PutM ()
-- | Runs the Put writer with write position given
-- by the first pointer argument. Returns the number
-- of words written.
runPut :: Ptr Word8 -> Put -> IO Int
runPut ptr (PutM f) =
do (_, ptr') <- f ptr
return (ptr' `minusPtr` ptr)
-- | Allocates a new byte string, and runs the Put writer with that byte string.
-- The first argument is an upper bound on the size of the array needed to do the serialization.
runPutToByteString :: Int -> Put -> S.ByteString
runPutToByteString maxSize put =
unsafeDupablePerformIO (S.createAndTrim maxSize (\ptr -> runPut ptr put))
-- unsafeDupablePerformIO (S.createAndTrim maxSize (\ptr -> (`minusPtr` ptr) <$> runPut ptr put ))
instance Monad PutM where
return x = PutM (\ptr -> return (x, ptr))
{-# INLINE return #-}
(PutM m) >>= f = PutM (\(!ptr) -> do
(a, ptr') <- m ptr
case f a of
PutM !g -> g ptr')
{-# INLINE (>>=) #-}
putWord8 :: Word8 -> Put
putWord8 !w = PutM (\(!ptr) -> do { poke ptr w; return ((), ptr `plusPtr` 1) })
{-# INLINE putWord8 #-}
putWord16be :: Word16 -> Put
putWord16be !w = PutM f
where f !ptr =
do poke ptr (fromIntegral (shiftr_w16 w 8) :: Word8)
poke (ptr `plusPtr` 1) (fromIntegral (w) :: Word8)
return ((), ptr `plusPtr` 2)
{-# INLINE putWord16be #-}
-- | Write a Word32 in big endian format
putWord32be :: Word32 -> Put
putWord32be !w = PutM f
where f !p =
do poke p (fromIntegral (shiftr_w32 w 24) :: Word8)
poke (p `plusPtr` 1) (fromIntegral (shiftr_w32 w 16) :: Word8)
poke (p `plusPtr` 2) (fromIntegral (shiftr_w32 w 8) :: Word8)
poke (p `plusPtr` 3) (fromIntegral (w) :: Word8)
return ((), p `plusPtr` 4)
{-# INLINE putWord32be #-}
-- | Write a Word64 in big endian format
putWord64be :: Word64 -> Put
#if WORD_SIZE_IN_BITS < 64
--
-- To avoid expensive 64 bit shifts on 32 bit machines, we cast to
-- Word32, and write that
--
putWord64be !w =
let a = fromIntegral (shiftr_w64 w 32) :: Word32
b = fromIntegral w :: Word32
in PutM $ \(!p) -> do
poke p (fromIntegral (shiftr_w32 a 24) :: Word8)
poke (p `plusPtr` 1) (fromIntegral (shiftr_w32 a 16) :: Word8)
poke (p `plusPtr` 2) (fromIntegral (shiftr_w32 a 8) :: Word8)
poke (p `plusPtr` 3) (fromIntegral (a) :: Word8)
poke (p `plusPtr` 4) (fromIntegral (shiftr_w32 b 24) :: Word8)
poke (p `plusPtr` 5) (fromIntegral (shiftr_w32 b 16) :: Word8)
poke (p `plusPtr` 6) (fromIntegral (shiftr_w32 b 8) :: Word8)
poke (p `plusPtr` 7) (fromIntegral (b) :: Word8)
return ((), p `plusPtr` 8)
#else
putWord64be !w = PutM $ \(!p) -> do
poke p (fromIntegral (shiftr_w64 w 56) :: Word8)
poke (p `plusPtr` 1) (fromIntegral (shiftr_w64 w 48) :: Word8)
poke (p `plusPtr` 2) (fromIntegral (shiftr_w64 w 40) :: Word8)
poke (p `plusPtr` 3) (fromIntegral (shiftr_w64 w 32) :: Word8)
poke (p `plusPtr` 4) (fromIntegral (shiftr_w64 w 24) :: Word8)
poke (p `plusPtr` 5) (fromIntegral (shiftr_w64 w 16) :: Word8)
poke (p `plusPtr` 6) (fromIntegral (shiftr_w64 w 8) :: Word8)
poke (p `plusPtr` 7) (fromIntegral (w) :: Word8)
return ((), p `plusPtr` 8)
#endif
{-# INLINE putWord64be #-}
putByteString :: S.ByteString -> Put
putByteString !bs = PutM f
where f !ptr =
let (fp, offset, len) = S.toForeignPtr bs
in do withForeignPtr fp $ \bsptr -> S.memcpy ptr (bsptr `plusPtr` offset) (fromIntegral len)
return ((), ptr `plusPtr` len)
{-# INLINE putByteString #-}
putZeros :: Int -> Put
putZeros !i = PutM $ \p -> S.memset p 0 (fromIntegral i) >> return ((), p `plusPtr` i)
-- | Mark currect address
newtype Marker = Marker (Ptr Word8)
-- | Create new marker at current position/
marker :: PutM Marker
marker = PutM $ \x -> return (Marker x, x)
{-# INLINE marker #-}
-- | Find difference in current position and marker.
distance :: Marker
-> PutM Int
distance (Marker x) = PutM $ \x' -> return (x' `minusPtr` x, x')
{-# INLINE distance #-}
shrink :: Marker
-> Put
shrink (Marker x) = PutM $ \_ -> return ((),x)
-- | Get real address
toAddr :: Marker -> Addr#
toAddr (Marker (Ptr a)) = a
{-# INLINE toAddr #-}
-- | Get marker from pointer
toPtr :: Marker -> Ptr Word8
toPtr (Marker (Ptr a)) = Ptr a
{-# INLINE toPtr #-}
toMarker :: Ptr Word8 -> Marker
toMarker (a) = Marker a;
{-# INLINE toMarker #-}
class RPut a where
rput :: Ptr a -> a -> IO ()
instance RPut Word8 where
rput = poke
{-# INLINE rput #-}
newtype Word16be = Word16be Word16 deriving (Num)
instance RPut Word16be where
rput p (Word16be x) = void (runPut (castPtr p) (putWord16be x))
{-# INLINE rput #-}
-- | Delayed action.
newtype DelayedPut a = DelayedPut (Ptr a)
--contramap :: (a -> b) -> (DelayedPut b) -> (DelayedPut a)
--contramap f (DelayedPut g) = DelayedPut (g.f)
undelay :: (RPut a)
=> DelayedPut a
-> a
-> PutM ()
undelay (DelayedPut a) !x = PutM $ \p -> rput a x >> return ((),p)
{-# INLINE undelay #-}
delayedWord8 :: PutM (DelayedPut Word8)
delayedWord8 = PutM $ \p -> poke p (0::Word8) >>
return (DelayedPut p, p `plusPtr` 1)
{-# INLINE delayedWord8 #-}
delayedWord16be :: PutM (DelayedPut Word16be)
delayedWord16be = PutM $ \p -> poke (castPtr p) (0::Word16) >>
return (DelayedPut (castPtr p), p `plusPtr` 2)
{-# INLINE delayedWord16be #-}
{-# INLINE shiftr_w16 #-}
shiftr_w16 :: Word16 -> Int -> Word16
{-# INLINE shiftr_w32 #-}
shiftr_w32 :: Word32 -> Int -> Word32
{-# INLINE shiftr_w64 #-}
shiftr_w64 :: Word64 -> Int -> Word64
#if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__)
shiftr_w16 (W16# w) (I# i) = W16# (w `uncheckedShiftRL#` i)
shiftr_w32 (W32# w) (I# i) = W32# (w `uncheckedShiftRL#` i)
#if WORD_SIZE_IN_BITS < 64
shiftr_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftRL64#` i)
#endif
#endif
data Buffer = Buffer {-# UNPACK #-} !(ForeignPtr Word8) -- pinned array
{-# UNPACK #-} !(Ptr Word8) -- current position
{-# UNPACK #-} !Int -- current size
bufferSize :: Buffer -> Int
bufferSize (Buffer _ _ i) = i
reuse :: Buffer -> Buffer
reuse (Buffer f _ _) = Buffer f (unsafeForeignPtrToPtr f) 0
extract :: Buffer -> S.ByteString
extract (Buffer f _ c) = S.fromForeignPtr f 0 c
mkBuffer :: Int -> IO Buffer
mkBuffer size = do
fpbuf <- S.mallocByteString size
let !pbuf = unsafeForeignPtrToPtr fpbuf
return $! Buffer fpbuf pbuf 0
runPutToBuffer :: Buffer -> Put -> IO Buffer
runPutToBuffer (Buffer f p x) put = runPut p put >>= \i -> return (Buffer f (p `plusPtr`i) (x+i))
|
ARCCN/hcprobe
|
src/Network/Openflow/StrictPut.hs
|
bsd-3-clause
| 8,499
| 0
| 15
| 1,943
| 2,350
| 1,273
| 1,077
| 168
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent
import System.Exit
import Types
import UI
import IM
import Util
main = do
putStrLn "Welcome To PeMo Messenger!"
mSession <- mkSession
case mSession of
Nothing -> do
putStrLn "Goodbye!"
exitWith ExitSuccess
Just (session, jid) -> initChat session jid
initChat :: Session -> Jid -> IO ()
initChat s jid = do
uiChan <- newChan -- (UIActions)
imChan <- newChan -- (IMActions)
-- initiate both threads UI and IM
forkIO $ imInit imChan uiChan s
uiInit imChan uiChan jid
|
zydeon/PeMo
|
src/Main.hs
|
bsd-3-clause
| 735
| 0
| 12
| 279
| 159
| 79
| 80
| 22
| 2
|
module System.Mesos.Raw.TaskInfo where
import System.Mesos.Internal
import System.Mesos.Raw.CommandInfo
import System.Mesos.Raw.ContainerInfo
import System.Mesos.Raw.DiscoveryInfo
import System.Mesos.Raw.ExecutorInfo
import System.Mesos.Raw.HealthCheck
import System.Mesos.Raw.Label
import System.Mesos.Raw.Resource
import System.Mesos.Raw.SlaveId
import System.Mesos.Raw.TaskId
type TaskInfoPtr = Ptr TaskInfo
foreign import ccall unsafe "ext/types.h toTaskInfo" c_toTaskInfo
:: Ptr CChar -- ^ name
-> CInt -- ^ name length
-> TaskIDPtr -- ^ task id
-> SlaveIDPtr -- ^ slave id
-> Ptr ResourcePtr -- ^ resources
-> CInt -- ^ resources count
-> ExecutorInfoPtr
-> CommandInfoPtr
-> Ptr CChar -- ^ data
-> CInt -- ^ dataLen
-> ContainerInfoPtr
-> HealthCheckPtr
-> Ptr LabelPtr -- ^ labels
-> CInt -- ^ labels count
-> DiscoveryInfoPtr
-> IO TaskInfoPtr
foreign import ccall unsafe "ext/types.h fromTaskInfo" c_fromTaskInfo
:: TaskInfoPtr
-> Ptr (Ptr CChar)
-> Ptr CInt
-> Ptr TaskIDPtr
-> Ptr SlaveIDPtr
-> Ptr (Ptr ResourcePtr)
-> Ptr CInt
-> Ptr ExecutorInfoPtr
-> Ptr CommandInfoPtr
-> Ptr (Ptr CChar)
-> Ptr CInt
-> Ptr ContainerInfoPtr
-> Ptr HealthCheckPtr
-> Ptr (Ptr LabelPtr)
-> Ptr CInt
-> Ptr DiscoveryInfoPtr
-> IO ()
foreign import ccall unsafe "ext/types.h destroyTaskInfo" c_destroyTaskInfo
:: TaskInfoPtr
-> IO ()
instance CPPValue TaskInfo where
marshal t = do
(np, nl) <- cstring $ taskInfoName t
rps <- mapM cppValue (taskInfoResources t)
tid <- cppValue $ taskInfoId' t
sid <- cppValue $ taskInfoSlaveId t
eip <- maybe (return nullPtr) cppValue $ case taskInfoImplementation t of
TaskExecutor e -> Just e
_ -> Nothing
cip <- maybe (return nullPtr) cppValue $ case taskInfoImplementation t of
TaskCommand c -> Just c
_ -> Nothing
(tdp, tdl) <- maybeCString $ taskInfoData_ t
(rpp, rl) <- arrayLen rps
ctrp <- maybe (return nullPtr) cppValue $ taskInfoContainer t
hcp <- maybe (return nullPtr) cppValue $ taskInfoHealthCheck t
labelp <- mapM (cppValue . toLabel) $ taskInfoLabels t
(labelpp, labell) <- arrayLen labelp
discp <- maybe (return nullPtr) cppValue $ taskInfoDiscovery t
liftIO $ c_toTaskInfo np (fromIntegral nl) tid sid rpp (fromIntegral rl) eip cip tdp (fromIntegral tdl) ctrp hcp labelpp (fromIntegral labell) discp
unmarshal ti = do
npp <- alloc
nlp <- alloc
tpp <- alloc
spp <- alloc
rpp <- alloc
rlp <- alloc
epp <- alloc
cpp <- alloc
dpp <- alloc
dlp <- alloc
cip <- alloc
hcp <- alloc
labelpp <- alloc
labellp <- alloc
discp <- alloc
poke rpp nullPtr
poke epp nullPtr
poke cpp nullPtr
poke dpp nullPtr
poke cip nullPtr
poke hcp nullPtr
poke labelpp nullPtr
poke discp nullPtr
liftIO $ c_fromTaskInfo ti npp nlp tpp spp rpp rlp epp cpp dpp dlp cip hcp labelpp labellp discp
n <- peekCString (npp, nlp)
tp <- peek tpp
t <- peekCPP tp
sp <- peek spp
s <- peekCPP sp
rp <- peek rpp
rs <- mapM peekCPP =<< peekArray (rp, rlp)
ep <- peek epp
e <- if ep == nullPtr
then return Nothing
else fmap Just $ unmarshal ep
cp <- peek cpp
c <- if cp == nullPtr
then return Nothing
else fmap Just $ unmarshal cp
-- this shouldn't ever happen, so it's probably ok to just have an error here.
let ei = maybe (maybe (error "FATAL: TaskInfo must have CommandInfo or ExecutorInfo") TaskCommand c) TaskExecutor e
d <- peekMaybeBS dpp dlp
ci <- peekMaybeCPP cip
hc <- peekMaybeCPP hcp
labelp <- peek labelpp
labels <- mapM peekCPP =<< peekArray (labelp, labellp)
disc <- peekMaybeCPP discp
return $ TaskInfo n t s rs ei d ci hc (map fromLabel labels) disc
destroy = c_destroyTaskInfo
equalExceptDefaults (TaskInfo n id_ sid rs ei d ci hc labels disc) (TaskInfo n' id' sid' rs' ei' d' ci' hc' labels' disc') =
n == n' && id_ == id' && sid == sid' && ci == ci' && hc == hc' && d == d' && and (zipWith equalExceptDefaults rs rs') && labels == labels' && disc == disc'
&& case (ei, ei') of
(TaskCommand c, TaskCommand c') -> equalExceptDefaults c c'
(TaskExecutor e, TaskExecutor e') -> equalExceptDefaults e e'
_ -> False
|
Atidot/hs-mesos
|
src/System/Mesos/Raw/TaskInfo.hs
|
mit
| 4,590
| 0
| 23
| 1,310
| 1,489
| 711
| 778
| 125
| 0
|
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Test.AWS.Gen.KMS
-- 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)
--
module Test.AWS.Gen.KMS where
import Data.Proxy
import Test.AWS.Fixture
import Test.AWS.Prelude
import Test.Tasty
import Network.AWS.KMS
import Test.AWS.KMS.Internal
-- Auto-generated: the actual test selection needs to be manually placed into
-- the top-level so that real test data can be incrementally added.
--
-- This commented snippet is what the entire set should look like:
-- fixtures :: TestTree
-- fixtures =
-- [ testGroup "request"
-- [ testEncrypt $
-- encrypt
--
-- , testListGrants $
-- listGrants
--
-- , testDisableKeyRotation $
-- disableKeyRotation
--
-- , testGenerateDataKeyWithoutPlaintext $
-- generateDataKeyWithoutPlaintext
--
-- , testEnableKeyRotation $
-- enableKeyRotation
--
-- , testCreateAlias $
-- createAlias
--
-- , testCreateGrant $
-- createGrant
--
-- , testListAliases $
-- listAliases
--
-- , testGenerateRandom $
-- generateRandom
--
-- , testCreateKey $
-- createKey
--
-- , testDisableKey $
-- disableKey
--
-- , testRetireGrant $
-- retireGrant
--
-- , testListKeys $
-- listKeys
--
-- , testGetKeyRotationStatus $
-- getKeyRotationStatus
--
-- , testGenerateDataKey $
-- generateDataKey
--
-- , testDeleteAlias $
-- deleteAlias
--
-- , testUpdateAlias $
-- updateAlias
--
-- , testDescribeKey $
-- describeKey
--
-- , testDecrypt $
-- decrypt
--
-- , testUpdateKeyDescription $
-- updateKeyDescription
--
-- , testReEncrypt $
-- reEncrypt
--
-- , testListKeyPolicies $
-- listKeyPolicies
--
-- , testPutKeyPolicy $
-- putKeyPolicy
--
-- , testEnableKey $
-- enableKey
--
-- , testRevokeGrant $
-- revokeGrant
--
-- , testGetKeyPolicy $
-- getKeyPolicy
--
-- ]
-- , testGroup "response"
-- [ testEncryptResponse $
-- encryptResponse
--
-- , testListGrantsResponse $
-- listGrantsResponse
--
-- , testDisableKeyRotationResponse $
-- disableKeyRotationResponse
--
-- , testGenerateDataKeyWithoutPlaintextResponse $
-- generateDataKeyWithoutPlaintextResponse
--
-- , testEnableKeyRotationResponse $
-- enableKeyRotationResponse
--
-- , testCreateAliasResponse $
-- createAliasResponse
--
-- , testCreateGrantResponse $
-- createGrantResponse
--
-- , testListAliasesResponse $
-- listAliasesResponse
--
-- , testGenerateRandomResponse $
-- generateRandomResponse
--
-- , testCreateKeyResponse $
-- createKeyResponse
--
-- , testDisableKeyResponse $
-- disableKeyResponse
--
-- , testRetireGrantResponse $
-- retireGrantResponse
--
-- , testListKeysResponse $
-- listKeysResponse
--
-- , testGetKeyRotationStatusResponse $
-- getKeyRotationStatusResponse
--
-- , testGenerateDataKeyResponse $
-- generateDataKeyResponse
--
-- , testDeleteAliasResponse $
-- deleteAliasResponse
--
-- , testUpdateAliasResponse $
-- updateAliasResponse
--
-- , testDescribeKeyResponse $
-- describeKeyResponse
--
-- , testDecryptResponse $
-- decryptResponse
--
-- , testUpdateKeyDescriptionResponse $
-- updateKeyDescriptionResponse
--
-- , testReEncryptResponse $
-- reEncryptResponse
--
-- , testListKeyPoliciesResponse $
-- listKeyPoliciesResponse
--
-- , testPutKeyPolicyResponse $
-- putKeyPolicyResponse
--
-- , testEnableKeyResponse $
-- enableKeyResponse
--
-- , testRevokeGrantResponse $
-- revokeGrantResponse
--
-- , testGetKeyPolicyResponse $
-- getKeyPolicyResponse
--
-- ]
-- ]
-- Requests
testEncrypt :: Encrypt -> TestTree
testEncrypt = req
"Encrypt"
"fixture/Encrypt.yaml"
testListGrants :: ListGrants -> TestTree
testListGrants = req
"ListGrants"
"fixture/ListGrants.yaml"
testDisableKeyRotation :: DisableKeyRotation -> TestTree
testDisableKeyRotation = req
"DisableKeyRotation"
"fixture/DisableKeyRotation.yaml"
testGenerateDataKeyWithoutPlaintext :: GenerateDataKeyWithoutPlaintext -> TestTree
testGenerateDataKeyWithoutPlaintext = req
"GenerateDataKeyWithoutPlaintext"
"fixture/GenerateDataKeyWithoutPlaintext.yaml"
testEnableKeyRotation :: EnableKeyRotation -> TestTree
testEnableKeyRotation = req
"EnableKeyRotation"
"fixture/EnableKeyRotation.yaml"
testCreateAlias :: CreateAlias -> TestTree
testCreateAlias = req
"CreateAlias"
"fixture/CreateAlias.yaml"
testCreateGrant :: CreateGrant -> TestTree
testCreateGrant = req
"CreateGrant"
"fixture/CreateGrant.yaml"
testListAliases :: ListAliases -> TestTree
testListAliases = req
"ListAliases"
"fixture/ListAliases.yaml"
testGenerateRandom :: GenerateRandom -> TestTree
testGenerateRandom = req
"GenerateRandom"
"fixture/GenerateRandom.yaml"
testCreateKey :: CreateKey -> TestTree
testCreateKey = req
"CreateKey"
"fixture/CreateKey.yaml"
testDisableKey :: DisableKey -> TestTree
testDisableKey = req
"DisableKey"
"fixture/DisableKey.yaml"
testRetireGrant :: RetireGrant -> TestTree
testRetireGrant = req
"RetireGrant"
"fixture/RetireGrant.yaml"
testListKeys :: ListKeys -> TestTree
testListKeys = req
"ListKeys"
"fixture/ListKeys.yaml"
testGetKeyRotationStatus :: GetKeyRotationStatus -> TestTree
testGetKeyRotationStatus = req
"GetKeyRotationStatus"
"fixture/GetKeyRotationStatus.yaml"
testGenerateDataKey :: GenerateDataKey -> TestTree
testGenerateDataKey = req
"GenerateDataKey"
"fixture/GenerateDataKey.yaml"
testDeleteAlias :: DeleteAlias -> TestTree
testDeleteAlias = req
"DeleteAlias"
"fixture/DeleteAlias.yaml"
testUpdateAlias :: UpdateAlias -> TestTree
testUpdateAlias = req
"UpdateAlias"
"fixture/UpdateAlias.yaml"
testDescribeKey :: DescribeKey -> TestTree
testDescribeKey = req
"DescribeKey"
"fixture/DescribeKey.yaml"
testDecrypt :: Decrypt -> TestTree
testDecrypt = req
"Decrypt"
"fixture/Decrypt.yaml"
testUpdateKeyDescription :: UpdateKeyDescription -> TestTree
testUpdateKeyDescription = req
"UpdateKeyDescription"
"fixture/UpdateKeyDescription.yaml"
testReEncrypt :: ReEncrypt -> TestTree
testReEncrypt = req
"ReEncrypt"
"fixture/ReEncrypt.yaml"
testListKeyPolicies :: ListKeyPolicies -> TestTree
testListKeyPolicies = req
"ListKeyPolicies"
"fixture/ListKeyPolicies.yaml"
testPutKeyPolicy :: PutKeyPolicy -> TestTree
testPutKeyPolicy = req
"PutKeyPolicy"
"fixture/PutKeyPolicy.yaml"
testEnableKey :: EnableKey -> TestTree
testEnableKey = req
"EnableKey"
"fixture/EnableKey.yaml"
testRevokeGrant :: RevokeGrant -> TestTree
testRevokeGrant = req
"RevokeGrant"
"fixture/RevokeGrant.yaml"
testGetKeyPolicy :: GetKeyPolicy -> TestTree
testGetKeyPolicy = req
"GetKeyPolicy"
"fixture/GetKeyPolicy.yaml"
-- Responses
testEncryptResponse :: EncryptResponse -> TestTree
testEncryptResponse = res
"EncryptResponse"
"fixture/EncryptResponse.proto"
kMS
(Proxy :: Proxy Encrypt)
testListGrantsResponse :: ListGrantsResponse -> TestTree
testListGrantsResponse = res
"ListGrantsResponse"
"fixture/ListGrantsResponse.proto"
kMS
(Proxy :: Proxy ListGrants)
testDisableKeyRotationResponse :: DisableKeyRotationResponse -> TestTree
testDisableKeyRotationResponse = res
"DisableKeyRotationResponse"
"fixture/DisableKeyRotationResponse.proto"
kMS
(Proxy :: Proxy DisableKeyRotation)
testGenerateDataKeyWithoutPlaintextResponse :: GenerateDataKeyWithoutPlaintextResponse -> TestTree
testGenerateDataKeyWithoutPlaintextResponse = res
"GenerateDataKeyWithoutPlaintextResponse"
"fixture/GenerateDataKeyWithoutPlaintextResponse.proto"
kMS
(Proxy :: Proxy GenerateDataKeyWithoutPlaintext)
testEnableKeyRotationResponse :: EnableKeyRotationResponse -> TestTree
testEnableKeyRotationResponse = res
"EnableKeyRotationResponse"
"fixture/EnableKeyRotationResponse.proto"
kMS
(Proxy :: Proxy EnableKeyRotation)
testCreateAliasResponse :: CreateAliasResponse -> TestTree
testCreateAliasResponse = res
"CreateAliasResponse"
"fixture/CreateAliasResponse.proto"
kMS
(Proxy :: Proxy CreateAlias)
testCreateGrantResponse :: CreateGrantResponse -> TestTree
testCreateGrantResponse = res
"CreateGrantResponse"
"fixture/CreateGrantResponse.proto"
kMS
(Proxy :: Proxy CreateGrant)
testListAliasesResponse :: ListAliasesResponse -> TestTree
testListAliasesResponse = res
"ListAliasesResponse"
"fixture/ListAliasesResponse.proto"
kMS
(Proxy :: Proxy ListAliases)
testGenerateRandomResponse :: GenerateRandomResponse -> TestTree
testGenerateRandomResponse = res
"GenerateRandomResponse"
"fixture/GenerateRandomResponse.proto"
kMS
(Proxy :: Proxy GenerateRandom)
testCreateKeyResponse :: CreateKeyResponse -> TestTree
testCreateKeyResponse = res
"CreateKeyResponse"
"fixture/CreateKeyResponse.proto"
kMS
(Proxy :: Proxy CreateKey)
testDisableKeyResponse :: DisableKeyResponse -> TestTree
testDisableKeyResponse = res
"DisableKeyResponse"
"fixture/DisableKeyResponse.proto"
kMS
(Proxy :: Proxy DisableKey)
testRetireGrantResponse :: RetireGrantResponse -> TestTree
testRetireGrantResponse = res
"RetireGrantResponse"
"fixture/RetireGrantResponse.proto"
kMS
(Proxy :: Proxy RetireGrant)
testListKeysResponse :: ListKeysResponse -> TestTree
testListKeysResponse = res
"ListKeysResponse"
"fixture/ListKeysResponse.proto"
kMS
(Proxy :: Proxy ListKeys)
testGetKeyRotationStatusResponse :: GetKeyRotationStatusResponse -> TestTree
testGetKeyRotationStatusResponse = res
"GetKeyRotationStatusResponse"
"fixture/GetKeyRotationStatusResponse.proto"
kMS
(Proxy :: Proxy GetKeyRotationStatus)
testGenerateDataKeyResponse :: GenerateDataKeyResponse -> TestTree
testGenerateDataKeyResponse = res
"GenerateDataKeyResponse"
"fixture/GenerateDataKeyResponse.proto"
kMS
(Proxy :: Proxy GenerateDataKey)
testDeleteAliasResponse :: DeleteAliasResponse -> TestTree
testDeleteAliasResponse = res
"DeleteAliasResponse"
"fixture/DeleteAliasResponse.proto"
kMS
(Proxy :: Proxy DeleteAlias)
testUpdateAliasResponse :: UpdateAliasResponse -> TestTree
testUpdateAliasResponse = res
"UpdateAliasResponse"
"fixture/UpdateAliasResponse.proto"
kMS
(Proxy :: Proxy UpdateAlias)
testDescribeKeyResponse :: DescribeKeyResponse -> TestTree
testDescribeKeyResponse = res
"DescribeKeyResponse"
"fixture/DescribeKeyResponse.proto"
kMS
(Proxy :: Proxy DescribeKey)
testDecryptResponse :: DecryptResponse -> TestTree
testDecryptResponse = res
"DecryptResponse"
"fixture/DecryptResponse.proto"
kMS
(Proxy :: Proxy Decrypt)
testUpdateKeyDescriptionResponse :: UpdateKeyDescriptionResponse -> TestTree
testUpdateKeyDescriptionResponse = res
"UpdateKeyDescriptionResponse"
"fixture/UpdateKeyDescriptionResponse.proto"
kMS
(Proxy :: Proxy UpdateKeyDescription)
testReEncryptResponse :: ReEncryptResponse -> TestTree
testReEncryptResponse = res
"ReEncryptResponse"
"fixture/ReEncryptResponse.proto"
kMS
(Proxy :: Proxy ReEncrypt)
testListKeyPoliciesResponse :: ListKeyPoliciesResponse -> TestTree
testListKeyPoliciesResponse = res
"ListKeyPoliciesResponse"
"fixture/ListKeyPoliciesResponse.proto"
kMS
(Proxy :: Proxy ListKeyPolicies)
testPutKeyPolicyResponse :: PutKeyPolicyResponse -> TestTree
testPutKeyPolicyResponse = res
"PutKeyPolicyResponse"
"fixture/PutKeyPolicyResponse.proto"
kMS
(Proxy :: Proxy PutKeyPolicy)
testEnableKeyResponse :: EnableKeyResponse -> TestTree
testEnableKeyResponse = res
"EnableKeyResponse"
"fixture/EnableKeyResponse.proto"
kMS
(Proxy :: Proxy EnableKey)
testRevokeGrantResponse :: RevokeGrantResponse -> TestTree
testRevokeGrantResponse = res
"RevokeGrantResponse"
"fixture/RevokeGrantResponse.proto"
kMS
(Proxy :: Proxy RevokeGrant)
testGetKeyPolicyResponse :: GetKeyPolicyResponse -> TestTree
testGetKeyPolicyResponse = res
"GetKeyPolicyResponse"
"fixture/GetKeyPolicyResponse.proto"
kMS
(Proxy :: Proxy GetKeyPolicy)
|
fmapfmapfmap/amazonka
|
amazonka-kms/test/Test/AWS/Gen/KMS.hs
|
mpl-2.0
| 13,353
| 0
| 7
| 2,924
| 1,549
| 911
| 638
| 269
| 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.UnassignInstance
-- 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.
-- | Unassigns a registered instance from all of it's layers. The instance remains
-- in the stack as an unassigned instance and can be assigned to another layer,
-- as needed. You cannot use this action with instances that were created with
-- AWS OpsWorks.
--
-- 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_UnassignInstance.html>
module Network.AWS.OpsWorks.UnassignInstance
(
-- * Request
UnassignInstance
-- ** Request constructor
, unassignInstance
-- ** Request lenses
, ui1InstanceId
-- * Response
, UnassignInstanceResponse
-- ** Response constructor
, unassignInstanceResponse
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.OpsWorks.Types
import qualified GHC.Exts
newtype UnassignInstance = UnassignInstance
{ _ui1InstanceId :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'UnassignInstance' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ui1InstanceId' @::@ 'Text'
--
unassignInstance :: Text -- ^ 'ui1InstanceId'
-> UnassignInstance
unassignInstance p1 = UnassignInstance
{ _ui1InstanceId = p1
}
-- | The instance ID.
ui1InstanceId :: Lens' UnassignInstance Text
ui1InstanceId = lens _ui1InstanceId (\s a -> s { _ui1InstanceId = a })
data UnassignInstanceResponse = UnassignInstanceResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'UnassignInstanceResponse' constructor.
unassignInstanceResponse :: UnassignInstanceResponse
unassignInstanceResponse = UnassignInstanceResponse
instance ToPath UnassignInstance where
toPath = const "/"
instance ToQuery UnassignInstance where
toQuery = const mempty
instance ToHeaders UnassignInstance
instance ToJSON UnassignInstance where
toJSON UnassignInstance{..} = object
[ "InstanceId" .= _ui1InstanceId
]
instance AWSRequest UnassignInstance where
type Sv UnassignInstance = OpsWorks
type Rs UnassignInstance = UnassignInstanceResponse
request = post "UnassignInstance"
response = nullResponse UnassignInstanceResponse
|
romanb/amazonka
|
amazonka-opsworks/gen/Network/AWS/OpsWorks/UnassignInstance.hs
|
mpl-2.0
| 3,531
| 0
| 9
| 714
| 363
| 224
| 139
| 48
| 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>SOAP Scanner | 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/soap/src/main/javahelp/org/zaproxy/zap/extension/soap/resources/help_sr_CS/helpset_sr_CS.hs
|
apache-2.0
| 974
| 85
| 52
| 160
| 398
| 210
| 188
| -1
| -1
|
module Foundation where
import Prelude
import Yesod
import Yesod.Static
import Yesod.Auth
import Yesod.Auth.BrowserId
import Yesod.Auth.GoogleEmail
import Yesod.Default.Config
import Yesod.Default.Util (addStaticContentExternal)
import Network.HTTP.Conduit (Manager)
import qualified Settings
import Settings.Development (development)
import qualified Database.Persist.Store
import Settings.StaticFiles
import Database.Persist.GenericSql
import Settings (widgetFile, Extra (..))
import Model
import Text.Jasmine (minifym)
import Web.ClientSession (getKey)
import Text.Hamlet (hamletFile)
-- | The site argument for your application. This can be a good place to
-- keep settings and values requiring initialization before your application
-- starts running, such as database connections. Every handler will have
-- access to the data present here.
data App = App
{ settings :: AppConfig DefaultEnv Extra
, getStatic :: Static -- ^ Settings for static file serving.
, connPool :: Database.Persist.Store.PersistConfigPool Settings.PersistConfig -- ^ Database connection pool.
, httpManager :: Manager
, persistConfig :: Settings.PersistConfig
}
-- Set up i18n messages. See the message folder.
mkMessage "App" "messages" "en"
-- This is where we define all of the routes in our application. For a full
-- explanation of the syntax, please see:
-- http://www.yesodweb.com/book/handler
--
-- This function does three things:
--
-- * Creates the route datatype AppRoute. Every valid URL in your
-- application can be represented as a value of this type.
-- * Creates the associated type:
-- type instance Route App = AppRoute
-- * Creates the value resourcesApp which contains information on the
-- resources declared below. This is used in Handler.hs by the call to
-- mkYesodDispatch
--
-- What this function does *not* do is create a YesodSite instance for
-- App. Creating that instance requires all of the handler functions
-- for our application to be in scope. However, the handler functions
-- usually require access to the AppRoute datatype. Therefore, we
-- split these actions into two functions and place them in separate files.
mkYesodData "App" $(parseRoutesFile "config/routes")
type Form x = Html -> MForm App App (FormResult x, Widget)
-- Please see the documentation for the Yesod typeclass. There are a number
-- of settings which can be configured by overriding methods here.
instance Yesod App where
approot = ApprootMaster $ appRoot . settings
-- Store session data on the client in encrypted cookies,
-- default session idle timeout is 120 minutes
makeSessionBackend _ = do
key <- getKey "config/client_session_key.aes"
return . Just $ clientSessionBackend key 120
defaultLayout widget = do
master <- getYesod
mmsg <- getMessage
-- We break up the default layout into two components:
-- default-layout is the contents of the body tag, and
-- default-layout-wrapper is the entire page. Since the final
-- value passed to hamletToRepHtml cannot be a widget, this allows
-- you to use normal widget features in default-layout.
pc <- widgetToPageContent $ do
$(widgetFile "normalize")
addStylesheet $ StaticR css_bootstrap_css
$(widgetFile "default-layout")
hamletToRepHtml $(hamletFile "templates/default-layout-wrapper.hamlet")
-- This is done to provide an optimization for serving static files from
-- a separate domain. Please see the staticRoot setting in Settings.hs
urlRenderOverride y (StaticR s) =
Just $ uncurry (joinPath y (Settings.staticRoot $ settings y)) $ renderRoute s
urlRenderOverride _ _ = Nothing
-- The page to be redirected to when authentication is required.
authRoute _ = Just $ AuthR LoginR
-- This function creates static content files in the static folder
-- and names them based on a hash of their content. This allows
-- expiration dates to be set far in the future without worry of
-- users receiving stale content.
addStaticContent = addStaticContentExternal minifym base64md5 Settings.staticDir (StaticR . flip StaticRoute [])
-- Place Javascript at bottom of the body tag so the rest of the page loads first
jsLoader _ = BottomOfBody
-- What messages should be logged. The following includes all messages when
-- in development, and warnings and errors in production.
shouldLog _ _source level =
development || level == LevelWarn || level == LevelError
-- How to run database actions.
instance YesodPersist App where
type YesodPersistBackend App = SqlPersist
runDB f = do
master <- getYesod
Database.Persist.Store.runPool
(persistConfig master)
f
(connPool master)
instance YesodAuth App where
type AuthId App = UserId
-- Where to send a user after successful login
loginDest _ = HomeR
-- Where to send a user after logout
logoutDest _ = HomeR
getAuthId creds = runDB $ do
x <- getBy $ UniqueUser $ credsIdent creds
case x of
Just (Entity uid _) -> return $ Just uid
Nothing -> do
fmap Just $ insert $ User (credsIdent creds) Nothing
-- You can add other plugins like BrowserID, email or OAuth here
authPlugins _ = [authBrowserId, authGoogleEmail]
authHttpManager = httpManager
-- This instance is required to use forms. You can modify renderMessage to
-- achieve customized and internationalized form validation messages.
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
-- | Get the 'Extra' value, used to hold data from the settings.yml file.
getExtra :: Handler Extra
getExtra = fmap (appExtra . settings) getYesod
-- Note: previous versions of the scaffolding included a deliver function to
-- send emails. Unfortunately, there are too many different options for us to
-- give a reasonable default. Instead, the information is available on the
-- wiki:
--
-- https://github.com/yesodweb/yesod/wiki/Sending-email
|
puffnfresh/yesod-buildpack-demo
|
Foundation.hs
|
bsd-2-clause
| 6,140
| 0
| 17
| 1,293
| 824
| 455
| 369
| -1
| -1
|
module Graphics.UI.Threepenny.Canvas (
-- * Synopsis
-- | Partial binding to the HTML5 canvas API.
-- * Documentation
Canvas
, Vector, Point
, Color(..), ColorStop, Gradient, FillStyle
, drawImage, clearCanvas
, solidColor, htmlColor
, linearGradient, horizontalLinearGradient, verticalLinearGradient
, fillRect, fillStyle, strokeStyle, lineWidth, textFont
, TextAlign(..), textAlign
, beginPath, moveTo, lineTo, closePath, arc, arc'
, fill, stroke, fillText, strokeText
) where
import Data.Char (toUpper)
import Data.List(intercalate)
import Numeric (showHex)
import Graphics.UI.Threepenny.Core
import qualified Data.Aeson as JSON
{-----------------------------------------------------------------------------
Canvas
------------------------------------------------------------------------------}
type Canvas = Element
type Vector = Point
type Point = (Double, Double)
data Color = RGB { red :: Int, green :: Int, blue :: Int }
| RGBA { red :: Int, green :: Int, blue :: Int, alpha :: Double }
deriving (Eq, Show)
type ColorStop = (Double, Color)
data Gradient
-- | defines a linear gradient
-- see <http://www.w3schools.com/tags/canvas_createlineargradient.asp>
= LinearGradient
{ upperLeft :: Vector -- ^ the left-upper point where the gradient should begin
, gradWidth :: Double -- ^ the width of the gradient
, gradHeight :: Double -- ^ the height of the gradient
, colorStops :: [ColorStop] -- ^ the gradients color stops
} deriving (Show, Eq)
data FillStyle
= SolidColor Color
| HtmlColor String -- Html representation of a color
| Gradient Gradient
deriving (Show, Eq)
{-----------------------------------------------------------------------------
Image drawing
------------------------------------------------------------------------------}
-- | Draw the image of an image element onto the canvas at a specified position.
drawImage :: Element -> Vector -> Canvas -> UI ()
drawImage image (x,y) canvas =
runFunction $ ffi "%1.getContext('2d').drawImage(%2,%3,%4)" canvas image x y
{-----------------------------------------------------------------------------
Fill Styles
------------------------------------------------------------------------------}
-- | creates a solid-color fillstyle
solidColor :: Color -> FillStyle
solidColor rgb = SolidColor rgb
-- | Solid color represented as a HTML string.
htmlColor :: String -> FillStyle
htmlColor = HtmlColor
-- | creates a linear gradient fill style
linearGradient :: Point -- ^ The upper-left coordinate of the gradient
-> Double -- ^ The width of the gradient
-> Double -- ^ The height of the gradient
-> [ColorStop] -- ^ the color-stops for the gradient
-> FillStyle
linearGradient (x0, y0) w h sts = Gradient $ LinearGradient (x0,y0) w h sts
-- | creates a simple horizontal gradient
horizontalLinearGradient:: Point -- ^ The upper-left coordinate of the gradient
-> Double -- ^ The width of the gradient
-> Color -- ^ The starting color of the gradient
-> Color -- ^ The ending color of the gradient
-> FillStyle
horizontalLinearGradient pt w c0 c1 = linearGradient pt w 0 [(0, c0), (1, c1)]
-- | creates a simple vertical gradient
verticalLinearGradient:: Point -- ^ The upper-left coordinate of the gradient
-> Double -- ^ The height of the gradient
-> Color -- ^ The starting color of the gradient
-> Color -- ^ The ending color of the gradient
-> FillStyle
verticalLinearGradient pt h c0 c1 = linearGradient pt 0 h [(0, c0), (1, c1)]
{-----------------------------------------------------------------------------
general
------------------------------------------------------------------------------}
-- | Clear the canvas
clearCanvas :: Canvas -> UI ()
clearCanvas = runFunction . ffi "%1.getContext('2d').clear()"
{-----------------------------------------------------------------------------
fill primitives
------------------------------------------------------------------------------}
-- | Draw a filled rectangle.
--
-- The 'fillStyle' attribute determines the color.
fillRect
:: Point -- ^ upper left corner
-> Double -- ^ width in pixels
-> Double -- ^ height in pixels
-> Canvas -> UI ()
fillRect (x,y) w h canvas =
runFunction $ ffi "%1.getContext('2d').fillRect(%2, %3, %4, %5)" canvas x y w h
-- | The Fillstyle to use inside shapes.
-- write-only as I could not find how to consistently read the fillstyle
fillStyle :: WriteAttr Canvas FillStyle
fillStyle = mkWriteAttr assignFillStyle
-- | sets the current fill style of the canvas context
assignFillStyle :: FillStyle -> Canvas -> UI ()
assignFillStyle (Gradient fs) canvas =
runFunction $ ffi cmd canvas
where cmd = "var ctx=%1.getContext('2d'); var grd=" ++ fsStr fs ++ cStops fs ++ "ctx.fillStyle=grd;"
fsStr (LinearGradient (x0, y0) w h _)
= "ctx.createLinearGradient(" ++ pStr [x0, y0, x0+w, y0+h] ++ ");"
cStops (LinearGradient _ _ _ sts) = concatMap addStop sts
addStop (p,c) = "grd.addColorStop(" ++ show p ++ ",'" ++ rgbString c ++ "');"
pStr = intercalate "," . map show
assignFillStyle (SolidColor color) canvas =
runFunction $ ffi "%1.getContext('2d').fillStyle=%2" canvas (rgbString color)
assignFillStyle (HtmlColor color) canvas =
runFunction $ ffi "%1.getContext('2d').fillStyle=%2" canvas color
-- | The color or style to use for the lines around shapes.
-- Default is @#000@ (black).
strokeStyle :: Attr Canvas String
strokeStyle = fromObjectProperty "getContext('2d').strokeStyle"
-- | The width of lines. Default is @1@.
lineWidth :: Attr Canvas Double
lineWidth = fromObjectProperty "getContext('2d').lineWidth"
-- | The font used for 'fillText' and 'strokeText'.
-- Default is @10px sans-serif@.
textFont :: Attr Canvas String
textFont = fromObjectProperty "getContext('2d').font"
data TextAlign = Start | End | LeftAligned | RightAligned | Center
deriving (Eq, Show, Read)
aToS :: TextAlign -> String
aToS algn =
case algn of
Start -> "start"
End -> "end"
LeftAligned -> "left"
RightAligned -> "right"
Center -> "center"
sToA :: String -> TextAlign
sToA algn =
case algn of
"start" -> Start
"end" -> End
"left" -> LeftAligned
"right" -> RightAligned
"center" -> Center
_ -> Start
-- | The alignment for 'fillText' and 'strokeText'. Default is 'Start'.
textAlign :: Attr Canvas TextAlign
textAlign = bimapAttr aToS sToA $ textAlignStr
where
textAlignStr :: Attr Canvas String
textAlignStr = fromObjectProperty "getContext('2d').textAlign"
-- | Starts a new path by resetting the list of sub-paths.
-- Call this function when you want to create a new path.
beginPath :: Canvas -> UI()
beginPath = runFunction . ffi "%1.getContext('2d').beginPath()"
-- | Moves the starting point of a new subpath to the @(x,y)@ coordinate.
moveTo :: Point -> Canvas -> UI()
moveTo (x,y) canvas =
runFunction $ ffi "%1.getContext('2d').moveTo(%2, %3)" canvas x y
-- | Connects the last point in the subpath to the @(x,y)@ coordinates
-- with a straight line.
lineTo :: Point -> Canvas -> UI()
lineTo (x,y) canvas =
runFunction $ ffi "%1.getContext('2d').lineTo(%2, %3)" canvas x y
-- | Draw a straight line from the current point to the start of the
-- path. If the shape has already been closed or has only one point,
-- this function does nothing.
closePath :: Canvas -> UI()
closePath = runFunction . ffi "%1.getContext('2d').closePath()"
-- | Add a circular arc to the current path.
arc
:: Point -- ^ Center of the circle of which the arc is a part.
-> Double -- ^ Radius of the circle of which the arc is a part.
-> Double -- ^ Starting angle, in radians.
-> Double -- ^ Ending angle, in radians.
-> Canvas -> UI ()
arc (x,y) radius startAngle endAngle canvas =
runFunction $ ffi "%1.getContext('2d').arc(%2, %3, %4, %5, %6)"
canvas x y radius startAngle endAngle
-- | Like 'arc', but with an extra argument that indicates whether
-- we go in counter-clockwise ('True') or clockwise ('False') direction.
arc' :: Point -> Double -> Double -> Double -> Bool -> Canvas -> UI ()
arc' (x,y) radius startAngle endAngle anti canvas =
runFunction $ ffi "%1.getContext('2d').arc(%2, %3, %4, %5, %6, %7)"
canvas x y radius startAngle endAngle anti
-- | Fills the subpaths with the current fill style.
fill :: Canvas -> UI ()
fill = runFunction . ffi "%1.getContext('2d').fill()"
-- | Strokes the subpaths with the current stroke style.
stroke :: Canvas -> UI ()
stroke = runFunction . ffi "%1.getContext('2d').stroke()"
-- | Render a text in solid color at a certain point on the canvas.
--
-- The 'fillStyle' attribute determines the color.
-- The 'textFont' attribute determines the font used.
-- The 'textAlign' attributes determines the position of the text
-- relative to the point.
fillText :: String -> Point -> Canvas -> UI ()
fillText text (x,y) canvas =
runFunction $ ffi "%1.getContext('2d').fillText(%2, %3, %4)" canvas text x y
-- | Render the outline of a text at a certain point on the canvas.
--
-- The 'strokeStyle' attribute determines the color of the outline.
-- The 'textFont' attribute determines the font used.
-- The 'textAlign' attributes determines the position of the text
-- relative to the point.
strokeText :: String -> Point -> Canvas -> UI ()
strokeText text (x,y) canvas =
runFunction $ ffi "%1.getContext('2d').strokeText(%2, %3, %4)" canvas text x y
{-----------------------------------------------------------------------------
helper functions
------------------------------------------------------------------------------}
rgbString :: Color -> String
rgbString color =
case color of
(RGB r g b) -> "#" ++ sh r ++ sh g ++ sh b
(RGBA r g b a) -> "rgba(" ++ show r ++ "," ++ show g ++ "," ++ show b ++ "," ++ show a ++ ")"
where sh i = pad . map toUpper $ showHex i ""
pad s
| length s == 0 = "00"
| length s == 1 = '0' : s
| length s == 2 = s
| otherwise = take 2 s
|
duplode/threepenny-gui
|
src/Graphics/UI/Threepenny/Canvas.hs
|
bsd-3-clause
| 10,542
| 0
| 16
| 2,373
| 1,972
| 1,082
| 890
| 157
| 6
|
{-
partDefault :: [(Part, a)] -> Group (Part, a)
partDefault xs = groupDefault $ fmap (\(p,x) -> (p^._instrument,(p,x))) xs
-}
|
FranklinChen/music-score
|
sketch/partDefault.hs
|
bsd-3-clause
| 132
| 0
| 2
| 24
| 3
| 2
| 1
| 1
| 0
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
module Distribution.Types.Benchmark (
Benchmark(..),
emptyBenchmark,
benchmarkType,
benchmarkModules,
benchmarkModulesAutogen
) where
import Prelude ()
import Distribution.Compat.Prelude
import Distribution.Types.BuildInfo
import Distribution.Types.BenchmarkType
import Distribution.Types.BenchmarkInterface
import Distribution.ModuleName
-- | A \"benchmark\" stanza in a cabal file.
--
data Benchmark = Benchmark {
benchmarkName :: String,
benchmarkInterface :: BenchmarkInterface,
benchmarkBuildInfo :: BuildInfo
}
deriving (Generic, Show, Read, Eq, Typeable, Data)
instance Binary Benchmark
instance Monoid Benchmark where
mempty = Benchmark {
benchmarkName = mempty,
benchmarkInterface = mempty,
benchmarkBuildInfo = mempty
}
mappend = (<>)
instance Semigroup Benchmark where
a <> b = Benchmark {
benchmarkName = combine' benchmarkName,
benchmarkInterface = combine benchmarkInterface,
benchmarkBuildInfo = combine benchmarkBuildInfo
}
where combine field = field a `mappend` field b
combine' f = case (f a, f b) of
("", x) -> x
(x, "") -> x
(x, y) -> error "Ambiguous values for benchmark field: '"
++ x ++ "' and '" ++ y ++ "'"
emptyBenchmark :: Benchmark
emptyBenchmark = mempty
benchmarkType :: Benchmark -> BenchmarkType
benchmarkType benchmark = case benchmarkInterface benchmark of
BenchmarkExeV10 ver _ -> BenchmarkTypeExe ver
BenchmarkUnsupported benchmarktype -> benchmarktype
-- | Get all the module names from a benchmark.
benchmarkModules :: Benchmark -> [ModuleName]
benchmarkModules benchmark = otherModules (benchmarkBuildInfo benchmark)
-- | Get all the auto generated module names from a benchmark.
-- This are a subset of 'benchmarkModules'.
benchmarkModulesAutogen :: Benchmark -> [ModuleName]
benchmarkModulesAutogen benchmark = autogenModules (benchmarkBuildInfo benchmark)
|
sopvop/cabal
|
Cabal/Distribution/Types/Benchmark.hs
|
bsd-3-clause
| 2,157
| 0
| 15
| 525
| 435
| 244
| 191
| 47
| 2
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module ToDoList where
import Control.Arrow ((&&&))
import Control.Lens ((.=))
import Data.Maybe
import Data.Traversable (for)
import Francium
import Francium.CSS hiding (filter)
import Francium.Component
import Francium.HTML
import GHCJS.Foreign
import GHCJS.Types
import IdiomExp
import ToDoItem
import qualified Storage
data ToDoList t =
ToDoList {addItem :: Event t JSString
,setStatuses :: Event t Status
,statusFilter :: Behavior t (Status -> Bool)
,clearCompleted :: Event t ()}
instance Component ToDoList where
data Output behavior event ToDoList = ToDoListOutput{allItems ::
behavior [Status]}
construct tdi =
mdo let addNonEmptyItem =
filterE (not . isEmptyString . fromJSString)
(addItem tdi)
eAddItem <-
do setStatusesLater <-
trim (setStatuses tdi)
execute (fmap (\x ->
FrameworksMoment
(do setStatuses' <- now setStatusesLater
trimComponent =<<
construct (ToDoItem x setStatuses')))
addNonEmptyItem)
openingStorage <-
liftIO (fmap (fromMaybe []) Storage.retrieve)
initialItems <-
for openingStorage
(\item ->
do component <-
trimComponent =<<
construct (ToDoItem (toJSString (Storage.title item))
(setStatuses tdi))
return (component
,(if Storage.complete item
then Complete
else Incomplete)))
startingView <-
fmap sequenceA
(for initialItems
(\(item,_) ->
do render_ <-
now (render item)
status_ <-
now (status (outputs item))
return $(i [|(render_,status_)|])))
let eItemsChanged =
accumE (map fst initialItems)
(unions [fmap append eAddItem
,destroyItem
,fmap const (incompleteItems <@ clearCompleted tdi)])
incompleteItems =
switchB (pure (map fst (filter (((== Incomplete) . snd)) initialItems)))
(fmap (fmap (map snd .
filter ((== Incomplete) . fst)))
(fmap (sequenceA .
map (\item ->
fmap (id &&& const item)
(status (outputs item))))
eItemsChanged))
items =
switchB startingView
(fmap (sequenceA .
fmap (\item ->
$(i [|(render item,status (outputs item))|])))
eItemsChanged)
destroyItem =
switchE (fmap (\events ->
anyMoment (fmap (unions .
(zipWith (\x -> (deleteElem x <$))
[0 ..]))
(mapM now events)))
(fmap (map (ToDoItem.destroy . outputs)) eItemsChanged))
visibleItems =
$(i [|map (pure fst)
$(i [|filter $(i [|statusFilter tdi . pure snd|]) items|])|])
stableData =
switchB (pure openingStorage)
(fmap (traverse (\item ->
$(i [|Storage.ToDoItem
(fmap fromJSString (steppedContent (outputs item)))
(fmap (== Complete) (status (outputs item)))|])))
eItemsChanged)
stableDataChanged <- changes stableData
reactimate' (fmap (fmap Storage.store) stableDataChanged)
return Instantiation {render =
fmap (into toDoContainer .
map (into itemContainer . pure))
visibleItems
,outputs =
ToDoListOutput {allItems =
fmap (fmap snd) items}}
itemContainer :: HTML
itemContainer =
with li_
(style .=
do borderBottomColor (rgb 237 237 237)
borderBottomStyle none
borderBottomWidth (px 1)
fontSize (px 24)
position relative)
[]
toDoContainer :: HTML
toDoContainer =
with ul_
(style .=
do listStyleType none
sym padding (px 0)
sym margin (px 0))
[]
isEmptyString :: JSString -> Bool
isEmptyString x = null (fromJSString x :: String)
append :: a -> [a] -> [a]
append x xs = xs ++ [x]
deleteElem :: Int -> [a] -> [a]
deleteElem _ [] = []
deleteElem j (x:xs)
| j < 0 = xs
| j > length xs = xs
| j == 0 = xs
| otherwise = x : deleteElem (j - 1) xs
|
bitemyapp/Francium
|
todo-mvc/ToDoList.hs
|
bsd-3-clause
| 5,558
| 8
| 27
| 2,653
| 1,011
| 594
| 417
| 136
| 1
|
-- {-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
module ShouldSucceed where
class C a where
op1 :: a -> a
class (C a) => B a where
op2 :: a -> a -> a
instance (B a) => B [a] where
op2 xs ys = xs
instance C [a] where
op1 xs = xs
{- This was passed by the prototype, but failed hard in the new
typechecker with the message
Fail:No match in theta_class
-}
|
rahulmutt/ghcvm
|
tests/suite/typecheck/compile/tc045.hs
|
bsd-3-clause
| 369
| 0
| 8
| 83
| 104
| 56
| 48
| 9
| 0
|
-- | Pretty printer utilities.
--
-- This is a re-export of Daan Leijen's pretty printer package (@wl-pprint@),
-- but with a `Pretty` class that includes a `pprPrec` function.
module DPH.Base.Pretty
( module Text.PrettyPrint.Leijen
, Pretty(..)
, pprParen
-- * Rendering
, RenderMode (..)
, render
, renderPlain
, renderIndent
, putDoc, putDocLn)
where
import Data.Set (Set)
import qualified Data.Set as Set
import qualified Text.PrettyPrint.Leijen as P
import Text.PrettyPrint.Leijen
hiding (Pretty(..), renderPretty, putDoc)
-- Utils ---------------------------------------------------------------------
-- | Wrap a `Doc` in parens if the predicate is true.
pprParen :: Bool -> Doc -> Doc
pprParen b c
= if b then parens c
else c
-- Pretty Class --------------------------------------------------------------
class Pretty a where
ppr :: a -> Doc
ppr = pprPrec 0
pprPrec :: Int -> a -> Doc
pprPrec _ = ppr
instance Pretty () where
ppr = text . show
instance Pretty Bool where
ppr = text . show
instance Pretty Int where
ppr = text . show
instance Pretty Integer where
ppr = text . show
instance Pretty Char where
ppr = text . show
instance Pretty a => Pretty [a] where
ppr xs = encloseSep lbracket rbracket comma
$ map ppr xs
instance Pretty a => Pretty (Set a) where
ppr xs = encloseSep lbracket rbracket comma
$ map ppr $ Set.toList xs
instance (Pretty a, Pretty b) => Pretty (a, b) where
ppr (a, b) = parens $ ppr a <> comma <> ppr b
-- Rendering ------------------------------------------------------------------
-- | How to pretty print a doc.
data RenderMode
-- | Render the doc with indenting.
= RenderPlain
-- | Render the doc without indenting.
| RenderIndent
deriving (Eq, Show)
-- | Render a doc with the given mode.
render :: RenderMode -> Doc -> String
render mode doc
= case mode of
RenderPlain -> eatSpace True $ displayS (renderCompact doc) ""
RenderIndent -> displayS (P.renderPretty 0.8 100 doc) ""
where eatSpace :: Bool -> String -> String
eatSpace _ [] = []
eatSpace True (c:cs)
= case c of
' ' -> eatSpace True cs
'\n' -> eatSpace True cs
_ -> c : eatSpace False cs
eatSpace False (c:cs)
= case c of
' ' -> ' ' : eatSpace True cs
'\n' -> ' ' : eatSpace True cs
_ -> c : eatSpace False cs
-- | Convert a `Doc` to a string without indentation.
renderPlain :: Doc -> String
renderPlain = render RenderPlain
-- | Convert a `Doc` to a string with indentation
renderIndent :: Doc -> String
renderIndent = render RenderIndent
-- | Put a `Doc` to `stdout` using the given mode.
putDoc :: RenderMode -> Doc -> IO ()
putDoc mode doc
= putStr $ render mode doc
-- | Put a `Doc` to `stdout` using the given mode.
putDocLn :: RenderMode -> Doc -> IO ()
putDocLn mode doc
= putStrLn $ render mode doc
|
mainland/dph
|
dph-plugin/DPH/Base/Pretty.hs
|
bsd-3-clause
| 3,184
| 0
| 11
| 950
| 793
| 425
| 368
| 72
| 8
|
{-# LANGUAGE Haskell98, CPP, DeriveDataTypeable, ForeignFunctionInterface, TypeSynonymInstances #-}
{-# LINE 1 "dist/dist-sandbox-261cd265/build/Network/Socket/Internal.hs" #-}
{-# LINE 1 "Network/Socket/Internal.hsc" #-}
{-# LANGUAGE CPP #-}
{-# LINE 2 "Network/Socket/Internal.hsc" #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-----------------------------------------------------------------------------
-- |
-- Module : Network.Socket.Internal
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/network/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- A module containing semi-public 'Network.Socket' internals.
-- Modules which extend the 'Network.Socket' module will need to use
-- this module while ideally most users will be able to make do with
-- the public interface.
--
-----------------------------------------------------------------------------
{-# LINE 22 "Network/Socket/Internal.hsc" #-}
module Network.Socket.Internal
(
-- * Socket addresses
HostAddress
{-# LINE 28 "Network/Socket/Internal.hsc" #-}
, HostAddress6
, FlowInfo
, ScopeID
{-# LINE 32 "Network/Socket/Internal.hsc" #-}
, PortNumber(..)
, SockAddr(..)
, peekSockAddr
, pokeSockAddr
, sizeOfSockAddr
, sizeOfSockAddrByFamily
, withSockAddr
, withNewSockAddr
-- * Protocol families
, Family(..)
-- * Socket error functions
{-# LINE 49 "Network/Socket/Internal.hsc" #-}
, throwSocketError
, throwSocketErrorCode
-- * Guards for socket operations that may fail
, throwSocketErrorIfMinus1_
, throwSocketErrorIfMinus1Retry
, throwSocketErrorIfMinus1Retry_
, throwSocketErrorIfMinus1RetryMayBlock
-- ** Guards that wait and retry if the operation would block
-- | These guards are based on 'throwSocketErrorIfMinus1RetryMayBlock'.
-- They wait for socket readiness if the action fails with @EWOULDBLOCK@
-- or similar.
, throwSocketErrorWaitRead
, throwSocketErrorWaitWrite
-- * Initialization
, withSocketsDo
-- * Low-level helpers
, zeroMemory
) where
import Foreign.C.Error (throwErrno, throwErrnoIfMinus1Retry,
throwErrnoIfMinus1RetryMayBlock, throwErrnoIfMinus1_,
Errno(..), errnoToIOError)
{-# LINE 79 "Network/Socket/Internal.hsc" #-}
import Foreign.C.Types (CInt(..))
import GHC.Conc (threadWaitRead, threadWaitWrite)
{-# LINE 94 "Network/Socket/Internal.hsc" #-}
import Network.Socket.Types
-- ---------------------------------------------------------------------
-- Guards for socket operations that may fail
-- | Throw an 'IOError' corresponding to the current socket error.
throwSocketError :: String -- ^ textual description of the error location
-> IO a
-- | Like 'throwSocketError', but the error code is supplied as an argument.
--
-- On Windows, do not use errno. Use a system error code instead.
throwSocketErrorCode :: String -> CInt -> IO a
-- | Throw an 'IOError' corresponding to the current socket error if
-- the IO action returns a result of @-1@. Discards the result of the
-- IO action after error handling.
throwSocketErrorIfMinus1_
:: (Eq a, Num a)
=> String -- ^ textual description of the location
-> IO a -- ^ the 'IO' operation to be executed
-> IO ()
{-# SPECIALIZE throwSocketErrorIfMinus1_ :: String -> IO CInt -> IO () #-}
-- | Throw an 'IOError' corresponding to the current socket error if
-- the IO action returns a result of @-1@, but retries in case of an
-- interrupted operation.
throwSocketErrorIfMinus1Retry
:: (Eq a, Num a)
=> String -- ^ textual description of the location
-> IO a -- ^ the 'IO' operation to be executed
-> IO a
{-# SPECIALIZE throwSocketErrorIfMinus1Retry :: String -> IO CInt -> IO CInt #-}
-- | Throw an 'IOError' corresponding to the current socket error if
-- the IO action returns a result of @-1@, but retries in case of an
-- interrupted operation. Discards the result of the IO action after
-- error handling.
throwSocketErrorIfMinus1Retry_
:: (Eq a, Num a)
=> String -- ^ textual description of the location
-> IO a -- ^ the 'IO' operation to be executed
-> IO ()
throwSocketErrorIfMinus1Retry_ loc m =
throwSocketErrorIfMinus1Retry loc m >> return ()
{-# SPECIALIZE throwSocketErrorIfMinus1Retry_ :: String -> IO CInt -> IO () #-}
-- | Throw an 'IOError' corresponding to the current socket error if
-- the IO action returns a result of @-1@, but retries in case of an
-- interrupted operation. Checks for operations that would block and
-- executes an alternative action before retrying in that case.
throwSocketErrorIfMinus1RetryMayBlock
:: (Eq a, Num a)
=> String -- ^ textual description of the location
-> IO b -- ^ action to execute before retrying if an
-- immediate retry would block
-> IO a -- ^ the 'IO' operation to be executed
-> IO a
{-# SPECIALIZE throwSocketErrorIfMinus1RetryMayBlock
:: String -> IO b -> IO CInt -> IO CInt #-}
{-# LINE 160 "Network/Socket/Internal.hsc" #-}
throwSocketErrorIfMinus1RetryMayBlock name on_block act =
throwErrnoIfMinus1RetryMayBlock name act on_block
throwSocketErrorIfMinus1Retry = throwErrnoIfMinus1Retry
throwSocketErrorIfMinus1_ = throwErrnoIfMinus1_
throwSocketError = throwErrno
throwSocketErrorCode loc errno =
ioError (errnoToIOError loc (Errno errno) Nothing Nothing)
{-# LINE 220 "Network/Socket/Internal.hsc" #-}
-- | Like 'throwSocketErrorIfMinus1Retry', but if the action fails with
-- @EWOULDBLOCK@ or similar, wait for the socket to be read-ready,
-- and try again.
throwSocketErrorWaitRead :: (Eq a, Num a) => Socket -> String -> IO a -> IO a
throwSocketErrorWaitRead sock name io =
throwSocketErrorIfMinus1RetryMayBlock name
(threadWaitRead $ fromIntegral $ sockFd sock)
io
-- | Like 'throwSocketErrorIfMinus1Retry', but if the action fails with
-- @EWOULDBLOCK@ or similar, wait for the socket to be write-ready,
-- and try again.
throwSocketErrorWaitWrite :: (Eq a, Num a) => Socket -> String -> IO a -> IO a
throwSocketErrorWaitWrite sock name io =
throwSocketErrorIfMinus1RetryMayBlock name
(threadWaitWrite $ fromIntegral $ sockFd sock)
io
-- ---------------------------------------------------------------------------
-- WinSock support
{-| With older versions of the @network@ library on Windows operating systems,
the networking subsystem must be initialised using 'withSocketsDo' before
any networking operations can be used. eg.
> main = withSocketsDo $ do {...}
It is fine to nest calls to 'withSocketsDo', and to perform networking operations
after 'withSocketsDo' has returned.
In newer versions of the @network@ library it is only necessary to call
'withSocketsDo' if you are calling the 'MkSocket' constructor directly.
However, for compatibility with older versions on Windows, it is good practice
to always call 'withSocketsDo' (it's very cheap).
-}
{-# INLINE withSocketsDo #-}
withSocketsDo :: IO a -> IO a
{-# LINE 259 "Network/Socket/Internal.hsc" #-}
withSocketsDo x = x
{-# LINE 275 "Network/Socket/Internal.hsc" #-}
|
phischu/fragnix
|
tests/packages/scotty/Network.Socket.Internal.hs
|
bsd-3-clause
| 7,393
| 0
| 9
| 1,452
| 671
| 403
| 268
| 87
| 1
|
module Language.ABCdiff (abcdiff) where
-- -- $Id$
import Language
import Autolib.Set
import Autolib.Util.Zufall
import Control.Monad ( guard )
import Data.List ( sort, nub )
abcdiff :: Language
abcdiff = Language
{ abbreviation = "{ a^i b^j c^k : i /= j, j /= k, k /= i }"
, nametag = "ABCdiff"
, alphabet = mkSet "abc"
, sample = sam
, anti_sample = error "ABCdiff.anti_sample not implemented"
, contains = con
}
sam :: RandomC m
=> Int -> Int
-> m [ String ]
sam c n = do
ws <- sequence $ replicate c $ do
w <- sequence $ replicate n $ randomRIO ('a', 'c')
return $ sort w
return $ filter (contains abcdiff) $ nub ws
con :: String -> Bool
con w0 =
let (as, w1) = span (== 'a') w0; i = length as
(bs, w2) = span (== 'b') w1; j = length bs
(cs, w3) = span (== 'c') w2; k = length cs
in null w3 && (i /= j) && (j /= k) && (k /= i)
|
florianpilz/autotool
|
src/Language/ABCdiff.hs
|
gpl-2.0
| 952
| 6
| 15
| 299
| 371
| 201
| 170
| 28
| 1
|
module Uni.SS04.Serie5 where
-- $Id$
import SAT.Quiz
import SAT.Types
import SAT.Param ( p )
import Inter.Types
generate :: [ IO Variant ]
generate =
[ return $ Variant $ SAT.Quiz.quiz "SAT" "QUIZ" $ p 10
]
|
Erdwolf/autotool-bonn
|
src/Uni/SS04/Serie5.hs
|
gpl-2.0
| 220
| 0
| 9
| 49
| 75
| 43
| 32
| 8
| 1
|
{-
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE NoImplicitPrelude #-}
module Control.Monad.ST.Lazy.Unsafe (module M) where
import "base" Control.Monad.ST.Lazy.Unsafe as M
|
Ye-Yong-Chi/codeworld
|
codeworld-base/src/Control/Monad/ST/Lazy/Unsafe.hs
|
apache-2.0
| 771
| 0
| 4
| 136
| 29
| 23
| 6
| 4
| 0
|
{-# LANGUAGE DataKinds, NoImplicitPrelude #-}
{-# OPTIONS_GHC -Wall -fwarn-tabs #-}
module Tests.Function (allTests) where
import Prelude ((.), id, ($), asTypeOf)
import Language.Hakaru.Syntax.Prelude
import Language.Hakaru.Types.DataKind
import Language.Hakaru.Syntax.AST (Term)
import Language.Hakaru.Syntax.ABT (ABT)
import Language.Hakaru.Expect (expect)
import Test.HUnit
import Tests.TestTools
allTests :: Test
allTests = test [
"t41" ~: testS t41,
"pairFun" ~: testSS [] (pair (lam exp) pi),
"pairFunSimp" ~: testSS [pair (lam exp) (lam (log . exp))]
(pair (lam exp) (lam id)),
"unknownMeasure" ~: testSS
[lam $ \m ->
normal zero one >>
asTypeOf m (dirac (pair pi pi))
] (lam id)
]
t41 :: (ABT Term abt)
=> abt '[] ('HMeasure (('HProb ':-> 'HProb) ':-> 'HProb))
t41 = dirac $ expect (unsafeProb <$> uniform zero (prob_ 2)) lam
|
zachsully/hakaru
|
haskell/Tests/Function.hs
|
bsd-3-clause
| 959
| 0
| 17
| 243
| 350
| 194
| 156
| -1
| -1
|
module HsDeclPretty (ppContext,ppFunDeps) where
import HsDeclStruct
import HsIdentPretty()
import HsAssocPretty()
import PrettySymbols(el,rarrow)
import PrettyPrint
import PrettyUtil(ppWhere,ppContext)
import HsGuardsPretty(ppRhs)
instance (PrintableOp i,Printable e, Printable p, Printable ds,
Printable t, Printable c, Printable tp) =>
Printable (DI i e p ds t c tp) where
ppi (HsTypeDecl _ tp t) =
sep [kw "type" <+> tp <+> equals, dataNest t ]
ppi (HsNewTypeDecl _ c tp t ders) =
sep [kw "newtype" <+> (ppContext $ ppis c) <+> tp <+> equals,
dataNest $ sep [ppi t, ppDeriving ders] ]
ppi (HsDataDecl _ c tp summands ders) =
sep [kw "data" <+> (ppContext $ ppis c) <+> tp,
dataNest $
sep [sep (zipWith (<+>) (equals : repeat (kw "|")) summands),
ppDeriving ders]]
ppi (HsClassDecl _ c tp fundeps ds) =
sep [kw "class" <+> sep [ppContext $ ppis c, ppi tp, ppFunDeps fundeps],
nest 2 $ ppWhere (ppis ds)]
ppi (HsInstDecl _ optn c tp ds) =
sep [kw "instance" <+> sep [ppContext $ ppis c, ppi tp],
nest 2 $ ppWhere (ppis ds)]
ppi (HsDefaultDecl _ t) = kw "default" <+> ppiFTuple t
ppi (HsTypeSig _ ns c t) =
-- If they are printed vertically, every name except the first one
-- must be indented...
sep [hcat (punctuate comma (map wrap ns)),
letNest $ el <+> ppContext (ppis c) <+> t]
ppi (HsFunBind _ ms) = vcat ms
ppi (HsPatBind _ p rhs ds) =
sep [wrap p, nest 2 $ sep [ppRhs equals rhs, ppWhere (ppis ds)]]
ppi (HsInfixDecl _ fixity ops) =
fixity <+> (fsep $ punctuate comma $ map ppiOp ops)
ppi (HsPrimitiveTypeDecl _ ctx tp) =
kw "data" <+> ppContext (ppis ctx) <+> tp
ppi (HsPrimitiveBind _ nm tp) =
kw "foreign" <+> kw "import" <+> wrap nm <+> el <+> tp
wrap = ppi
instance (Printable i,Printable e, Printable p, Printable ds) =>
Printable (HsMatchI i e p ds) where
ppi (HsMatch _ f ps rhs ds)
= sep [wrap f <+> fsep (map wrap ps),
nest 2 $ sep [ppRhs equals rhs, ppWhere (ppis ds)]]
wrap = ppi
instance (PrintableOp i,Printable t,Printable c)
=> Printable (HsConDeclI i t c) where
ppi (HsConDecl _ is c n [t1,t2]) | isOp n = ppiBinOp t1 (con (ppiOp n)) t2
ppi (HsConDecl _ is c n ts) = con (wrap n) <+> (fsep $ map wrap ts)
ppi (HsRecDecl _ is c n fs)
= con (wrap n) <+> (braces $ ppiFSeq $ map ppField fs)
where ppField (ns, t) = wrapFSeq ns <+> el <+> t
wrap = ppi
instance Printable t => Printable (HsBangType t) where
ppi (HsBangedType t) = kw '!' <> wrap t
ppi (HsUnBangedType t) = ppi t
wrap (HsBangedType t) = kw '!' <> wrap t
wrap (HsUnBangedType t) = wrap t
-- Pretty prints deriving clauses
--ppDeriving :: [HsName] -> Doc
ppDeriving [] = empty
ppDeriving [i] = kw "deriving" <+> tcon i
ppDeriving is = kw "deriving" <+> ppiFTuple (map tcon is)
ppFunDeps [] = empty
ppFunDeps fs = kw '|' <+> ppiFSeq (map ppFunDep fs)
ppFunDep (ts1,ts2) = fsep ts1<>rarrow<>fsep ts2
|
forste/haReFork
|
tools/base/AST/HsDeclPretty.hs
|
bsd-3-clause
| 3,241
| 24
| 19
| 971
| 1,375
| 686
| 689
| 66
| 1
|
-- | Internal types to the library.
module Stack.Types.Internal where
import Control.Concurrent.MVar
import Control.Monad.Logger (LogLevel)
import Data.Text (Text)
import Network.HTTP.Client.Conduit (Manager,HasHttpManager(..))
import Stack.Types.Config
-- | Monadic environment.
data Env config =
Env {envConfig :: !config
,envLogLevel :: !LogLevel
,envTerminal :: !Bool
,envReExec :: !Bool
,envManager :: !Manager
,envSticky :: !Sticky
,envSupportsUnicode :: !Bool}
instance HasStackRoot config => HasStackRoot (Env config) where
getStackRoot = getStackRoot . envConfig
instance HasPlatform config => HasPlatform (Env config) where
getPlatform = getPlatform . envConfig
instance HasGHCVariant config => HasGHCVariant (Env config) where
getGHCVariant = getGHCVariant . envConfig
instance HasConfig config => HasConfig (Env config) where
getConfig = getConfig . envConfig
instance HasBuildConfig config => HasBuildConfig (Env config) where
getBuildConfig = getBuildConfig . envConfig
instance HasEnvConfig config => HasEnvConfig (Env config) where
getEnvConfig = getEnvConfig . envConfig
instance HasHttpManager (Env config) where
getHttpManager = envManager
class HasLogLevel r where
getLogLevel :: r -> LogLevel
instance HasLogLevel (Env config) where
getLogLevel = envLogLevel
instance HasLogLevel LogLevel where
getLogLevel = id
class HasTerminal r where
getTerminal :: r -> Bool
instance HasTerminal (Env config) where
getTerminal = envTerminal
class HasReExec r where
getReExec :: r -> Bool
instance HasReExec (Env config) where
getReExec = envReExec
class HasSupportsUnicode r where
getSupportsUnicode :: r -> Bool
instance HasSupportsUnicode (Env config) where
getSupportsUnicode = envSupportsUnicode
newtype Sticky = Sticky
{ unSticky :: Maybe (MVar (Maybe Text))
}
class HasSticky r where
getSticky :: r -> Sticky
instance HasSticky (Env config) where
getSticky = envSticky
|
mathhun/stack
|
src/Stack/Types/Internal.hs
|
bsd-3-clause
| 1,997
| 0
| 11
| 356
| 545
| 293
| 252
| 66
| 0
|
import Module (message)
main = putStrLn $ "Main.hs: " ++ message
|
mydaum/cabal
|
cabal-testsuite/PackageTests/BuildTargets/UseLocalPackageForSetup/pkg/Main.hs
|
bsd-3-clause
| 66
| 1
| 6
| 12
| 25
| 12
| 13
| 2
| 1
|
-- | Miscellaneous utiliy functions.
--
{-# LANGUAGE DeriveDataTypeable, ScopedTypeVariables, BangPatterns #-}
module Dfterm3.Util
( newFinalizableIORef
, newFinalizableFinRef
, finalizeFinRef
, touchFinRef
, FinRef()
, safeFromIntegral
, forkDyingIO
, forkExceptionTaggedIO
, exceptionTaggedIO
, whenJust
, whenJustM )
where
import Data.Typeable ( Typeable )
import Data.Foldable ( forM_ )
import Control.Monad ( void, unless )
import Data.IORef
import Control.Concurrent
import Control.Exception
import System.IO
data FinRef = FinRef (IORef ()) (IORef Bool) (IO ())
deriving ( Typeable )
instance Eq FinRef where
(FinRef ref _ _) == (FinRef ref2 _ _) = ref == ref2
-- | Creates an IORef with a finalizer.
newFinalizableIORef :: a -> IO () -> IO (IORef a)
newFinalizableIORef value finalizer = do
ref <- newIORef value
void $ mkWeakIORef ref finalizer
return ref
-- | Creates a `FinRef`. This is similar to `newFinalizableIORef` but the
-- handle is a `FinRef` instead.
newFinalizableFinRef :: IO () -> IO FinRef
newFinalizableFinRef finalizer = do
ref <- newIORef ()
bool_ref <- newIORef False
void $ mkWeakIORef ref $ do
dont_finalize <- atomicModifyIORef' bool_ref $ \old -> ( True, old )
unless dont_finalize finalizer
return $ FinRef ref bool_ref finalizer
-- | Runs a finalizer a `FinRef` immediately. The finalizer will not be run
-- again later.
--
-- If the finalizer was already run once before, this will not run it again.
finalizeFinRef :: FinRef -> IO ()
finalizeFinRef (FinRef _ bool_ref finalizer) = do
dont_finalize <- atomicModifyIORef' bool_ref $ \old -> ( True, old )
unless dont_finalize finalizer
-- | Almost the same as `fromIntegral` but raises a user error if the source
-- integer cannot be represented in the target type.
--
-- It is only almost the same because it can only convert integral types.
safeFromIntegral :: forall a b. (Num a, Integral a, Num b, Integral b) =>
a -> b
safeFromIntegral from
| from /= (fromIntegral result :: a) = error "Invalid coercion."
| otherwise = result
where
result = fromIntegral from :: b
{-# INLINE safeFromIntegral #-}
touchFinRef :: FinRef -> IO ()
touchFinRef (FinRef !_ !_ !_) = return ()
{-# NOINLINE touchFinRef #-}
-- | The same as `forkIO` but if an uncaught exception is thrown, it tags it
-- with the given string.
forkExceptionTaggedIO :: String -> IO () -> IO ThreadId
forkExceptionTaggedIO tag action =
forkIO $ exceptionTaggedIO tag action
-- | Similar to `forkExceptionTaggedIO` but does not fork a thread.
--
-- This catches all exceptions so you probably only want to use it at top-level
-- of a thread where those exceptions would not be caught anyway.
exceptionTaggedIO :: String -> IO () -> IO ()
exceptionTaggedIO tag action =
catch action $ \e ->
hPutStrLn stderr $ "[" ++ tag ++ "] " ++ show (e :: SomeException)
-- | Launches a thread that will be killed when the given action finishes.
forkDyingIO :: IO () -- ^ Computation to run in thread.
-> IO a -- ^ Computation to run after forking.
-> IO a
forkDyingIO thread_action action = mask $ \restore -> do
tid <- forkIOWithUnmask $ \unmask -> unmask thread_action
finally (restore action) (killThread tid)
whenJust :: Monad m => Maybe a -> (a -> m ()) -> m ()
whenJust Nothing _ = return ()
whenJust (Just x) action = action x
whenJustM :: Monad m => m (Maybe a) -> (a -> m ()) -> m ()
whenJustM maybe_action action = do
result <- maybe_action
forM_ result action
|
Noeda/dfterm3
|
src/Dfterm3/Util.hs
|
isc
| 3,642
| 0
| 13
| 817
| 919
| 467
| 452
| 74
| 1
|
{-# LANGUAGE ForeignFunctionInterface #-}
module AGLGUI.Raw
( WVPtr
, JSValPtr
, JSArrPtr
, Callback
, FunPtr
, aglguiInit
, aglguiQuit
, aglguiUpdate
, aglguiApiReg
, aglguiMakeWebView
, aglguiLoadURL
, aglguiTexture
, mkCallback
, freeCallback
, aglguiInjectMouseMove
, aglguiInjectMouseDown
, aglguiInjectMouseUp
, aglguiJSValueIsBool
, aglguiJSValueIsNumber
, aglguiJSValueIsString
, aglguiJSValueIsArray
, aglguiJSValueIsObject
, aglguiJSValueIsNull
, aglguiJSValueToBool
, aglguiJSValueToDouble
, aglguiJSValueToString
, aglguiJSValueStringLength
, aglguiJSArrayLength
, aglguiJSArrayAt
) where
import Data.Word
import Foreign.C
import Foreign.Ptr
type WVPtr = Ptr ()
type JSValPtr = Ptr ()
type JSArrPtr = Ptr ()
type Callback = JSArrPtr -> IO JSValPtr
-- | Callbacks created by mkCallback should be released using freeCallback when no longer required.
foreign import ccall "wrapper"
mkCallback :: Callback -> IO (FunPtr Callback)
freeCallback :: FunPtr Callback -> IO ()
freeCallback = freeHaskellFunPtr
foreign import ccall "aglguiInit"
aglguiInit :: CString -> IO ()
foreign import ccall "aglguiQuit"
aglguiQuit :: IO ()
foreign import ccall "aglguiUpdate"
aglguiUpdate :: IO ()
foreign import ccall "aglguiApiReg"
aglguiApiReg :: CString -> FunPtr Callback -> CChar -> IO ()
foreign import ccall "aglguiMakeWebView"
aglguiMakeWebView :: CInt -> CInt -> IO WVPtr
foreign import ccall "aglguiLoadURL"
aglguiLoadURL :: WVPtr -> CString -> IO ()
foreign import ccall "aglguiTexture"
aglguiTexture :: WVPtr -> IO CUInt
foreign import ccall "aglguiInjectMouseMove"
aglguiInjectMouseMove :: WVPtr -> CInt -> CInt -> IO ()
foreign import ccall "aglguiInjectMouseDown"
aglguiInjectMouseDown :: WVPtr -> CInt -> IO ()
foreign import ccall "aglguiInjectMouseUp"
aglguiInjectMouseUp :: WVPtr -> CInt -> IO ()
foreign import ccall "aglguiJSValueIsBool"
aglguiJSValueIsBool :: JSValPtr -> IO CChar
foreign import ccall "aglguiJSValueIsNumber"
aglguiJSValueIsNumber :: JSValPtr -> IO CChar
foreign import ccall "aglguiJSValueIsString"
aglguiJSValueIsString :: JSValPtr -> IO CChar
foreign import ccall "aglguiJSValueIsArray"
aglguiJSValueIsArray :: JSValPtr -> IO CChar
foreign import ccall "aglguiJSValueIsObject"
aglguiJSValueIsObject :: JSValPtr -> IO CChar
foreign import ccall "aglguiJSValueIsNull"
aglguiJSValueIsNull :: JSValPtr -> IO CChar
foreign import ccall "aglguiJSValueToBool"
aglguiJSValueToBool :: JSValPtr -> IO CChar
foreign import ccall "aglguiJSValueToDouble"
aglguiJSValueToDouble :: JSValPtr -> IO CDouble
foreign import ccall "aglguiJSValueToString"
aglguiJSValueToString :: JSValPtr -> IO (Ptr Word16)
foreign import ccall "aglguiJSValueStringLength"
aglguiJSValueStringLength :: JSValPtr -> IO CUInt
foreign import ccall "aglguiJSArrayLength"
aglguiJSArrayLength :: JSArrPtr -> IO CUInt
foreign import ccall "aglguiJSArrayAt"
aglguiJSArrayAt :: JSArrPtr -> CUInt -> IO JSValPtr
|
tcsavage/hsaglgui
|
src/AGLGUI/Raw.hs
|
mit
| 3,019
| 0
| 10
| 486
| 676
| 369
| 307
| 86
| 1
|
import Data.List
import qualified Data.Map as M
import Picologic.AST
import Picologic.Pretty
import Picologic.Solver
import Picologic.Tseitin
import System.Exit (exitFailure)
import System.IO.Unsafe (unsafePerformIO)
import Test.QuickCheck
instance Arbitrary Expr where
arbitrary = sized $ \n ->
tree (round $ sqrt $ fromIntegral n :: Int)
where
tree 0 = elements $ map (Var . Ident) (concat $ replicate 3 ["a", "b", "c", "d"]) ++ [Top, Bottom]
tree n =
oneof
[ do
a <- tree (pred n)
return $ Neg a,
do
l <- arbitrary
let n2 = l `mod` n
a <- tree n2
b <- tree (n - n2)
con <- elements [Conj, Disj, Implies, Iff]
return $ con a b
]
shrink (Var _) = []
shrink (Neg (Neg x)) = [x, Neg x] ++ map Neg (shrink x)
shrink (Neg x) = [x] ++ map Neg (shrink x)
shrink (Conj a b) =
[a, b]
++ map (Conj a) (shrink b)
++ map (\aa -> Conj aa b) (shrink a)
shrink (Disj a b) =
[a, b]
++ map (Disj a) (shrink b)
++ map (\aa -> Disj aa b) (shrink a)
shrink (Implies a b) =
[a, b]
++ map (Implies a) (shrink b)
++ map (\aa -> Implies aa b) (shrink a)
shrink (Iff a b) =
[a, b]
++ map (Iff a) (shrink b)
++ map (\aa -> Iff aa b) (shrink a)
shrink Top = []
shrink Bottom = []
envl =
[ (Ident "a", True),
(Ident "b", True),
(Ident "c", False),
(Ident "d", False)
]
env = M.fromList envl
test_nnf :: Expr -> Bool
test_nnf e = eval env e == eval env (nnf e)
test_cnf :: Expr -> Bool
test_cnf e = eval env e == eval env (cnf e)
test_tseitin :: Expr -> Bool
test_tseitin e = unsafePerformIO test
where
test = do
let vars = variables e
let ts = tseitinCNF e
-- putStrLn "\nexpr"
-- print $ ppExprLisp e
-- putStrLn "tseitin"
-- print $ ppExprLisp ts
-- putStrLn "tseitin clauses"
-- mapM_ print $ clausesExpr ts
let ce = cnf e
as <- solveCNF ce
bs0 <- solveCNF ts
let bs = dropTseitinVarsInSolutions bs0
let as1 = addVarsToSolutions vars as
let bs1 = addVarsToSolutions vars bs
--print ("as", as)
--print ("bs", bs)
return $ normalize as1 == normalize bs1
normalize (Solutions ssv) = sort $ map sort ssv
test_partEval :: Expr -> Bool
test_partEval e =
if eval env e
then elast == Top
else elast == Bottom
where
envs = map (\(i, v) -> M.singleton i v) envl
elast = last $ scanl (flip partEval) e envs
qc = verboseCheckWith (stdArgs {maxSuccess = 2000})
-- how to make an error fail a 'cabal test'?
qcwf p =
verboseCheckWith
(stdArgs {maxSuccess = 1000})
(whenFail exitFailure p)
main :: IO ()
main = do
putStrLn "nnf"
qc test_nnf
putStrLn "cnf"
qc test_cnf
putStrLn "tseitin"
qc test_tseitin
putStrLn "partEval"
qc test_partEval
|
sdiehl/picologic
|
tests/Test.hs
|
mit
| 2,943
| 0
| 15
| 922
| 1,200
| 606
| 594
| 91
| 2
|
module Prelude.CompatSpec (main, spec) where
import Test.Hspec
import Prelude ()
import Prelude.Compat
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "($!)" $ do
it "is infixr 0" $ do -- #54
(succ $! succ $! 0) `shouldBe` (2 :: Int)
(succ $! 2 *** 2) `shouldBe` (5 :: Int)
infixr 1 ***
(***) :: Int -> Int -> Int
(***) = (*)
|
haskell-compat/base-compat
|
base-compat-batteries/test/Prelude/CompatSpec.hs
|
mit
| 398
| 0
| 16
| 125
| 160
| 92
| 68
| 15
| 1
|
data People = Person String Int
jogi :: People
jogi = Person "Joachim Löw" 50
isAdult :: People -> Bool
isAdult (Person name age) = (age >= 18)
|
MartinThoma/LaTeX-examples
|
documents/Programmierparadigmen/scripts/haskell/algebraic-datatypes.hs
|
mit
| 145
| 0
| 7
| 28
| 59
| 31
| 28
| 5
| 1
|
module Test.Vision.Image.Storage.PGM.Internal (
testInternal,
pgmFile, pgm
) where
import Vision.Image.Storage.PGM.Internal as I
import Test.Hspec
import Test.QuickCheck
import Data.Functor ((<$>))
import Data.Monoid (mconcat)
import Data.Either (isRight)
import Data.Binary (Word8)
import Data.List (intersperse)
import Data.Convertible (convert)
import qualified Data.Vector.Storable as V
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString as B
-- Generators
sepBy gen xs = sequence $ intersperse gen $ return <$> xs
space = elements [" ", "\t", "\n", "\r", "\f"]
spaces = mconcat <$> listOf1 space
pixels :: Int -> Int -> Int -> Gen [Word8]
pixels w h m = vectorOf (w * h) $ elements [0..(convert m)]
number :: Gen Int
number = getNonNegative <$> arbitrary
config :: Gen (Int, Int, Int, [Word8])
config = do
width <- number
height <- number
maxVal <- return 255
px <- pixels width height maxVal
return (width, height, maxVal, px)
pgm :: Gen PGM
pgm = pgm' <$> config
pgm' :: (Int, Int, Int, [Word8]) -> PGM
pgm' (width, height, maxVal, px) = PGM width height maxVal $ V.fromList px
pgmFile = pgmFile' <$> config
pgmFile' (width, height, maxVal, px) = do
let headerItems = "P5" : (show <$> [width, height, maxVal])
header <- BC.pack . mconcat <$> sepBy spaces headerItems
space' <- BC.pack <$> space
let body = B.pack px
return $ mconcat [header, space', body]
pgmAndPgmFile :: Gen (PGM, B.ByteString)
pgmAndPgmFile = do
config' <- config
let pgm'' = pgm' config'
file' <- pgmFile' config'
return (pgm'', file')
-- Tests
testInternal = describe "Vision.Image.Storage.PGM.Internal" $ do
it "should have the property parse . format == Right id" $ property $
forAll pgm (\pgm' -> (I.parse . I.format) pgm' `shouldBe` Right pgm')
it "parsing file should produce the same as the pre-genned parsed equivalent" $ property $
forAll pgmAndPgmFile (\(pgm', pgmFile') -> I.parse pgmFile' `shouldBe` Right pgm')
|
hughfdjackson/friday-pgm
|
test/Test/Vision/Image/Storage/PGM/Internal.hs
|
mit
| 1,988
| 0
| 16
| 358
| 729
| 398
| 331
| 51
| 1
|
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
{-# LANGUAGE TemplateHaskell, QuasiQuotes #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE CPP #-}
{- |
Module : Snap.Routes
Copyright : (c) Anupam Jain 2016
License : MIT (see the file LICENSE)
Maintainer : ajnsit@gmail.com
Stability : experimental
Portability : non-portable (uses ghc extensions)
This package provides typesafe URLs for Snap applications.
-}
module Snap.Routes
( module Snap.Routes
, module Routes.Class
, module Routes.Parse
, module Snap
)
where
-- Snap
import Snap
-- Routes
import Routes.Class (Route, RenderRoute(..), ParseRoute(..), RouteAttrs(..))
import Routes.Parse (parseRoutes, parseRoutesNoCheck, parseRoutesFile, parseRoutesFileNoCheck, parseType)
import Routes.TH (mkRenderRouteInstance, mkParseRouteInstance, mkRouteAttrsInstance, mkDispatchClause, ResourceTree(..), MkDispatchSettings(..), defaultGetHandler)
-- Text and Bytestring
import Data.ByteString (ByteString)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8, decodeUtf8)
import Blaze.ByteString.Builder (toByteString)
import Network.HTTP.Types (encodePath, queryTextToQuery, decodePath, queryToQueryText, Query)
-- TH
import Language.Haskell.TH.Syntax
-- Convenience
import Control.Arrow (second)
import Data.Maybe (fromMaybe)
-- Abstract request data needed for routing
data RequestData master = RequestData
{ currentRoute :: Maybe (Route master)
, requestPathInfo :: [Text]
, requestMethod :: ByteString
}
-- The type of our response handler
type ResponseHandler m = MonadSnap m => m ()
-- The type of our application
type App m sub = RequestData sub -> ResponseHandler m
-- Environment data
data Env sub master = Env
{ envMaster :: master
, envSub :: sub
, envToMaster :: Route sub -> Route master
}
-- | A `Handler` generates an App from the master datatype
type RouteHandler sub = forall master m. RenderRoute master => HandlerS m sub master
type SubrouteHandler sub master = forall m. HandlerS m sub master
type HandlerS m sub master = Env sub master -> App m sub
-- | Generates everything except actual dispatch
mkRouteData :: String -> [ResourceTree String] -> Q [Dec]
mkRouteData typName routes = do
let typ = parseType typName
let rname = mkName $ "_resources" ++ typName
let resourceTrees = map (fmap parseType) routes
eres <- lift routes
let resourcesDec =
[ SigD rname $ ListT `AppT` (ConT ''ResourceTree `AppT` ConT ''String)
, FunD rname [Clause [] (NormalB eres) []]
]
rinst <- mkRenderRouteInstance typ resourceTrees
pinst <- mkParseRouteInstance typ resourceTrees
ainst <- mkRouteAttrsInstance typ resourceTrees
return $ concat [ [ainst]
, [pinst]
, resourcesDec
, rinst
]
-- | Generates a 'Routable' instance and dispatch function
mkRouteDispatch :: String -> [ResourceTree String] -> Q [Dec]
mkRouteDispatch typName routes = do
let typ = parseType typName
m <- newName "m"
disp <- mkRouteDispatchClause routes
#if MIN_VERSION_template_haskell(2,11,0)
let inst = InstanceD Nothing
#else
let inst = InstanceD
#endif
return [inst []
(ConT ''Routable `AppT` VarT m `AppT` typ `AppT` typ)
[FunD (mkName "dispatcher") [disp]]]
-- | Same as mkRouteDispatch but for subsites
mkRouteSubDispatch :: String -> String -> [ResourceTree a] -> Q [Dec]
mkRouteSubDispatch typName constraint routes = do
let typ = parseType typName
disp <- mkRouteDispatchClause routes
master <- newName "master"
m <- newName "m"
-- We don't simply use parseType for GHC 7.8 (TH-2.9) compatibility
-- ParseType only works on Type (not Pred)
-- In GHC 7.10 (TH-2.10) onwards, Pred is aliased to Type
className <- lookupTypeName constraint
-- Check if this is a classname or a type
let contract = maybe (error $ "Unknown typeclass " ++ show constraint) (getContract master) className
#if MIN_VERSION_template_haskell(2,11,0)
let inst = InstanceD Nothing
#else
let inst = InstanceD
#endif
return [inst [contract]
(ConT ''Routable `AppT` VarT m `AppT` typ `AppT` VarT master)
[FunD (mkName "dispatcher") [disp]]]
where
getContract master className =
#if MIN_VERSION_template_haskell(2,10,0)
ConT className `AppT` VarT master
#else
ClassP className [VarT master]
#endif
-- Helper that creates the dispatch clause
mkRouteDispatchClause :: [ResourceTree a] -> Q Clause
mkRouteDispatchClause =
mkDispatchClause MkDispatchSettings
{ mdsRunHandler = [| runHandler |]
, mdsSubDispatcher = [| subDispatcher |]
, mdsGetPathInfo = [| requestPathInfo |]
, mdsMethod = [| requestMethod |]
, mdsSetPathInfo = [| setPathInfo |]
, mds404 = [| app404 |]
, mds405 = [| app405 |]
, mdsGetHandler = defaultGetHandler
, mdsUnwrapper = return
}
-- | Generates all the things needed for efficient routing.
-- Including your application's `Route` datatype,
-- `RenderRoute`, `ParseRoute`, `RouteAttrs`, and `Routable` instances.
-- Use this for everything except subsites
mkRoute :: String -> [ResourceTree String] -> Q [Dec]
mkRoute typName routes = do
dat <- mkRouteData typName routes
disp <- mkRouteDispatch typName routes
return (disp++dat)
-- TODO: Also allow using the master datatype name directly, instead of a constraint class
-- | Same as mkRoute, but for subsites
mkRouteSub :: String -> String -> [ResourceTree String] -> Q [Dec]
mkRouteSub typName constraint routes = do
dat <- mkRouteData typName routes
disp <- mkRouteSubDispatch typName constraint routes
return (disp++dat)
-- | A `Routable` instance can be used in dispatching.
-- An appropriate instance for your site datatype is
-- automatically generated by `mkRoute`.
class Routable m sub master where
dispatcher :: HandlerS m sub master
-- | Generates the application middleware from a `Routable` master datatype
routeDispatch :: Routable m master master => Request -> master -> ResponseHandler m
routeDispatch req = customRouteDispatch dispatcher req
-- | Like routeDispatch but generates the application middleware from a custom dispatcher
customRouteDispatch :: HandlerS m master master -> Request -> master -> ResponseHandler m
-- TODO: Should this have master master instead of sub master?
-- TODO: Verify that this plays well with subsites
-- Env master master is converted to Env sub master by subDispatcher
-- Route information is filled in by runHandler
customRouteDispatch customDispatcher req master =
customDispatcher
(_masterToEnv master)
RequestData
{ currentRoute=Nothing
, requestPathInfo = parsePathInfo $ decodeUtf8 $ rqPathInfo req
, requestMethod = showMethod $ rqMethod req
}
where
-- Don't want to depend on the Show instance
showMethod :: Method -> ByteString
showMethod GET = "GET"
showMethod HEAD = "HEAD"
showMethod POST = "POST"
showMethod PUT = "PUT"
showMethod DELETE = "DELETE"
showMethod TRACE = "TRACE"
showMethod OPTIONS = "OPTIONS"
showMethod CONNECT = "CONNECT"
showMethod PATCH = "PATCH"
showMethod (Method meth) = meth
-- | Render a `Route` and Query parameters to Text
showRouteQuery :: RenderRoute master => Route master -> [(Text,Text)] -> Text
showRouteQuery r q = uncurry _encodePathInfo $ second (map (second Just) . (++ q)) $ renderRoute r
-- | Renders a `Route` as Text
showRoute :: RenderRoute master => Route master -> Text
showRoute = uncurry _encodePathInfo . second (map $ second Just) . renderRoute
_encodePathInfo :: [Text] -> [(Text, Maybe Text)] -> Text
-- Slightly hackish: Convert "" into "/"
_encodePathInfo [] = _encodePathInfo [""]
_encodePathInfo segments = decodeUtf8 . toByteString . encodePath segments . queryTextToQuery
-- | Read a route from Text
-- Returns Nothing if Route reading failed. Just route otherwise
readRoute :: ParseRoute master => Text -> Maybe (Route master)
readRoute = parseRoute . second readQueryString . decodePath . encodeUtf8
-- | Convert a Query to the format expected by parseRoute
readQueryString :: Query -> [(Text, Text)]
readQueryString = map (second (fromMaybe "")) . queryToQueryText
-- PRIVATE
-- Slightly hacky: manually split path into components
parsePathInfo :: Text -> [Text]
-- Hacky, map "" to []
parsePathInfo "" = []
parsePathInfo other = T.splitOn "/" other
-- Set the path info in a RequestData
setPathInfo :: [Text] -> RequestData master -> RequestData master
setPathInfo p reqData = reqData { requestPathInfo = p }
-- Baked in applications that handle 404 and 405 errors
-- On no matching route, skip to next application
app404 :: HandlerS m sub master
app404 _env _rd = pass
-- On matching route, but no matching http method, skip to next application
-- This allows a later route to handle methods not implemented by the previous routes
app405 :: HandlerS m sub master
app405 _env _rd = pass
-- Run a route handler function
-- Currently all this does is populate the route into RequestData
-- But it may do more in the future
runHandler
:: HandlerS m sub master
-> Env sub master
-> Maybe (Route sub)
-> App m sub
runHandler h env rout reqdata = h env reqdata{currentRoute=rout}
-- Run a route subsite handler function
subDispatcher
:: Routable m sub master
=> (HandlerS m sub master -> Env sub master -> Maybe (Route sub) -> App m sub)
-> (master -> sub)
-> (Route sub -> Route master)
-> Env master master
-> App m master
subDispatcher _runhandler getSub toMasterRoute env reqData = dispatcher env' reqData'
where
env' = _envToSub getSub toMasterRoute env
reqData' = reqData{currentRoute=Nothing}
-- qq (k,mv) = (decodeUtf8 k, maybe "" decodeUtf8 mv)
-- req = snapReq reqData
_masterToEnv :: master -> Env master master
_masterToEnv master = Env master master id
_envToSub :: (master -> sub) -> (Route sub -> Route master) -> Env master master -> Env sub master
_envToSub getSub toMasterRoute env = Env master sub toMasterRoute
where
master = envMaster env
sub = getSub master
-- Convenience function to hook in a route
serveRoute :: (Routable m master master, MonadSnap m) => master -> m ()
serveRoute master = getRequest >>= flip routeDispatch master
|
ajnsit/snap-routes
|
src/Snap/Routes.hs
|
mit
| 10,571
| 0
| 15
| 2,170
| 2,380
| 1,281
| 1,099
| 166
| 10
|
{-
Tests for connection establishment and athorization. It is assumed
than these tests being executed with different settings in pg_hba.conf
-}
import Control.Exception (finally)
import Data.Monoid ((<>))
import Data.Foldable
import qualified Data.ByteString as B
import System.Process (callCommand)
import Test.Tasty
import Test.Tasty.HUnit
import Database.PostgreSQL.Driver.Connection
import Database.PostgreSQL.Driver.Settings
main :: IO ()
main = defaultMain $ testGroup "Postgres-wire"
[ testConnection "Connection trust" confTrust
, testConnection "Connection with password" confPassword
, testConnection "Connection with md5" confPassword
]
testConnection :: TestName -> B.ByteString -> TestTree
testConnection name confContent = testCase name $ withPghba confContent $
traverse_ connectAndClose
[ defaultSettings { settingsHost = "" }
, defaultSettings { settingsHost = "/var/run/postgresql" }
, defaultSettings { settingsHost = "localhost" }
]
where
connectAndClose settings = connect settings >>= either (error . show) close
defaultSettings = ConnectionSettings
{ settingsHost = ""
, settingsPort = 5432
, settingsDatabase = "test_connection"
, settingsUser = "test_postgres"
, settingsPassword = "password"
, settingsTls = NoTls
}
pghbaFilename :: FilePath
pghbaFilename = "/etc/postgresql/10/main/pg_hba.conf"
withPghba :: B.ByteString -> IO a -> IO a
withPghba confContent action = do
oldContent <- B.readFile pghbaFilename
B.writeFile pghbaFilename confContent
(restart >> action) `finally`
(B.writeFile pghbaFilename oldContent >> restart)
where
restart = callCommand "service postgresql restart"
makeConf :: B.ByteString -> B.ByteString
makeConf method =
"local all postgres peer\n"
<> "local all all " <> method <> "\n"
<> "host all all 127.0.0.1/32 " <> method <> "\n"
<> "host all all ::1/128 " <> method <> "\n"
confTrust :: B.ByteString
confTrust = makeConf "trust"
confPassword :: B.ByteString
confPassword = makeConf "password"
confMd5 :: B.ByteString
confMd5 = makeConf "md5"
|
postgres-haskell/postgres-wire
|
tests_connection/test.hs
|
mit
| 2,272
| 0
| 13
| 531
| 474
| 259
| 215
| 49
| 1
|
import Grammar (parseExpr)
import Data.Tree.Pretty (drawVerticalTree)
import Nodes
main :: IO ()
main =
putStrLn . drawVerticalTree . ast . parsed $ "2 + 2\n(3 + 1) + 2\n"
parsed = parseExpr
|
milankinen/cbhs
|
src/Main.hs
|
mit
| 200
| 0
| 8
| 41
| 59
| 33
| 26
| 7
| 1
|
module PrintLasm where
import Data.Char
import Data.Map hiding (map, foldr)
import Prelude hiding (lookup)
import Control.Monad.State
import Debug.Trace
import AbsLasm
data LEnv = Env
type EnvState = State LEnv
-- Printer
printLASM :: LProgram -> String
printLASM prog = render progDoc where
progDoc = evalState (prt prog) Env
type Doc = [ShowS] -> [ShowS]
render :: Doc -> String
render d = rend (map ($ "") $ d []) "" where
rend ss =
case ss of
t :ts -> showString t . rend ts
_ -> id
doc :: ShowS -> Doc
doc = (:)
concatS :: [ShowS] -> ShowS
concatS = foldr (.) id
concatD :: [Doc] -> Doc
concatD = foldr (.) id
concatEnvDoc :: [EnvState Doc] -> EnvState Doc
concatEnvDoc ed = do
ed' <- sequence ed
return $ concatD ed'
nl :: EnvState Doc
nl = prt "\n"
class Print a where
prt :: a -> EnvState Doc
prtList :: [a] -> EnvState Doc
prtList = concatEnvDoc . map prt
instance Print a => Print [a] where
prt = prtList
instance Print Char where
prt s = return $ doc (showChar s)
prtList s = return $ doc (showString s)
instance Print Int where
prt x = return $ doc (shows x)
instance Print Integer where
prt x = return $ doc (shows x)
instance Print Double where
prt x = return $ doc (shows x)
instance Print Ident where
prt (Ident s) = return $ doc (showString s)
instance Print LProgram where
prt (Prog tls) = concatEnvDoc [prt "declare void @printInt(i32)\n",
prt "declare void @printDouble(double)\n",
prt "declare void @printString(i8*)\n",
prt "declare i32 @readInt()\n",
prt "declare double @readDouble()\n",
prt "declare i8* @calloc(i64, i64)\n\n",
prt tls]
instance Print LTop where
prt (Fun t i as ss) = concatEnvDoc [nl, prt "define ", prt t, prt " @", prt i,
prt "(", prt as, prt ") {\n", prt ss, prt " unreachable\n}", nl, nl]
prt (DFun t i ts) = concatEnvDoc [prt "declare ", prt t, prt " @", prt i,
prt "(", prt ts, prt ")\n"]
prt (Global (Register r) s) = concatEnvDoc [prt "@", prt r,
prt " = internal constant [", prt lenS, prt " x i8] c\"", prt s,
prt "\\00\"", nl] where lenS = length s + 1
instance Print LType where
prt TVoid = prt "void"
prt TInt = prt "i32"
prt TDbl = prt "double"
prt TBool = prt "i1"
prt (TStruct ts) = concatEnvDoc [prt "{", prt ts, prt "}"]
prt (TArray t) = concatEnvDoc [prt "[0 x ", prt t, prt "]"]
prt (TPtr t) = concatEnvDoc [prt t, prt "*"]
prtList ts = case ts of
[] -> prt ""
[x] -> prt x
x:xs -> concatEnvDoc [prt x, prt ", ", prt xs]
instance Print LArg where
prt (Arg t i) = concatEnvDoc [prt t, prt " %", prt i]
prtList as = case as of
[] -> prt ""
[x] -> prt x
x:xs -> concatEnvDoc [prt x, prt ", ", prt xs]
instance Print LValue where
prt (VInt i) = concatEnvDoc [prt "i32 ", prt i]
prt (VDbl d) = concatEnvDoc [prt "double ", prt d]
prt (VBool i) = concatEnvDoc [prt "i1 ", prt i]
prt (VString (Register r) i) = concatEnvDoc [prt "i8* getelementptr ([",
prt i, prt " x i8]* @", prt r, prt ", i32 0, i64 0)"]
instance Print Operand where
prt (Var t r) = concatEnvDoc [prt t, prt " ", prt r]
prt (Const v) = prt v
prtList os = case os of
[] -> prt ""
[x] -> prt x
x:xs -> concatEnvDoc [prt x, prt ", ", prt xs]
instance Print LBrType where
prt BEq = prt "eq"
prt BNeq = prt "ne"
prt BGt = prt "sgt"
prt BGEq = prt "sge"
prt BLt = prt "slt"
prt BLEq = prt "sle"
instance Print Register where
prt (Register s) = concatEnvDoc [prt "%", prt s]
instance Print Label where
prt (Label s) = prt s
instance Print LStm where
prt stm = case stm of
SCall r i t os -> concatEnvDoc [prt " ", prt r, prt " = call ", prt t,
prt " @", prt i, prt "(", prt os, prt ")\n"]
SVCall i os -> concatEnvDoc [prt " call void @", prt i, prt "(",
prt os, prt ")\n"]
SAdd r t o1 o2 -> case t of
TInt -> concatEnvDoc [prt " ", prt r, prt " = add ", prt t, prt " ",
prtOp' o1, prt ", ", prtOp' o2, nl]
TDbl -> concatEnvDoc [prt " ", prt r, prt " = fadd ", prt t, prt " ",
prtOp' o1, prt ", ", prtOp' o2, nl]
SSub r t o1 o2 -> case t of
TInt -> concatEnvDoc [prt " ", prt r, prt " = sub ", prt t, prt " ",
prtOp' o1, prt ", ", prtOp' o2, nl]
TDbl -> concatEnvDoc [prt " ", prt r, prt " = fsub ", prt t, prt " ",
prtOp' o1, prt ", ", prtOp' o2, nl]
SMul r t o1 o2 -> case t of
TInt -> concatEnvDoc [prt " ", prt r, prt " = mul ", prt t, prt " ",
prtOp' o1, prt ", ", prtOp' o2, nl]
TDbl -> concatEnvDoc [prt " ", prt r, prt " = fmul ", prt t, prt " ",
prtOp' o1, prt ", ", prtOp' o2, nl]
SDiv r t o1 o2 -> case t of
TInt -> concatEnvDoc [prt " ", prt r, prt " = sdiv ", prt t, prt " ",
prtOp' o1, prt ", ", prtOp' o2, nl]
TDbl -> concatEnvDoc [prt " ", prt r, prt " = fdiv ", prt t, prt " ",
prtOp' o1, prt ", ", prtOp' o2, nl]
SMod r t o1 o2 -> case t of
TInt -> concatEnvDoc [prt " ", prt r, prt " = srem ", prt t, prt " ",
prtOp' o1, prt ", ", prtOp' o2, nl]
TDbl -> concatEnvDoc [prt " ", prt r, prt " = frem ", prt t, prt " ",
prtOp' o1, prt ", ", prtOp' o2, nl]
SOr r t o1 o2 -> concatEnvDoc [prt " ", prt r, prt " = or ", prt t, prt " ",
prtOp' o1, prt ", ", prtOp' o2, nl]
SAnd r t o1 o2 -> concatEnvDoc [prt " ", prt r, prt " = and ", prt t, prt " ",
prtOp' o1, prt ", ", prtOp' o2, nl]
SXor r t o1 o2 -> concatEnvDoc [prt " ", prt r, prt " = xor ", prt t,
prt " ", prtOp' o1, prt ", ", prtOp' o2, nl]
SStore o r -> concatEnvDoc [prt " store ", prt o, prt ", ",
prt (oType o), prt "* ", prt r, nl]
SLoad r1 t r2 -> concatEnvDoc [prt " ", prt r1, prt " = load ",
prt t, prt "* ", prt r2, nl]
SAlloc r t -> concatEnvDoc [prt " ", prt r, prt " = alloca ",
prt t, nl]
SJmp l -> concatEnvDoc [prt " br label %", prt l, nl]
SBr r l1 l2 -> concatEnvDoc [prt " br i1 ", prt r, prt ", label %",
prt l1, prt ", label %", prt l2, nl]
SCmp r bt t o1 o2 -> case t of
TDbl -> concatEnvDoc [prt " ", prt r, prt " = fcmp ", prtBrD bt, prt " ",
prt t, prt " ", prtOp' o1, prt ", ", prtOp' o2, nl]
_ -> concatEnvDoc [prt " ", prt r, prt " = icmp ", prt bt, prt " ",
prt t, prt " ", prtOp' o1, prt ", ", prtOp' o2, nl]
SLabel l -> concatEnvDoc [prt l, prt ":\n"]
SCalloc r1 r2 t o1 r3 -> concatEnvDoc [prt " ", prt r1, prt " = zext ", prt o1, prt " to i64\n",
prt " ", prt r2, prt " = call i8* @calloc(", prt "i64 ", prt r1 , prt ", i64 ",
prt sz, prt ")\n", prt " ", prt r3, prt " = bitcast i8* ",
prt r2, prt " to ", prt (TPtr (TArray t)), prt"\n"]
where sz = case t of
TDbl -> "8"
TInt -> "4"
t -> error $ "[Print LStm] unsupported array type: " ++ show t
SInsStruct r1 t r2 o1 i -> concatEnvDoc [prt " ", prt r1,
prt " = insertvalue ", prt t, prt " ", prt r2, prt ", ", prt o1,
prt ", ", prt i, prt "\n"]
SExtStruct r1 t r2 i -> concatEnvDoc [prt " ", prt r1,
prt " = extractvalue ", prt t, prt " ", prt r2, prt ", ",
prt i, prt "\n"]
SGEPtr r1 t r2 os -> concatEnvDoc [prt " ", prt r1, prt " = getelementptr ",
prt t, prt " ", prt r2, prt ", ", prt os, nl]
SReturn t o -> concatEnvDoc [prt " ret ", prt o, nl]
SVReturn -> prt " ret void\n"
prtBrD :: LBrType -> EnvState Doc
prtBrD BEq = prt "oeq"
prtBrD BNeq = prt "one"
prtBrD BGt = prt "ogt"
prtBrD BGEq = prt "oge"
prtBrD BLt = prt "olt"
prtBrD BLEq = prt "sle"
prtOp' :: Operand -> EnvState Doc
prtOp' (Var _ r) = prt r
prtOp' (Const v) = case v of
VInt i -> prt i
VDbl d -> prt d
VBool b -> prt b
_ -> error $ "[prtOp'] not implemented for value: " ++ show v
oType :: Operand -> LType
oType (Var t r) = t
oType (Const v) = case v of
VInt _ -> TInt
VDbl _ -> TDbl
VBool _ -> TBool
_ -> error $ "[oType] not implemented for value: " ++ show v
|
davidsundelius/JLC
|
src/PrintLasm.hs
|
mit
| 8,821
| 0
| 15
| 3,148
| 3,805
| 1,877
| 1,928
| 197
| 4
|
{-# LANGUAGE QuasiQuotes #-}
module Data.String.InterpolateSpec (main, spec) where
import Test.Hspec
import Test.QuickCheck
import Data.String.Interpolate
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "[i|...|]" $ do
it "interpolates an expression of type Int" $ do
property $ \x y -> [i|foo #{x + y :: Int} bar|] `shouldBe` "foo " ++ show (x + y) ++ " bar"
it "interpolates an expression of type String" $ do
property $ \xs ys -> [i|foo #{xs ++ ys} bar|] `shouldBe` "foo " ++ xs ++ ys ++ " bar"
it "accepts character escapes" $ do
[i|foo \955 bar|] `shouldBe` "foo \955 bar"
it "accepts character escapes in interpolated expressions" $ do
[i|foo #{"\955" :: String} bar|] `shouldBe` "foo \955 bar"
it "dose not strip backslashes (issue #1)" $ do
[i|foo\\bar|] `shouldBe` "foo\\bar"
it "allows to prevent interpolation by escaping the hash with a backslash" $ do
[i|foo \#{23 :: Int} bar|] `shouldBe` "foo #{23 :: Int} bar"
it "does not prevent interpolation on literal backslash" $ do
[i|foo \\#{23 :: Int} bar|] `shouldBe` "foo \\23 bar"
|
beni55/interpolate
|
test/Data/String/InterpolateSpec.hs
|
mit
| 1,170
| 0
| 19
| 293
| 283
| 158
| 125
| 24
| 1
|
{-
- By Yue Wang 13.12.2014
- proj02 Given a list, find the first and last occurrences of the largest element.
- -}
firstAndLast :: (Ord a) => [a] -> (Int,Int)
firstAndLast [] = error "empty list"
firstAndLast xs = (fstMax xs, lstMax xs)
where fstMax seq@(y:ys) = if y == maximum seq then 0 else 1 + fstMax ys
lstMax seq@(y:ys) = if last seq == maximum seq then length seq - 1 else lstMax (init seq)
|
Mooophy/DMA
|
ch02/proj02.hs
|
mit
| 459
| 0
| 10
| 137
| 156
| 81
| 75
| 5
| 3
|
{-# LANGUAGE OverloadedStrings #-}
{- |
Wai middleware for request throttling.
Basic idea: on every (matching) request a counter is incremented.
If it exceeds given limit, request is blocked and error response
is sent to client. Request counter resets after defined period of
time.
The `throttle' function limits request to the underlying
application. If you wish to limit only parts of your requests
you need to do the routing yourself. For convenience,
`throttlePath' function is provided which applies throttling
only for requests with matching URL path.
-}
module Network.Wai.Middleware.Throttler
( ThrottleCache(..)
, newMemoryThrottleCache
, throttle
, throttlePath
) where
import Control.Concurrent.MVar (MVar, newMVar, takeMVar, putMVar, readMVar)
import Data.Map (Map)
import qualified Data.Map as Map (empty, insert, lookup)
import Data.Maybe (fromMaybe)
import Data.ByteString as B (ByteString, take, length)
import Data.ByteString.Char8 as B8 (pack)
import Data.Time.Clock (getCurrentTime, UTCTime, NominalDiffTime)
import Data.Time.Clock.POSIX (posixSecondsToUTCTime, utcTimeToPOSIXSeconds)
import Network.Wai (Request, Response, Middleware, rawPathInfo, responseLBS)
import Network.HTTP.Types.Status (tooManyRequests429)
-- | Cache type class. Throttle cache is used to store request counts.
-- Can store multiple counts via different keys. E.g. keys can be client
-- IP addresses or user logins.
class ThrottleCache cache where
-- | Increment count for given key and return new count value.
-- Cache should automatically reset counts to zero after a defined period.
cacheCount :: cache -- ^ cache
-> ByteString -- ^ key
-> IO Int
data MemoryThrottleCache = MemoryThrottleCache Int NominalDiffTime (MVar (Map ByteString (UTCTime, Int)))
-- | Create in-memory throttle cache.
--
-- Normally throttle cache does not need to know what the limit
-- is. But this one uses some trickery to prevent unnecessary
-- calls to slow getCurrentTime function.
newMemoryThrottleCache :: Int -- ^ limit
-> NominalDiffTime -- ^ limit renew period
-> IO MemoryThrottleCache
newMemoryThrottleCache limit period = fmap (MemoryThrottleCache limit period) $ newMVar Map.empty
instance ThrottleCache MemoryThrottleCache where
cacheCount (MemoryThrottleCache limit period v) key = do
map <- takeMVar v
(t', c') <- case Map.lookup key map of
Nothing -> do
now <- getCurrentTime
return $ (alignTime now period, 1)
Just (t, c) -> do
case c + 1 > limit of
True -> do
now <- getCurrentTime
let alignedNow = alignTime now period
case alignedNow == t of
True -> return $ (t, c + 1)
False -> return $ (alignedNow, 1)
False -> return $ (t, c + 1)
putMVar v $ Map.insert key (t', c') map
return c'
where alignTime :: UTCTime -> NominalDiffTime -> UTCTime
alignTime time period = posixSecondsToUTCTime . fromIntegral $ a - (a `mod` b)
where a = floor . utcTimeToPOSIXSeconds $ time
b = floor period
-- | Apply throttling to requests with matching URL path
throttlePath :: ThrottleCache cache
=> ByteString -- ^ URL path to match
-> cache -- ^ cache to store request counts
-> Int -- ^ request limit
-> (Request -> Maybe ByteString) -- ^ function to get cache key based on request. If Nothing is returned, request is not throttled
-> Middleware
throttlePath path cache limit getKey app req = do
case pathMatches path req of
False -> app req
True -> throttle cache limit getKey app req
where pathMatches :: ByteString -> Request -> Bool
pathMatches path request = (rawPathInfo request) == path
-- | Wai middleware that cuts requests if request rate is higher than defined level.
-- Responds with 429 if limit exceeded
throttle :: ThrottleCache cache
=> cache -- ^ cache to store request counts
-> Int -- ^ request limit
-> (Request -> Maybe ByteString) -- ^ function to get cache key based on request. If Nothing is returned, request is not throttled
-> Middleware
throttle cache limit getKey app req = do
case getKey req of
Nothing -> app req
Just key -> do
count <- cacheCount cache key
if count > limit then return throttledResponse else app req
where throttledResponse = responseLBS tooManyRequests429 [] ""
|
maximkulkin/wai-throttler
|
Network/Wai/Middleware/Throttler.hs
|
mit
| 4,815
| 0
| 24
| 1,367
| 888
| 482
| 406
| 71
| 3
|
{-# LANGUAGE BangPatterns #-}
module Galua.OpcodeInterpreter(execute) where
import Control.Exception hiding (Handler)
import Control.Monad
import Data.Foldable
import Data.IORef
import qualified Data.Vector as Vector
import qualified Data.Vector.Mutable as IOVector
import Galua.Code
import Galua.Value
import Galua.FunValue
import Galua.Overloading
import Galua.Mach
import Galua.MachUtils(luaError')
import Galua.Number
import Galua.LuaString(fromByteString)
import Galua.Util.SmallVec(SmallVec)
import qualified Galua.Util.SmallVec as SMV
-- | Attempt to load the instruction stored at the given address
-- in the currently executing function.
{-# INLINE loadInstruction #-}
loadInstruction :: LuaExecEnv -> Int {- ^ instruction counter -} -> OpCode
loadInstruction eenv i =
luaExecCode eenv `Vector.unsafeIndex` i
-- program counter offsets are checked when functions
-- are loaded in Galua.Code
kst :: Literal -> IO Value
kst k =
case k of
LNil -> return Nil
LBool b -> return (Bool b)
LNum x -> return (Number (Double x))
LInt x -> return (Number (Int x))
LStr x -> String <$> fromByteString x
-- | Compute the result of executing the opcode at the given address
-- within the current function execution environment.
{-# INLINE execute #-}
execute :: VM -> Int -> IO NextStep
execute !vm !pc =
do eenv <- case vmCurExecEnv vm of
ExecInLua lenv -> return lenv
ExecInHs {} -> interpThrow ExecuteLuaWhileInHs
ExecInC {} -> interpThrow ExecuteLuaWhileInC
let advance = jump 0
jump i = return $! Goto (pc + i + 1)
tgt =: m = do a <- m
set eenv tgt a
advance
storeIn tgt v = tgt =: return v
tabs = machMetatablesRef (vmMachineEnv vm)
binOp f tgt src1 src2 =
do x1 <- get eenv src1
x2 <- get eenv src2
f tabs (storeIn tgt) x1 x2
unOp f tgt src1 =
do x1 <- get eenv src1
f tabs (storeIn tgt) x1
relOp f invert op1 op2 =
do x1 <- get eenv op1
x2 <- get eenv op2
-- if ((RK(B) ? RK(C)) ~= A) then pc++
f tabs (\res -> jump (if res /= invert then 1 else 0)) x1 x2
case loadInstruction eenv pc of
OP_MOVE tgt src -> tgt =: get eenv src
OP_LOADK tgt src -> tgt =: kst src
OP_GETUPVAL tgt src -> tgt =: get eenv src
OP_SETUPVAL src tgt -> tgt =: get eenv src
-- SETUPVAL's argument order is different!
OP_LOADKX tgt v ->
do set eenv tgt =<< kst v
jump 1 -- skip over the extrarg
OP_LOADBOOL tgt b c ->
do set eenv tgt (Bool b)
jump (if c then 1 else 0)
OP_LOADNIL tgt count ->
do traverse_ (\r -> set eenv r Nil) (regRange tgt (count+1))
advance
OP_GETTABUP tgt src tabKey -> binOp m__index tgt src tabKey
OP_GETTABLE tgt src tabKey -> binOp m__index tgt src tabKey
OP_SETTABUP tgt key src ->
do t <- get eenv tgt
k <- get eenv key
v <- get eenv src
m__newindex tabs advance t k v
OP_SETTABLE tgt key src ->
do t <- get eenv tgt
k <- get eenv key
v <- get eenv src
m__newindex tabs advance t k v
OP_NEWTABLE tgt arraySize hashSize ->
tgt =: (Table <$> machNewTable vm arraySize hashSize)
OP_SELF tgt src key ->
do t <- get eenv src
k <- get eenv key
let after v = do set eenv tgt v
set eenv (plusReg tgt 1) t
advance
m__index tabs after t k
OP_ADD tgt op1 op2 -> binOp m__add tgt op1 op2
OP_SUB tgt op1 op2 -> binOp m__sub tgt op1 op2
OP_MUL tgt op1 op2 -> binOp m__mul tgt op1 op2
OP_MOD tgt op1 op2 -> binOp m__mod tgt op1 op2
OP_POW tgt op1 op2 -> binOp m__pow tgt op1 op2
OP_DIV tgt op1 op2 -> binOp m__div tgt op1 op2
OP_IDIV tgt op1 op2 -> binOp m__idiv tgt op1 op2
OP_BAND tgt op1 op2 -> binOp m__band tgt op1 op2
OP_BOR tgt op1 op2 -> binOp m__bor tgt op1 op2
OP_BXOR tgt op1 op2 -> binOp m__bxor tgt op1 op2
OP_SHL tgt op1 op2 -> binOp m__shl tgt op1 op2
OP_SHR tgt op1 op2 -> binOp m__shr tgt op1 op2
OP_UNM tgt op1 -> unOp m__unm tgt op1
OP_BNOT tgt op1 -> unOp m__bnot tgt op1
OP_LEN tgt op1 -> unOp m__len tgt op1
OP_NOT tgt op1 -> tgt =: (Bool . not . valueBool <$> get eenv op1)
OP_CONCAT tgt start end ->
do xs <- getRegsFromTo eenv start end
m__concat tabs (storeIn tgt) xs
OP_JMP mbCloseReg jmp ->
do traverse_ (closeStack eenv) mbCloseReg
jump jmp
OP_EQ invert op1 op2 -> relOp m__eq invert op1 op2
OP_LT invert op1 op2 -> relOp m__lt invert op1 op2
OP_LE invert op1 op2 -> relOp m__le invert op1 op2
OP_TEST ra c ->
do a <- get eenv ra
jump (if valueBool a == c then 0 else 1)
OP_TESTSET ra rb c ->
do b <- get eenv rb
if valueBool b == c
then do set eenv ra b
advance
else jump 1
OP_CALL a b c ->
do u <- get eenv a
args <- getCallArguments eenv (plusReg a 1) b
let after result = do setCallResults eenv a c result
advance
m__call tabs after u args
OP_TAILCALL a b _c ->
do u <- get eenv a
args <- getCallArguments eenv (plusReg a 1) b
let after (f,as) = return $! FunTailcall f as
resolveFunction tabs after u args
OP_RETURN a c -> do vs <- getCallArguments eenv a c
return $! FunReturn vs
OP_FORLOOP a sBx ->
get eenv a >>= \v1 ->
get eenv (plusReg a 1) >>= \v2 ->
get eenv (plusReg a 2) >>= \v3 ->
forloopAsNumber "initial" v1 $ \initial ->
forloopAsNumber "limit" v2 $ \limit ->
forloopAsNumber "step" v3 $ \step ->
let next = initial + step
cond | 0 < step = next <= limit
| otherwise = limit <= next
in if cond
then do set eenv a (Number next)
set eenv (plusReg a 3) (Number next)
jump sBx
else advance
OP_FORPREP a jmp ->
get eenv a >>= \v1 ->
get eenv (plusReg a 1) >>= \v2 ->
get eenv (plusReg a 2) >>= \v3 ->
forloopAsNumber "initial" v1 $ \initial ->
forloopAsNumber "limit" v2 $ \limit ->
forloopAsNumber "step" v3 $ \step ->
do set eenv a (Number (initial - step))
set eenv (plusReg a 1) (Number limit)
-- save back the Number form
set eenv (plusReg a 2) (Number step)
-- save back the Number form
jump jmp
OP_TFORCALL a c ->
do f <- get eenv a
a1 <- get eenv (plusReg a 1)
a2 <- get eenv (plusReg a 2)
let after result =
do setCallResults eenv (plusReg a 3) (CountInt c) result
advance
m__call tabs after f (SMV.vec2 a1 a2)
OP_TFORLOOP a sBx ->
do v <- get eenv (plusReg a 1)
if v == Nil
then advance
else do set eenv a v
jump sBx
OP_SETLIST a b offset skip ->
do tab' <- get eenv a
tab <- case tab' of
Table tab -> return tab
_ -> interpThrow SetListNeedsTable
let setTab i x = setTableRaw tab (Number (Int (offset+i))) x
case b of
CountInt count ->
forM_ [1..count] $ \i ->
setTab i =<< get eenv (plusReg a i)
CountTop ->
do vrs <- readIORef (luaExecVarress eenv)
case vrs of
NoVarResults -> interpThrow MissingVarResults
VarResults c vs ->
do let count = regDiff a c - 1
forM_ [1..count] $ \i ->
setTab i =<< get eenv (plusReg a i)
SMV.iForM_ vs $ \i v ->
setTab (count+1+i) v
writeIORef (luaExecVarress eenv) NoVarResults
jump skip
OP_CLOSURE tgt ix cloFunc ->
do let ups = funcUpvalues cloFunc
closureUpvals <- IOVector.new (Vector.length ups)
forM_ (Vector.indexed ups) $ \(i,e) ->
IOVector.unsafeWrite closureUpvals i =<< getLValue eenv e
let fid = luaExecFID eenv
f = luaFunction (subFun fid ix) cloFunc
tgt =: (Closure <$> machNewClosure vm f closureUpvals)
OP_VARARG a b ->
do let varargs = luaExecVarargs eenv
setCallResults eenv a b . SMV.fromList =<< readIORef varargs
advance
OP_EXTRAARG{} -> interpThrow UnexpectedExtraArg
-- | Get a list of the `count` values stored from `start`.
{-# INLINE getCallArguments #-}
getCallArguments ::
LuaExecEnv -> Reg {- ^ start -} -> Count {- ^ count -} -> IO (SmallVec Value)
getCallArguments eenv a b =
case b of
CountInt x -> getRegsFromLen eenv a x
CountTop ->
do vrs <- readIORef (luaExecVarress eenv)
case vrs of
NoVarResults -> interpThrow MissingVarResults
VarResults c vs
| a < c ->
do xs <- getRegsFromTo eenv a (plusReg c (-1))
writeIORef (luaExecVarress eenv) NoVarResults
return (xs SMV.++ vs)
| otherwise ->
do writeIORef (luaExecVarress eenv) NoVarResults
return vs
-- | Stores a list of results into a given register range.
-- When expected is 'CountTop', values are stored up to TOP
{-# INLINE setCallResults #-}
setCallResults ::
LuaExecEnv ->
Reg {- ^ starting register -} ->
Count {- ^ results expected -} ->
SmallVec Value {- ^ results -} ->
IO ()
setCallResults eenv a b xs =
case b of
CountInt count ->
SMV.ipadForM_ xs count Nil $ \i v ->
set eenv (plusReg a i) v
CountTop ->
do writeIORef (luaExecVarress eenv) $! VarResults a xs
let end = Reg (IOVector.length (luaExecRegs eenv) - 1)
for_ (regFromTo a end) $ \(Reg i) ->
IOVector.unsafeWrite (luaExecRegs eenv) i =<< newIORef Nil
-- | Allocate fresh references for all registers from the `start` to the
-- `TOP` of the stack
{-# INLINE closeStack #-}
closeStack :: LuaExecEnv -> Reg {- ^ start -} -> IO ()
closeStack eenv start =
do let regs = luaExecRegs eenv
vrs <- readIORef (luaExecVarress eenv)
let end = case vrs of
NoVarResults -> Reg (IOVector.length regs - 1)
VarResults b _ -> plusReg b (-1)
for_ (regFromTo start end) $ \(Reg i) ->
IOVector.unsafeWrite regs i =<< newIORef Nil
-- | Interpret a value as an input to a for-loop. If the value
-- is not a number an error is raised using the given name.
forloopAsNumber :: String {- ^ argument name -} -> Value ->
(Number -> IO NextStep) -> IO NextStep
forloopAsNumber label v cont =
case valueNumber v of
Just n -> cont n
Nothing -> luaError' ("'for' " ++ label ++ " must be a number")
{-# INLINE forloopAsNumber #-}
------------------------------------------------------------------------
-- Reference accessors
------------------------------------------------------------------------
-- | Class for types that are indexes to references
class LValue a where
getLValue :: LuaExecEnv -> a -> IO (IORef Value)
instance LValue UpIx where
getLValue eenv (UpIx i) =
do let upvals = luaExecUpvals eenv
IOVector.unsafeRead upvals i
{-# INLINE getLValue #-}
instance LValue Reg where
getLValue eenv (Reg i) = IOVector.unsafeRead (luaExecRegs eenv) i
{-# INLINE getLValue #-}
instance LValue Upvalue where
getLValue eenv (UpUp x) = getLValue eenv x
getLValue eenv (UpReg x) = getLValue eenv x
{-# INLINE getLValue #-}
{-# INLINE set #-}
set :: LValue a => LuaExecEnv -> a -> Value -> IO ()
set eenv r !x =
do ref <- getLValue eenv r
writeIORef ref x
-- | Class for types that are indexes to values.
class RValue a where
get :: LuaExecEnv -> a -> IO Value
instance RValue Upvalue where
{-# INLINE get #-}
get = lvalToRval
instance RValue UpIx where
{-# INLINE get #-}
get = lvalToRval
instance RValue Reg where
{-# INLINE get #-}
get = lvalToRval
{-# INLINE lvalToRval #-}
lvalToRval :: LValue a => LuaExecEnv -> a -> IO Value
lvalToRval eenv r = readIORef =<< getLValue eenv r
instance RValue RK where
get eenv (RK_Reg r) = get eenv r
get _ (RK_Kst k) = kst k
{-# INLINE get #-}
{-# INLINE getRegsFromLen #-}
getRegsFromLen :: LuaExecEnv -> Reg -> Int -> IO (SmallVec Value)
getRegsFromLen eenv (Reg r) len =
do let regs = luaExecRegs eenv
area = IOVector.unsafeSlice r len regs
SMV.generateM len (\i -> readIORef =<< IOVector.unsafeRead area i)
-- maybe unsafeFreeze?
{-# INLINE getRegsFromTo #-}
getRegsFromTo :: LuaExecEnv -> Reg -> Reg -> IO (SmallVec Value)
getRegsFromTo eenv (Reg r1) (Reg r2) =
getRegsFromLen eenv (Reg r1) (r2 - r1 + 1)
------------------------------------------------------------------------
-- Interpreter failures
------------------------------------------------------------------------
-- | Raise an exception due to a bug in the implementation of either the
-- interpreter or the bytecode compiler. These exceptions are not accessible
-- to the executing Lua program and should never occur due to a bug in a
-- user program.
interpThrow :: InterpreterFailureType -> IO b
interpThrow e = throwIO (InterpreterFailure {-loc-} e)
-- | Failure type paired with the stack trace at the time of failure
data InterpreterFailure =
InterpreterFailure {-[LocationInfo]-} InterpreterFailureType
instance Exception InterpreterFailure
-- | Types of fatal interpreter failures
data InterpreterFailureType
= UnexpectedExtraArg
| SetListNeedsTable
| ExecuteLuaWhileInC
| ExecuteLuaWhileInHs
| ExecuteLuaWhileInMLua
| MissingVarResults
deriving (Show)
instance Show InterpreterFailure where
show (InterpreterFailure {-loc-} e) = unlines
( "Interpreter failed!"
: [("Exception: " ++ show e)]
-- : ""
-- : map prettyLocationInfo loc
)
|
GaloisInc/galua
|
galua/src/Galua/OpcodeInterpreter.hs
|
mit
| 15,024
| 0
| 29
| 5,206
| 4,419
| 2,106
| 2,313
| 328
| 58
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
module Xml.LibrarySpec (spec) where
import Lastfm
import Lastfm.Library
import Test.Hspec
import Text.Xml.Lens
import SpecHelper
spec :: Spec
spec = do
it "addAlbum" $
shouldHaveXml_ . privately $
addAlbum (pure (albumItem <*> artist "Franz Ferdinand" <*> album "Franz Ferdinand"))
it "addArtist" $
shouldHaveXml_ . privately $
addArtist (pure (artistItem <*> artist "Mobthrow"))
it "addTrack" $
shouldHaveXml_ . privately $
addTrack <*> artist "Eminem" <*> track "Kim"
it "removeAlbum" $
shouldHaveXml_ . privately $
removeAlbum <*> artist "Franz Ferdinand" <*> album "Franz Ferdinand"
it "removeArtist" $
shouldHaveXml_ . privately $
removeArtist <*> artist "Burzum"
it "removeTrack" $
shouldHaveXml_ . privately $
removeTrack <*> artist "Eminem" <*> track "Kim"
it "removeScrobble" $
shouldHaveXml_ . privately $
removeScrobble <*> artist "Gojira" <*> track "Ocean" <*> timestamp 1328905590
it "getAlbums" $
publicly (getAlbums <*> user "smpcln" <* artist "Burzum" <* limit 5)
`shouldHaveXml`
root.node "albums".node "album".node "name".text
it "getArtists" $
publicly (getArtists <*> user "smpcln" <* limit 7)
`shouldHaveXml`
root.node "artists".node "artist".node "name".text
it "getTracks" $
publicly (getTracks <*> user "smpcln" <* artist "Burzum" <* limit 4)
`shouldHaveXml`
root.node "tracks".node "track".node "name".text
|
supki/liblastfm
|
test/api/Xml/LibrarySpec.hs
|
mit
| 1,530
| 0
| 14
| 321
| 453
| 214
| 239
| -1
| -1
|
-- Copyright 2015-2016 Yury Gribov
--
-- Use of this source code is governed by MIT license that can be
-- found in the LICENSE.txt file.
module Board (Board, genrand, size, pretty_print, pretty_read, solve, to_cnf) where
import qualified System.Random
import qualified Data.List
import qualified Data.Maybe
import qualified Data.Array
import Data.Array ((!),(//))
import Debug.Trace (trace)
import qualified Control.DeepSeq
import Control.DeepSeq (($!!))
import qualified Support
import qualified CNF
type BoardElt = Maybe Int
type Board = (Int, Data.Array.Array Int BoardElt)
indices (size, _) = [0 .. size - 1]
index_pairs b = [(i, j) | i <- indices b, j <- indices b]
encode_idx (size, _) (i, j) = i * size + j
decode_idx (size, _) i =
let row = i `mod` size in (row, i - row * size)
block_size size = Support.isqrt size
ij2block (size, _) i j =
let
bs = block_size size
in
(div i bs, div j bs)
block_ijs b@(size, m) i j =
let
bs = block_size size
in
[(i', j') | di <- [0 .. bs - 1],
dj <- [0 .. bs - 1],
let i' = i * bs + di,
let j' = j * bs + dj]
-- Get row of board
row :: Board -> Int -> [Maybe Int]
row b@(size, m) i =
[x | j <- indices b,
let idx = encode_idx b (i, j),
let x = m ! idx]
-- Same but with non-initialized elements removed
row_short :: Board -> Int -> [Int]
row_short b i = Data.Maybe.catMaybes $ row b i
-- Same for columns
col :: Board -> Int -> [Maybe Int]
col b@(size, m) j =
[x | i <- indices b,
let idx = encode_idx b (i, j),
let x = m ! idx]
-- Same for columns
col_short :: Board -> Int -> [Int]
col_short b i = Data.Maybe.catMaybes $ col b i
-- Get neighbors of element
block :: Board -> (Int, Int) -> [Maybe Int]
block b@(size, m) (i, j) =
[x | ij <- block_ijs b i j,
let idx = encode_idx b ij,
let x = m ! idx]
-- Same but with non-initialized elements removed
block_short :: Board -> (Int, Int) -> [Int]
block_short b ij = Data.Maybe.catMaybes $ block b ij
-- Can we place k at (i, j) in board?
is_good_position :: (Int, Int) -> Int -> Board -> Bool
is_good_position (i, j) k b@(size, m) =
let
no_conflicts = notElem k
old = m ! encode_idx b (i, j)
bij = ij2block b i j
in
Data.Maybe.isNothing old && no_conflicts (row_short b i) && no_conflicts (col_short b j) && no_conflicts (block_short b bij)
-- Helper for genrand: put n random elements on board
put_on_board :: Board -> Int -> Int -> System.Random.StdGen -> Either String (Board, System.Random.StdGen)
put_on_board _ _ 0 _ = Left "size is probably too big for generator"
put_on_board b 0 _ r = Right (b, r)
put_on_board b@(size, m) n limit r =
let
bnds = (0, size - 1)
(i, r2) = System.Random.randomR bnds r
(j, r3) = System.Random.randomR bnds r2
(k, r4) = System.Random.randomR (1, size) r3
idx = encode_idx b (i, j)
m' = m // [(idx, Just k)]
limit' = limit - 1
in
if is_good_position (i, j) k b
then put_on_board (size, m') (n - 1) limit' r4
else put_on_board b n limit' r4
-- Generate board with n random elements
genrand :: Int -> Int -> System.Random.StdGen -> Either String (Board, System.Random.StdGen)
genrand size n r
| bs * bs /= size = Left "board size must be a square"
| otherwise = put_on_board (size, m) n limit r
where
m = Support.filled (0, size * size - 1) Nothing
limit = 10000
bs = Support.isqrt size
-- Returns board size
size :: Board -> Int
size (s, _) = s
pretty_print :: Board -> String
pretty_print b@(size, m) =
let
ndigits = length $ show size
pad = Support.pad ndigits ' '
print_elt x = pad $
case x of
Nothing -> "."
Just y -> Prelude.show y
print_row i = unwords (map print_elt $ row b i) ++ "\n"
in
concatMap print_row [0 .. size - 1]
pretty_read :: String -> Board
pretty_read s =
let
rows = Support.deintersperse_multi '\n' s
cols = map (Support.deintersperse_multi ' ') rows
num_rows = length rows
num_cols = map length cols
size = if all (== num_rows) num_cols
then num_rows
else error "non-matching number of rows/columns"
read_elt x = if x == "." then Nothing else Just $ read x
mapmap f = map (map f)
nums = mapmap read_elt cols
-- FIXME: slow
inits =
[(idx, x) | i <- [0 .. size - 1],
j <- [0 .. size - 1],
let idx = i * size + j,
let x = nums !! i !! j]
in
(size, Data.Array.array (0, size * size - 1) inits)
{-
This is a first try on generating CNF from Sudoku.
Let N denote the size of the board.
Each position (total N*N positions) gets N boolean variables,
Si,j(k) one per each possible number in this position.
The number of variables is thus N^3.
Then we can formalize Sudoku as
(1) Si,j(k) -> not Si,j(k') for all k' /= k
(2) Si,j(k) -> not Si',j(k) for all i' /= i
(3) Si,j(k) -> not Si,j'(k) for all j' /= i
(4) Si,j(k) -> not Si',j'(k) for all i', j' in surrounding block
(5) Si,j(k) for some k
We can rewrite these for CNF form:
(1) not Si,j(k) or not Si,j(k')
(2) not Si,j(k) or not Si',j(k)
(3) not Si,j(k) or not Si,j'(k)
(4) not Si,j(k) or not Si',j'(k)
(5) Si,j(1) or Si,j(2) or ...
Each rule scheme gives N^4 equations. Problem sizes for small boards:
* 26244 for 9x9 boards
* 262144 for 16x16 boards
* 1562500 for 25x25 boards
* 6718464 for 36*36 boards
-}
nvars (size, _) = size * size * size
encode (size, _) i j k = i * size * size + j * size + k
decode (size, _) idx = let idx1 = idx - 1 in (idx1 `mod` size * size, idx1 `mod` size, rem idx1 size + 1)
to_cnf :: Board -> CNF.CNF
to_cnf b@(size, m) = rules
where
rule1 i j k k' = CNF.Clz2 (CNF.notlit $ encode b i j k) (CNF.notlit $ encode b i j k')
rule2 i j k i' = CNF.Clz2 (CNF.notlit $!! encode b i j k) (CNF.notlit $!! encode b i' j k)
rule3 i j k j' = CNF.Clz2 (CNF.notlit $!! encode b i j k) (CNF.notlit $!! encode b i j' k)
rule4 i j k i' j' = CNF.Clz2 (CNF.notlit $!! encode b i j k) (CNF.notlit $!! encode b i' j' k)
rule5 i j = CNF.ClzN $ map (\k -> CNF.lit $ encode b i j k) [1 .. size]
fact (i, j) =
case m ! encode_idx b (i, j) of
Nothing -> Nothing
Just k -> Just $ CNF.Clz1 $ CNF.lit $ encode b i j k
ijks = [(i, j, k) | i <- [0 .. size - 1], j <- [0 .. size - 1], k <- [1 .. size]]
rules = rules1 ++ rules2 ++ rules3 ++ rules4 ++ rules5 ++ facts
rules1 =
[rule1 i j k k' | (i, j, k) <- ijks, k' <- [1 .. k - 1]]
rules2 =
[rule2 i j k i' | (i, j, k) <- ijks, i' <- [0 .. i - 1]]
rules3 =
[rule3 i j k j' | (i, j, k) <- ijks, j' <- [0 .. j - 1]]
rules4 =
[rule4 i j k i' j' | (i, j, k) <- ijks,
let idx = encode_idx b (i, j),
let (bi, bj) = ij2block b i j,
(i', j') <- block_ijs b bi bj,
let idx' = encode_idx b (i', j'),
idx' > idx]
rules5 = [rule5 i j | i <- [0 .. size - 1], j <- [0 .. size - 1]]
facts = Data.Maybe.mapMaybe fact $ index_pairs b
-- Helper for solve
get_single_yes :: Board -> [CNF.Lit] -> Int
get_single_yes b cnf
-- | trace ("get_assign:\n cnf = " ++ (show cnf) ++ "\n pos = " ++ (show pos) ++ "\n negs = " ++ (show negs) ++ "\n") False = undefined
| length yes /= 1 = error "invalid input from solver: number of positive variables for cell /= 1"
| otherwise = k
where
(_, yes) = Data.List.partition CNF.is_negation cnf
CNF.Yes var = head yes
(_, _, k) = decode b var
conflict :: Board -> Board -> Bool
conflict (size1, m1) (size2, m2)
| size1 /= size2 = error "unexpected arguments"
| otherwise = any (\i -> conflict' (m1 ! i) (m2 ! i)) $ Data.Array.indices m1
where
conflict' Nothing _ = False
conflict' _ Nothing = False
conflict' (Just x) (Just y) = x /= y
-- Helper for solve
from_cnf b@(size, m) cnf
| length cnf /= size * size * size = error "invalid input from solver: number of variables not matching board"
| conflict b b' = error "invalid input from solver: original board contents not preserved"
| otherwise = b'
where
chunks = Support.chunks cnf size -- Each cell has size variables assigned
vals = map (get_single_yes b) chunks
m' = Data.Array.array (0, size * size - 1) $ zip [0 .. size * size - 1] (map Just vals)
b' = (size, m')
-- Solve Sudoku!
solve :: Board -> IO (Maybe Board)
solve b@(size, m) = do
sol <- CNF.solve False $ to_cnf b
case sol of
Nothing -> return Nothing
Just cnf -> return $ Just $ from_cnf b cnf
|
yugr/sudoku
|
src/Board.hs
|
mit
| 8,721
| 0
| 15
| 2,466
| 3,319
| 1,767
| 1,552
| -1
| -1
|
-- Copyright © 2013 Julian Blake Kongslie <jblake@jblake.org>
-- Licensed under the MIT license.
{-# OPTIONS_GHC -Wall -Werror #-}
module Language.GBAsm.Relative
where
import Data.Generics.Uniplate.Operations
import Language.GBAsm.Types
-- |Transform operands by replacing relative addressing with subtraction operations on absolute addresses.
relativePass :: FullAST -> FullAST
relativePass = transform fixAST
where
fixAST (Raw dec@(_,pos) ops) = Raw dec $ map (tOperand pos) ops
fixAST (Inc dec@(_,pos) fn a b) = Inc dec fn (tOperand pos a) (tOperand pos b)
fixAST (Op1 dec@(_,pos) op a) = Op1 dec op (tOperand pos a)
fixAST (Op2 dec@(_,pos) op a b) = Op2 dec op (tOperand pos a) (tOperand pos b)
fixAST n = n
tOperand pos = transform fixOperand
where
fixOperand (Rel a) = Sub a $ Abs $ outputAddress pos + outputSize pos
fixOperand o = o
|
jblake/gbasm
|
src/Language/GBAsm/Relative.hs
|
mit
| 931
| 0
| 12
| 222
| 300
| 158
| 142
| 14
| 6
|
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.NavigatorID
(getAppCodeName, getAppName, getAppVersion, getPlatform,
getProduct, getProductSub, getUserAgent, getVendor, getVendorSub,
NavigatorID(..), gTypeNavigatorID, IsNavigatorID, toNavigatorID)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID.appCodeName Mozilla NavigatorID.appCodeName documentation>
getAppCodeName ::
(MonadDOM m, IsNavigatorID self, FromJSString result) =>
self -> m result
getAppCodeName self
= liftDOM
(((toNavigatorID self) ^. js "appCodeName") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID.appName Mozilla NavigatorID.appName documentation>
getAppName ::
(MonadDOM m, IsNavigatorID self, FromJSString result) =>
self -> m result
getAppName self
= liftDOM
(((toNavigatorID self) ^. js "appName") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID.appVersion Mozilla NavigatorID.appVersion documentation>
getAppVersion ::
(MonadDOM m, IsNavigatorID self, FromJSString result) =>
self -> m result
getAppVersion self
= liftDOM
(((toNavigatorID self) ^. js "appVersion") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID.platform Mozilla NavigatorID.platform documentation>
getPlatform ::
(MonadDOM m, IsNavigatorID self, FromJSString result) =>
self -> m result
getPlatform self
= liftDOM
(((toNavigatorID self) ^. js "platform") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID.product Mozilla NavigatorID.product documentation>
getProduct ::
(MonadDOM m, IsNavigatorID self, FromJSString result) =>
self -> m result
getProduct self
= liftDOM
(((toNavigatorID self) ^. js "product") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID.productSub Mozilla NavigatorID.productSub documentation>
getProductSub ::
(MonadDOM m, IsNavigatorID self, FromJSString result) =>
self -> m result
getProductSub self
= liftDOM
(((toNavigatorID self) ^. js "productSub") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID.userAgent Mozilla NavigatorID.userAgent documentation>
getUserAgent ::
(MonadDOM m, IsNavigatorID self, FromJSString result) =>
self -> m result
getUserAgent self
= liftDOM
(((toNavigatorID self) ^. js "userAgent") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID.vendor Mozilla NavigatorID.vendor documentation>
getVendor ::
(MonadDOM m, IsNavigatorID self, FromJSString result) =>
self -> m result
getVendor self
= liftDOM
(((toNavigatorID self) ^. js "vendor") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID.vendorSub Mozilla NavigatorID.vendorSub documentation>
getVendorSub ::
(MonadDOM m, IsNavigatorID self, FromJSString result) =>
self -> m result
getVendorSub self
= liftDOM
(((toNavigatorID self) ^. js "vendorSub") >>= fromJSValUnchecked)
|
ghcjs/jsaddle-dom
|
src/JSDOM/Generated/NavigatorID.hs
|
mit
| 4,241
| 0
| 11
| 746
| 937
| 533
| 404
| 74
| 1
|
module TuringMachine where
import Alphabet
import State
import Tape as T
import Movement
import Util
-- |Transition function
type Transition s a = State s -> Alphabet a -> (State s, Alphabet a, Movement)
-- |Turingmachine containing the current state, the transition table and the k
-- tapes.
data TuringMachine s a = TM (State s) (Transition s a) (Tape a)
-- |Intitializes a Turing Machine TM with k Tapes. Whereas the first tape is the
-- input tape, the last tape is the output tape. Hence there are k-2 working
-- tapes left.
init :: Tape a -> Transition s a -> TuringMachine s a
init tape transition = TM SStart transition tape
computeStep :: TuringMachine s a -> TuringMachine s a
computeStep (TM Halt transf tape) = TM Halt transf tape
computeStep (TM state transf tape) = TM state' transf tape'
where action = transf state (T.read tape)
state' = fstOf3 action
symbol' = sndOf3 action
tape' = moveTape (thdOf3 action) (write symbol' tape)
compute :: TuringMachine s a -> TuringMachine s a
compute (TM Halt transf tape) = TM Halt transf tape
compute machine = compute . computeStep $ machine
getOutput :: TuringMachine s a -> Tape a
getOutput (TM _ _ tape) = tape
moveTape :: Movement -> Tape a -> Tape a
moveTape L tape = moveLeft tape
moveTape R tape = moveRight tape
moveTape S tape = tape
|
carabolic/huring
|
src/Data/TuringMachine.hs
|
gpl-2.0
| 1,343
| 0
| 10
| 278
| 421
| 215
| 206
| 26
| 1
|
module Ch_09
(boundedMin
) where
boundedMin :: (Double -> Double) -- ^ function
-> Double -- ^ leftmost point
-> Double -- ^ rightmost point
-> Double -- ^ error bound
-> Double -- ^ result within bound
boundedMin func a b err
| abs (x3 - x0) <= err = (x0 + x3) / 2
| func x1 > func x2 = boundedMin func x1 x3 err
| otherwise = boundedMin func x0 x2 err
where
phi = (sqrt 5 - 1) / 2
x0 = a
x1 = a + (b-a) * (1-phi)
x2 = a + (b-a) * phi
x3 = b
|
Marcus-Rosti/numerical-methods
|
src/ch_09/Ch_09.hs
|
gpl-2.0
| 496
| 0
| 11
| 158
| 211
| 111
| 100
| 16
| 1
|
-- BNF Converter: Error Monad
-- Copyright (C) 2004 Author: Aarne Ranta
-- This file comes with NO WARRANTY and may be used FOR ANY PURPOSE.
module Amath.Expr.ErrM where
-- the Error monad: like Maybe type with error msgs
import Control.Monad (MonadPlus(..), liftM)
data Err a = Ok a | Bad String
deriving (Read, Show, Eq, Ord)
instance Monad Err where
return = Ok
fail = Bad
Ok a >>= f = f a
Bad s >>= f = Bad s
instance Functor Err where
fmap = liftM
instance MonadPlus Err where
mzero = Bad "Err.mzero"
mplus (Bad _) y = y
mplus x _ = x
|
arnizamani/SeqSolver
|
Amath/Expr/ErrM.hs
|
gpl-2.0
| 586
| 0
| 8
| 153
| 169
| 91
| 78
| 15
| 0
|
{-# LANGUAGE DeriveDataTypeable #-}
module DataStructures.Sets where
import qualified Data.Set as S
import System.Random
import System.IO.Unsafe
import Control.Exception
import Data.Typeable
type Set a = S.Set a
data SetsException = EmptySet | IndexOutOfRange Int
deriving (Show, Typeable)
instance Exception SetsException
-- Membership in the set
mem::Ord a => a -> Set a -> Bool
mem x s = S.member x s
-- Sets equality
(==)::Ord a => Set a -> Set a -> Bool
(==) s1 s2 = S.isSubsetOf s1 s2 && S.isSubsetOf s2 s1
-- Subset
subset::Ord a => Set a -> Set a -> Bool
subset = S.isSubsetOf
-- Emptiness test
is_empty::Set a -> Bool
is_empty = S.null
-- Add an element
add::Ord a => a -> Set a -> Set a
add = S.insert
-- Construction of a single-element set
singleton::a -> Set a
singleton = S.singleton
-- Remove an element
remove::Ord a => a -> Set a -> Set a
remove = S.delete
-- Sets union
union::Ord a => Set a -> Set a -> Set a
union = S.union
-- Sets intersection
inter::Ord a => Set a -> Set a -> Set a
inter = S.intersection
-- Sets difference
diff::Ord a => Set a -> Set a -> Set a
diff = S.difference
-- Filter over a set
filter::(a -> Bool) -> Set a -> Set a
filter = S.filter
-- Map of a set
map::Ord b =>(a -> b) -> Set a -> Set b
map = S.map
-- Size of a set
cardinal::Set a -> Int
cardinal = S.size
-- Nth element of a set
nth::Int -> Set a -> a
nth i s = if (i<0 || i>=(cardinal s)) then throw (IndexOutOfRange i) else S.elemAt i s
-- Minimum element of an integer's set
min_elt::Set Int -> Int
min_elt s = if (is_empty s) then throw EmptySet else (S.findMin s)
-- Maximum element of an integer's set
max_elt::Set Int -> Int
max_elt s = if (is_empty s) then throw EmptySet else (S.findMax s)
-- Set of an integer's interval
interval::Int -> Int -> Set Int
interval i j = S.fromAscList [i..(j-1)]
-- Sum of the integers obtained by applying a function to the set
sum::Set a -> (a -> Int) -> Int
sum s f = S.foldr (+) 0 (S.map f s)
-- Random element of the set
choose::Set a -> a
choose s = unsafePerformIO f
where f = do
newStdGen
g <- getStdGen
return (S.elemAt (fst (randomR (0,(cardinal s)-1) g)) s)
|
ricardopenyamari/ir2haskell
|
clir-parser-haskell-master/src/DataStructures/Sets.hs
|
gpl-2.0
| 2,318
| 0
| 19
| 615
| 876
| 454
| 422
| 53
| 2
|
module Util (
unwordsList
) where
unwordsList :: (Show a) => [a] -> String
unwordsList = unwords . map show
|
mhrheaume/hskme
|
Util.hs
|
gpl-2.0
| 110
| 2
| 7
| 22
| 44
| 25
| 19
| 4
| 1
|
{- |
Module : $EmptyHeader$
Description : <optional short description entry>
Copyright : (c) <Authors or Affiliations>
License : GPLv2 or higher, see LICENSE.txt
Maintainer : <email>
Stability : unstable | experimental | provisional | stable | frozen
Portability : portable | non-portable (<reason>)
<optional description>
-}
module Proof where
-- ((-->), (<-->), (\/), (/\), true, false, box, dia, neg, var, provable)
import Data.List (delete, intersect, nub)
-- data type for fomulas
data Form = Var Int --Var Char (Maybe Int) -- variables
| Not !Form -- ¬A
| Box !Form -- [] A
| Conj !Form !Form -- A/\B
deriving (Eq)
type Sequent = [Form] -- defines a sequent
-- pretty printing (sort of)
instance Show Form where
show f = case f of
Var i -> "p" ++ show i
Not g -> "~" ++ show g
Box g -> "[]" ++ show g
Conj g h -> "(" ++ show g ++ "&" ++ show h ++ ")"
-- syntactic sugar
p = Var 0
q = Var 1
r = Var 2
(-->) :: Form -> Form -> Form
infixr 5 -->
p --> q = Not (Conj p (Not q)) -- ~p\/q
(<-->) :: Form -> Form -> Form
infixr 4 <-->
p <--> q = Conj (p-->q) (q-->p) --Not (Conj (Not (Conj p q)) (Not(Conj (Not p) (Not q))))
box :: Form -> Form
box p = Box p
dia :: Form -> Form
dia p = Not(Box(Not p))
(/\) :: Form -> Form -> Form
infix 7 /\
p /\ q = Conj p q
(\/) :: Form -> Form -> Form
infix 6 \/
p \/ q = neg ((neg p) /\ (neg q))
neg :: Form -> Form
neg p = Not p
false :: Form
false = (Var 0) /\ (Not (Var 0))
true :: Form
true = neg false
var :: Int -> Form
var n = Var n
-- the rank of a modal formula
rank :: Form -> Int
rank (Box p) = 1 + (rank p)
rank (Conj p q) = (max (rank p) (rank q))
rank (Not p) = rank p
rank (Var p) = 0
-- expand applies all sequent rules that do not induce branching
expand :: Sequent -> Sequent
expand s | seq s $ False = undefined -- force strictness
expand [] = []
expand ((Not (Not p)):as) = expand (p:as)
expand ((Not (Conj p q)):as) = expand ((Not p):(Not q):as)
expand (a:as) = a:(expand as)
----------------------------------------------------------------------------------------------------
--Inference Rules
-- map a sequent the list of all lists of all premises that derive
-- the sequent. Note that a premise is a list of sequents:
-- * to prove Gamma, A /\ B we need both Gamma, A and Gamma, B as premises.
-- * to prove Gamma, neg(A /\ B), we need Gamma, neg A, neg B as premise.
-- * to prove A, neg A, Gamma we need no premises
-- So a premise is a list of sequents, and the list of all possible
-- premises therefore has type [[ Sequent ]]
-- the functions below compute the list of all possible premises
-- that allow to derive a given sequent using the rule that
-- lends its name to the function.
axiom :: Sequent -> [[Sequent]]
-- faster to check for atomic axioms
-- axiom1 xs = [ [] | p <- xs, (Not q) <- xs, p==q]
axiom xs = nub [ [] | (Var n) <- xs, (Not (Var m)) <- xs, m==n]
negI :: Sequent -> [[Sequent]]
negI xs = [ [(p: delete f xs)] | f@(Not(Not p)) <- xs]
negConj :: Sequent -> [[Sequent]]
negConj (as) = [[( (Not(p)): (Not(q)) : delete f as )]| f@(Not(Conj p q)) <- as]
-- two variants here: use @-patterns or ``plain'' recursion.
conj :: Sequent -> [[ Sequent ]]
conj s | seq s $ False = undefined -- force strictness
conj (as) = [ [ (p: delete f as) , ( q: delete f as )] | f@(Conj p q ) <- as]
boxI :: Sequent -> [[Sequent]]
boxI (xs) = let as = [ (Not p) | (Not(Box p)) <- xs]
in [ [ p:as] | (Box p) <- xs ] ++
[ [ (Not q):delete g xs] | g@(Not (Box q)) <- xs ] -- T rule
tRule :: Sequent -> [[ Sequent ]]
tRule (xs) = [ [ (Not p):delete f xs] | f@(Not (Box p)) <- xs ] -- T rule
-- collect all possible premises, i.e. the union of the possible
-- premises taken over the set of all rules in one to get the
-- recursion off the ground.
-- CAVEAT: the order of axioms /rules has a HUGE impact on performance.
allRules :: Sequent -> [[Sequent]]
-- this is as good as it gets if we apply the individual rules
-- message for the afterworld: if you want to find proofs quickly,
-- first look at the rules that induce branching.
-- allRules s = (axiom1 s) ++ (axiom2 s) ++ (boxI s) ++ (conj s) ++ (negDisj s) ++ (negI s) ++ (negConj s) ++ (disj s)
-- we can do slightly better if we apply all rules that do not
-- induce branching in one single step.
allRules s = let t = expand s in (axiom $ t) ++ (boxI $ t) ++ (conj $ t) -- ++ (tRule t)
-- A sequent is provable iff there exists a set of premises that
-- prove the sequent such that all elements in the list of premises are
-- themselves provable.
sprovable :: Sequent -> Bool
sprovable s | seq s $ False = undefined -- force strictness
sprovable s = any (\p -> (all sprovable p)) (allRules s)
-- specialisatino to formulas
provable :: Form -> Bool
provable p = sprovable [ p ]
-- test cases:
dp1 = (neg (neg p)) \/ ((neg (neg q)) \/ r) -- not provable
dp2 = box p \/ neg(box p) -- provable
dp3 = box p \/ neg(box(neg(neg p))) -- provable
dp4 = neg( neg(box p /\ neg(box p)) --> (box q /\ box p) /\ neg(box q))
dp5 = neg( neg(box p /\ neg(box p)) --> (box q /\ box p) /\ dia(neg q))
dp6 = (box p) /\ (dia q) --> (dia (p /\ q)) -- true?
dp7 = (box (dia (box p))) --> (dia (box (neg p))) -- false?
level :: Int -> [Form]
level 0 = [var 0, var 1, neg $ var 0, neg $ var 1 ]
level n = let pbox = map box [ x | i <- [0 .. (n-1)], x <- (level i)]
nbox = map (neg . box) [ x | i <- [0 .. (n-1)], x <- (level i)]
in
pbox ++ nbox ++ [ p /\ q | p <- pbox, q <- nbox] ++ [neg (p /\ q) | p <- pbox, q <- nbox ]
tforms :: [ (Sequent, Sequent) ]
tforms = [ ([neg a, neg $ box a, b ], [neg $ box a, b]) | a <- level 2, b <- level 2]
ttest :: [ (Sequent, Sequent) ] -> String
ttest [] = []
ttest ( (s1, s2):as ) =
let s1p = (sprovable s1) ;
s2p = (sprovable s2)
in if (s1p /= s2p) then "GOTCHA: " ++ (show s1) ++ (show s2) ++ "<"
else "*" ++ (ttest as)
|
nevrenato/Hets_Fork
|
GMP/Proof.hs
|
gpl-2.0
| 6,140
| 0
| 15
| 1,626
| 2,265
| 1,202
| 1,063
| 103
| 2
|
{-# LANGUAGE DeriveDataTypeable,OverloadedStrings #-}
module Ampersand.Prototype.GenFrontend (doGenFrontend) where
import Ampersand.Basics
import Ampersand.Classes.Relational
import Ampersand.ADL1
import Ampersand.Core.ShowAStruct
import Ampersand.FSpec.FSpec
import Ampersand.FSpec.ToFSpec.NormalForms
import Ampersand.Misc
import Ampersand.Prototype.ProtoUtil
import Codec.Archive.Zip
import Control.Exception
import Control.Monad
import qualified Data.ByteString.Lazy as BL
import Data.Char
import Data.Data
import Data.Hashable (hash)
import Data.List
import Data.Maybe
import Network.HTTP.Simple
import System.Directory
import System.FilePath
import Text.StringTemplate
import Text.StringTemplate.GenericStandard () -- only import instances
{- TODO
- Be more consistent with record selectors/pattern matching
- HStringTemplate hangs on uninitialized vars in anonymous template? (maybe only fields?)
- isRoot is a bit dodgy (maybe make dependency on ONE and SESSIONS a bit more apparent)
- Keeping templates as statics requires that the static files are written before templates are used.
Maybe we should keep them as cabal data-files instead. (file extensions and directory structure are predictable)
NOTE: interface refs are handled as follows:
INTERFACE MyInterface
BOX [ ref : rel[$a*$b]
INTERFACE RefInterface
]
INTERFACE RefInterface relRef[$b*$c]
BOX [ .. : ..[$c*$d]
]
is basically mapped onto:
INTERFACE MyInterface
BOX [ ref : (rel;relRef)[$a*$c]
BOX [ .. : ..[$c*$d]
]
]
This is considered editable iff the composition rel;relRef yields an editable relation (e.g. for editableR;I).
-}
getTemplateDir :: FSpec -> String
getTemplateDir fSpec = dirPrototype (getOpts fSpec) </> "templates"
-- For useful info on the template language, see
-- https://theantlrguy.atlassian.net/wiki/display/ST4/StringTemplate+cheat+sheet
-- NOTE: due to a bug in HStringTemplate's checkTemplateDeep, non-existent attribute names on
-- composite attributes in anonymous templates will hang the generator :-(
-- Eg. "$subObjects:{subObj| .. $subObj.nonExistentField$ .. }$"
doGenFrontend :: FSpec -> IO ()
doGenFrontend fSpec =
do { verboseLn options "Generating frontend..."
; isCleanInstall <- downloadPrototypeFramework options
; copyTemplates fSpec
; feInterfaces <- buildInterfaces fSpec
; genViewInterfaces fSpec feInterfaces
; genControllerInterfaces fSpec feInterfaces
; genRouteProvider fSpec feInterfaces
; writePrototypeAppFile options ".timestamp" (show . hash . show . genTime $ options) -- this hashed timestamp is used by the prototype framework to prevent browser from using the wrong files from cache
; copyCustomizations fSpec
-- ; deleteTemplateDir fSpec -- don't delete template dir anymore, because it is required the next time the frontend is generated
; when isCleanInstall $ do
putStrLn "Installing dependencies..." -- don't use verboseLn here, because installing dependencies takes some time and we want the user to see this
installComposerLibs options
; verboseLn options "Frontend generated"
}
where
options = getOpts fSpec
copyTemplates :: FSpec -> IO ()
copyTemplates fSpec =
do { let tempDir = dirSource (getOpts fSpec) </> "templates"
toDir = dirPrototype (getOpts fSpec) </> "templates"
; tempDirExists <- doesDirectoryExist tempDir
; if tempDirExists then
do { verboseLn (getOpts fSpec) $ "Copying project specific templates from " ++ tempDir ++ " -> " ++ toDir
; copyDirRecursively tempDir toDir (getOpts fSpec) -- recursively copy all templates
}
else
verboseLn (getOpts fSpec) $ "No project specific templates (there is no directory " ++ tempDir ++ ")"
}
copyCustomizations :: FSpec -> IO ()
copyCustomizations fSpec =
mapM_ (copyDir protoDir) custDirs
where
custDirs = map (dirSource opts </>) (dirCustomizations opts)
protoDir = dirPrototype opts
opts = getOpts fSpec
copyDir :: FilePath -> FilePath -> IO()
copyDir targetDir sourceDir = do
sourceDirExists <- doesDirectoryExist sourceDir
if sourceDirExists then
do verboseLn opts $ "Copying customizations from " ++ sourceDir ++ " -> " ++ targetDir
copyDirRecursively sourceDir targetDir opts -- recursively copy all customizations
else verboseLn opts $ "No customizations (there is no directory " ++ sourceDir ++ ")"
-- deleteTemplateDir :: FSpec -> IO ()
-- deleteTemplateDir fSpec = removeDirectoryRecursive $ dirPrototype (getOpts fSpec) </> "templates"
------ Build intermediate data structure
-- NOTE: _ disables 'not used' warning for fields
data FEInterface = FEInterface { ifcName :: String
, ifcLabel :: String
, _ifcExp :: Expression
, _ifcSource :: A_Concept
, _ifcTarget :: A_Concept
, _ifcRoles :: [Role]
, _ifcObj :: FEObject2
} deriving (Typeable, Data)
data FEObject2 =
FEObjE { objName :: String
, objExp :: Expression
, objSource :: A_Concept
, objTarget :: A_Concept
, objCrudC :: Bool
, objCrudR :: Bool
, objCrudU :: Bool
, objCrudD :: Bool
, exprIsUni :: Bool
, exprIsTot :: Bool
, relIsProp :: Bool -- True iff the expression is a kind of simple relation and that relation is a property.
, exprIsIdent :: Bool
, atomicOrBox :: FEAtomicOrBox
}
| FEObjT { objName :: String
, objTxt :: String
} deriving (Show, Data, Typeable )
-- Once we have mClass also for Atomic, we can get rid of FEAtomicOrBox and pattern match on _ifcSubIfcs to determine atomicity.
data FEAtomicOrBox = FEAtomic { objMPrimTemplate :: Maybe ( FilePath -- the absolute path to the template
, [String] -- the attributes of the template
) }
| FEBox { objMClass :: Maybe String
, ifcSubObjs :: [FEObject2]
} deriving (Show, Data,Typeable)
buildInterfaces :: FSpec -> IO [FEInterface]
buildInterfaces fSpec = mapM (buildInterface fSpec allIfcs) topLevelUserInterfaces
where
allIfcs :: [Interface]
allIfcs = interfaceS fSpec
topLevelUserInterfaces :: [Interface]
topLevelUserInterfaces = filter (not . ifcIsAPI) allIfcs
buildInterface :: FSpec -> [Interface] -> Interface -> IO FEInterface
buildInterface fSpec allIfcs ifc =
do { obj <- buildObject (BxExpr $ ifcObj ifc)
; return
FEInterface { ifcName = escapeIdentifier $ name ifc
, ifcLabel = name ifc
, _ifcExp = objExp obj
, _ifcSource = objSource obj
, _ifcTarget = objTarget obj
, _ifcRoles = ifcRoles ifc
, _ifcObj = obj
}
-- NOTE: due to Amperand's interface data structure, expression, source, and target are taken from the root object.
-- (name comes from interface, but is equal to object name)
}
where
buildObject :: BoxItem -> IO FEObject2
buildObject (BxExpr object') =
do { let object = substituteReferenceObjectDef fSpec object'
; let iExp = conjNF (getOpts fSpec) $ objExpression object
; (aOrB, iExp') <-
case objmsub object of
Nothing ->
do { let ( _ , _ , tgt) = getSrcDclTgt iExp
; let mView = case objmView object of
Just nm -> Just $ lookupView fSpec nm
Nothing -> getDefaultViewForConcept fSpec tgt
; mSpecificTemplatePath <-
case mView of
Just Vd{vdhtml=Just (ViewHtmlTemplateFile fName), vdats=viewSegs}
-> return $ Just (fName, mapMaybe vsmlabel viewSegs)
_ -> -- no view, or no view with an html template, so we fall back to target-concept template
-- TODO: once we can encode all specific templates with views, we will probably want to remove this fallback
do { let templatePath = "Atomic-" ++ escapeIdentifier (name tgt) ++ ".html"
; hasSpecificTemplate <- doesTemplateExist fSpec templatePath
; return $ if hasSpecificTemplate then Just (templatePath, []) else Nothing
}
; return (FEAtomic { objMPrimTemplate = mSpecificTemplatePath}
, iExp)
}
Just si ->
case si of
Box{} ->
do { subObjs <- mapM buildObject (siObjs si)
; return (FEBox { objMClass = siMClass si
, ifcSubObjs = subObjs
}
, iExp)
}
InterfaceRef{} ->
case filter (\rIfc -> name rIfc == siIfcId si) allIfcs of -- Follow interface ref
[] -> fatal ("Referenced interface " ++ siIfcId si ++ " missing")
(_:_:_) -> fatal ("Multiple relations of referenced interface " ++ siIfcId si)
[i] ->
if siIsLink si
then do { let templatePath = "View-LINKTO.html"
; return (FEAtomic { objMPrimTemplate = Just (templatePath, [])}
, iExp)
}
else do { refObj <- buildObject (BxExpr $ ifcObj i)
; let comp = ECps (iExp, objExp refObj)
-- Dont' normalize, to prevent unexpected effects (if X;Y = I then ((rel;X) ; (Y)) might normalize to rel)
; return (atomicOrBox refObj, comp)
} -- TODO: in Generics.php interface refs create an implicit box, which may cause problems for the new front-end
; let (src, mDecl, tgt) = getSrcDclTgt iExp'
; return FEObjE { objName = name object
, objExp = iExp'
, objSource = src
, objTarget = tgt
, objCrudC = crudC . objcrud $ object
, objCrudR = crudR . objcrud $ object
, objCrudU = crudU . objcrud $ object
, objCrudD = crudD . objcrud $ object
, exprIsUni = isUni iExp'
, exprIsTot = isTot iExp'
, relIsProp = case mDecl of
Nothing -> False
Just dcl -> isProp (EDcD dcl)
, exprIsIdent = isIdent iExp'
, atomicOrBox = aOrB
}
}
where getSrcDclTgt expr =
case getExpressionRelation expr of
Nothing -> (source expr, Nothing , target expr)
Just (declSrc, decl, declTgt, _) -> (declSrc , Just decl, declTgt )
-- if the expression is a relation, use the (possibly narrowed type) from getExpressionRelation
buildObject (BxTxt object') = do
return FEObjT{ objName = name object'
, objTxt = objtxt object'
}
------ Generate RouteProvider.js
genRouteProvider :: FSpec -> [FEInterface] -> IO ()
genRouteProvider fSpec ifcs =
do { --verboseLn opts $ show $ map name (interfaceS fSpec)
; template <- readTemplate fSpec "routeProvider.config.js"
; let contents = renderTemplate template $
setAttribute "contextName" (fsName fSpec)
. setAttribute "ampersandVersionStr" ampersandVersionStr
. setAttribute "ifcs" ifcs
. setAttribute "verbose" (verboseP opts)
; writePrototypeAppFile opts "routeProvider.config.js" contents
}
where opts = getOpts fSpec
------ Generate view html code
genViewInterfaces :: FSpec -> [FEInterface] -> IO ()
genViewInterfaces fSpec = mapM_ (genViewInterface fSpec)
genViewInterface :: FSpec -> FEInterface -> IO ()
genViewInterface fSpec interf =
do { lns <- genViewObject fSpec 0 (_ifcObj interf)
; template <- readTemplate fSpec "interface.html"
; let contents = renderTemplate template $
setAttribute "contextName" (addSlashes . fsName $ fSpec)
. setAttribute "isTopLevel" ((name . source . _ifcExp $ interf) `elem` ["ONE", "SESSION"])
. setAttribute "roles" (map show . _ifcRoles $ interf) -- show string, since StringTemplate does not elegantly allow to quote and separate
. setAttribute "ampersandVersionStr" ampersandVersionStr
. setAttribute "interfaceName" (ifcName interf)
. setAttribute "interfaceLabel" (ifcLabel interf) -- no escaping for labels in templates needed
. setAttribute "expAdl" (showA . _ifcExp $ interf)
. setAttribute "source" (escapeIdentifier . name . _ifcSource $ interf)
. setAttribute "target" (escapeIdentifier . name . _ifcTarget $ interf)
. setAttribute "crudC" (objCrudC (_ifcObj interf))
. setAttribute "crudR" (objCrudR (_ifcObj interf))
. setAttribute "crudU" (objCrudU (_ifcObj interf))
. setAttribute "crudD" (objCrudD (_ifcObj interf))
. setAttribute "contents" (intercalate "\n" lns) -- intercalate, because unlines introduces a trailing \n
. setAttribute "verbose" (verboseP opts)
; let filename = "ifc" ++ ifcName interf ++ ".view.html"
; writePrototypeAppFile opts filename contents
}
where opts = getOpts fSpec
-- Helper data structure to pass attribute values to HStringTemplate
data SubObjectAttr2 = SubObjAttr{ subObjName :: String
, subObjLabel :: String
, subObjContents :: String
, subObjExprIsUni :: Bool
} deriving (Show, Data, Typeable)
genViewObject :: FSpec -> Int -> FEObject2 -> IO [String]
genViewObject fSpec depth obj@FEObjE{} =
let atomicAndBoxAttrs :: StringTemplate String -> StringTemplate String
atomicAndBoxAttrs = setAttribute "exprIsUni" (exprIsUni obj)
. setAttribute "exprIsTot" (exprIsTot obj)
. setAttribute "name" (escapeIdentifier . objName $ obj)
. setAttribute "label" (objName obj) -- no escaping for labels in templates needed
. setAttribute "expAdl" (showA . objExp $ obj)
. setAttribute "source" (escapeIdentifier . name . objSource $ obj)
. setAttribute "target" (escapeIdentifier . name . objTarget $ obj)
. setAttribute "crudC" (objCrudC obj)
. setAttribute "crudR" (objCrudR obj)
. setAttribute "crudU" (objCrudU obj)
. setAttribute "crudD" (objCrudD obj)
. setAttribute "verbose" (verboseP (getOpts fSpec))
in case atomicOrBox obj of
FEAtomic{} ->
do { {-
verboseLn (getOpts fSpec) $ replicate depth ' ' ++ "ATOMIC "++show nm ++
" [" ++ name src ++ "*"++ name tgt ++ "], " ++
(if isEditable then "" else "not ") ++ "editable"
-}
-- For now, we choose specific template based on target concept. This will probably be too weak.
-- (we might want a single concept to could have multiple presentations, e.g. BOOL as checkbox or as string)
--; putStrLn $ nm ++ ":" ++ show mPrimTemplate
; conceptTemplate <- getTemplateForObject
; let (templateFilename, _) = fromMaybe (conceptTemplate, []) (objMPrimTemplate . atomicOrBox $ obj) -- Atomic is the default template
; template <- readTemplate fSpec templateFilename
; return . indentation
. lines
. renderTemplate template $
atomicAndBoxAttrs
}
FEBox { objMClass = mClass
, ifcSubObjs = subObjs} ->
do { subObjAttrs <- mapM genView_SubObject subObjs
; let clssStr = maybe "Box-ROWS.html" (\cl -> "Box-" ++ cl ++ ".html") mClass
; parentTemplate <- readTemplate fSpec clssStr
; return . indentation
. lines
. renderTemplate parentTemplate $
atomicAndBoxAttrs
. setAttribute "isRoot" (depth == 0)
. setAttribute "subObjects" subObjAttrs
}
where
indentation :: [String] -> [String]
indentation = map ( (replicate (if depth == 0 then 4 else 16) ' ') ++)
genView_SubObject :: FEObject2 -> IO SubObjectAttr2
genView_SubObject subObj =
case subObj of
FEObjE{} ->
do lns <- genViewObject fSpec (depth + 1) subObj
return SubObjAttr{ subObjName = escapeIdentifier $ objName subObj
, subObjLabel = objName subObj -- no escaping for labels in templates needed
, subObjContents = intercalate "\n" lns
, subObjExprIsUni = exprIsUni subObj
}
FEObjT{} ->
do return SubObjAttr{ subObjName = escapeIdentifier $ objName subObj
, subObjLabel = objName subObj
, subObjContents = objTxt subObj
, subObjExprIsUni = True
}
getTemplateForObject :: IO FilePath
getTemplateForObject
| relIsProp obj && (not . exprIsIdent) obj -- special 'checkbox-like' template for propery relations
= return $ "View-PROPERTY"++".html"
| otherwise = getTemplateForConcept (objTarget obj)
getTemplateForConcept :: A_Concept -> IO FilePath
getTemplateForConcept cpt = do
exists <- doesTemplateExist fSpec cptfn
return $ if exists
then cptfn
else "Atomic-"++show ttp++".html"
where ttp = cptTType fSpec cpt
cptfn = "Concept-"++name cpt++".html"
genViewObject _ _ FEObjT{} = pure []
------ Generate controller JavaScript code
genControllerInterfaces :: FSpec -> [FEInterface] -> IO ()
genControllerInterfaces fSpec = mapM_ (genControllerInterface fSpec)
genControllerInterface :: FSpec -> FEInterface -> IO ()
genControllerInterface fSpec interf =
do { -- verboseLn (getOpts fSpec) $ "\nGenerate controller for " ++ show iName
; let controlerTemplateName = "interface.controller.js"
; template <- readTemplate fSpec controlerTemplateName
; let contents = renderTemplate template $
setAttribute "contextName" (fsName fSpec)
. setAttribute "isRoot" ((name . source . _ifcExp $ interf) `elem` ["ONE", "SESSION"])
. setAttribute "roles" (map show . _ifcRoles $ interf) -- show string, since StringTemplate does not elegantly allow to quote and separate
. setAttribute "ampersandVersionStr" ampersandVersionStr
. setAttribute "interfaceName" (ifcName interf)
. setAttribute "interfaceLabel" (ifcLabel interf) -- no escaping for labels in templates needed
. setAttribute "expAdl" (showA . _ifcExp $ interf)
. setAttribute "exprIsUni" (exprIsUni (_ifcObj interf))
. setAttribute "source" (escapeIdentifier . name . _ifcSource $ interf)
. setAttribute "target" (escapeIdentifier . name . _ifcTarget $ interf)
. setAttribute "crudC" (objCrudC (_ifcObj interf))
. setAttribute "crudR" (objCrudR (_ifcObj interf))
. setAttribute "crudU" (objCrudU (_ifcObj interf))
. setAttribute "crudD" (objCrudD (_ifcObj interf))
. setAttribute "verbose" (verboseP opts)
. setAttribute "usedTemplate" controlerTemplateName
; let filename = "ifc" ++ ifcName interf ++ ".controller.js"
; writePrototypeAppFile opts filename contents
}
where
opts = getOpts fSpec
------ Utility functions
-- data type to keep template and source file together for better errors
data Template = Template (StringTemplate String) String
-- TODO: better abstraction for specific template and fallback to default
doesTemplateExist :: FSpec -> String -> IO Bool
doesTemplateExist fSpec templatePath =
do { let absPath = getTemplateDir fSpec </> templatePath
; doesFileExist absPath
}
readTemplate :: FSpec -> String -> IO Template
readTemplate fSpec templatePath =
do { let absPath = getTemplateDir fSpec </> templatePath
; res <- readUTF8File absPath
; case res of
Left err -> error $ "Cannot read template file " ++ templatePath ++ "\n" ++ err
Right templateStr -> return $ Template (newSTMP templateStr) absPath
}
-- having Bool attributes prevents us from using a [(String, String)] parameter for attribute settings
renderTemplate :: Template -> (StringTemplate String -> StringTemplate String) -> String
renderTemplate (Template template absPath) setAttrs =
let appliedTemplate = setAttrs template
in case checkTemplateDeep appliedTemplate of
([], [], []) -> render appliedTemplate
(parseErrs@(_:_), _, _) -> templateError $ concat [ "Parse error in " ++ tmplt ++ " " ++ err ++ "\n"
| (tmplt,err) <- parseErrs]
([], attrs@(_:_), _) -> templateError $ "The following attributes are expected by the template, but not supplied: " ++ show attrs
([], [], ts@(_:_)) -> templateError $ "Missing invoked templates: " ++ show ts -- should not happen as we don't invoke templates
where templateError msg = error $ "\n\n*** TEMPLATE ERROR in:\n" ++ absPath ++ "\n\n" ++ msg
downloadPrototypeFramework :: Options -> IO Bool
downloadPrototypeFramework opts =
(do
x <- allowExtraction
if x
then do
verboseLn opts $ "Emptying folder to deploy prototype framework"
destroyDestinationDir
verboseLn opts "Start downloading prototype framework."
response <-
parseRequest ("https://github.com/AmpersandTarski/Prototype/archive/"++zwolleVersion opts++".zip") >>=
httpBS
let archive = removeTopLevelFolder
. toArchive
. BL.fromStrict
. getResponseBody $ response
verboseLn opts "Start extraction of prototype framework."
let zipoptions =
[OptVerbose | verboseP opts]
++ [OptDestination destination]
extractFilesFromArchive zipoptions archive
writeFile (destination </> ".frameworkSHA")
(show . zComment $ archive)
return x
else return x
) `catch` \err -> -- git failed to execute
exitWith . FailedToInstallPrototypeFramework $
[ "Error encountered during deployment of prototype framework:"
, show (err :: SomeException)
]
where
destination = dirPrototype opts
destroyDestinationDir :: IO ()
destroyDestinationDir = removeDirectoryRecursive destination
removeTopLevelFolder :: Archive -> Archive
removeTopLevelFolder archive =
archive{zEntries = mapMaybe removeTopLevelPath . zEntries $ archive}
where
removeTopLevelPath :: Entry -> Maybe Entry
removeTopLevelPath entry =
case tail . splitPath . eRelativePath $ entry of
[] -> Nothing
xs -> Just entry{eRelativePath = joinPath xs}
allowExtraction :: IO Bool
allowExtraction = do
pathExist <- doesPathExist destination
destIsDirectory <- doesDirectoryExist destination
if pathExist
then
if destIsDirectory
then do
dirContents <- listDirectory destination
let emptyDir = null dirContents
let forceReinstall = forceReinstallFramework opts
if emptyDir
then return True
else do
if forceReinstall
then do
putStrLn "Deleting all files to deploy prototype framework in"
putStrLn (" " ++ destination)
putStrLn "Are you sure? y/n"
proceed <- promptUserYesNo
return proceed
else do
(verboseLn opts $
"(Re)deploying prototype framework not allowed, because\n"
++ " "++destination++" isn't empty. You could use the switch --force-reinstall-framework")
return False
else do
verboseLn opts $
"(Re)deploying prototype framework not allowed, because\n"
++ " "++destination++" isn't a directory."
return False
else return True
promptUserYesNo :: IO Bool
promptUserYesNo = do
char <- getChar -- TODO: refactor that the first character is directly processed
case toUpper char of
'Y' -> return True
'N' -> return False
_ -> do when (char /= '\n') $ putStrLn "Please specify y/n" -- Remove 'when' part if first char it directly processed
x <- promptUserYesNo
return x
|
AmpersandTarski/ampersand
|
src/Ampersand/Prototype/GenFrontend.hs
|
gpl-3.0
| 27,492
| 3
| 31
| 10,017
| 5,175
| 2,659
| 2,516
| 410
| 12
|
module Examples.Windowing.QDSL where
import Prelude hiding (Int,pi,div,foldl,map,replicate,zipWith)
import QFeldspar.QDSL
import Examples.Prelude.QDSL
windowingVec :: Qt (Vec (Complex Float) -> Vec (Complex Float))
windowingVec = [|| \ (Vec ll f) -> let l = ll in
$$zipWith (*)
($$append
($$replicate (l - (div l 4)) (1.0 :+ 0.0))
($$replicate l (0.0 :+ 0.0)))
(Vec l (\ x -> f x)) ||]
windowing :: Qt (Ary (Complex Float) -> Ary (Complex Float))
windowing = [|| $$toArrF $$windowingVec ||]
|
shayan-najd/QFeldspar
|
Examples/Windowing/QDSL.hs
|
gpl-3.0
| 608
| 4
| 18
| 192
| 249
| 134
| 115
| -1
| -1
|
module Database.Sedna where
import Database.SednaBindings
import Database.SednaTypes
import Control.Exception
import Data.ByteString.Char8
import Data.Text (Text)
import qualified Data.Text as Text
-------------------------------------------------------------------------------
withTransaction :: SednaConnection -> (SednaConnection -> IO a) -> IO a
withTransaction conn func =
do
sednaBegin conn
r <- onException (func conn) doRollback
sednaCommit conn
return r
where doRollback =
Control.Exception.catch (sednaRollBack conn) doRollbackHandler
-- Discard any exception from (sednaRollBack conn) so original
-- exception can be re-raised
doRollbackHandler :: SomeException -> IO ()
doRollbackHandler _ = return ()
-------------------------------------------------------------------------------
loadXMLFile :: SednaConnection -> FilePath -> Document -> Collection -> IO ()
loadXMLFile conn path doc coll = withTransaction conn $
(\conn' -> sednaLoadFile conn' path doc coll)
-------------------------------------------------------------------------------
loadString conn str doc coll =
withTransaction conn $ (\conn' -> sednaLoadData conn' (pack str) doc coll)
-------------------------------------------------------------------------------
version :: SednaConnection -> IO Text
version conn = withTransaction conn $ (\conn' -> do
sednaExecute conn' "doc ('$version')"
sednaGetResult conn')
|
ExternalReality/SednaDBXML
|
src/Database/Sedna.hs
|
gpl-3.0
| 1,713
| 0
| 10
| 472
| 328
| 168
| 160
| 27
| 1
|
{-# LANGUAGE RecordWildCards, OverloadedStrings #-}
import Prelude hiding (takeWhile)
import Control.Concurrent (forkIO)
import Control.Monad (forever, (>=>), void)
import Data.Default (Default(def))
import Data.List (partition)
import Data.Maybe
import System.Environment (getArgs)
import System.Timeout (timeout)
import Network.Socket.ByteString (sendAll, sendAllTo, recvFrom)
import Network.Socket hiding (recvFrom)
import Network.DNS
import Data.Attoparsec.Char8 -- TODO: This is deprecated. What's the correct way of doing stuff?
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy as BL
data Conf = Conf
{ bufSize :: Int
, timeOut :: Int
, nameservers :: [HostName]
}
instance Default Conf where
def = Conf
{ bufSize = 512
, timeOut = 10 * 1000 * 1000
, nameservers = []
}
toEither :: a -> Maybe b -> Either a b
toEither a = maybe (Left a) Right
filterIPs :: DNSMessage -> DNSMessage
filterIPs DNSMessage{..} =
DNSMessage { header = header -- TODO: Use lens to simplify this update
, answer = case filter not52 answer of
[] -> answer
ips -> ips
, question = question
, authority = authority
, additional = additional }
where
not52 :: ResourceRecord -> Bool
not52 ResourceRecord{..} = -- TODO: These patterns should be refactored
case rdata of
RD_A ip -> Prelude.take 2 (show ip) /= "52"
_ -> True
not52 _ = True
{-- Proxy dns request to a real dns server. --}
proxyRequest :: Conf -> HostName -> DNSMessage -> IO (Either String DNSMessage)
proxyRequest Conf{..} server req = do
let rc = defaultResolvConf { resolvInfo = RCHostName server }
worker Resolver{..} = do
let packet = B.concat . BL.toChunks $ encode req
sendAll dnsSock packet
receive dnsSock
rs <- makeResolvSeed rc
withResolver rs $ \r ->
(toEither "proxy request timeout" >=> check >=> (Right . filterIPs))
<$> timeout timeOut (worker r)
where
ident = identifier . header $ req
check :: DNSMessage -> Either String DNSMessage
check rsp = let hdr = header rsp
in if identifier hdr == ident
then Right rsp
else Left "identifier not match"
{-- Handle A query for domain suffixes configured, and proxy other requests to
- a real dns server.
--}
handleRequest :: Conf -> DNSMessage -> IO (Either String DNSMessage)
handleRequest conf req =
case nameservers conf of
[] -> return $ Left "nameserver not configured."
srv:_ -> proxyRequest conf srv req
{-- Parse request and compose response. --}
handlePacket :: Conf -> Socket -> SockAddr -> B.ByteString -> IO ()
handlePacket conf@Conf{..} sock addr s =
case decode (BL.fromChunks [s]) of
Left errmsg -> putStrLn $ "decode fail:" ++ errmsg
Right req ->
handleRequest conf req >>=
either
putStrLn
(\rsp -> let packet = B.concat . BL.toChunks $ encode rsp
in timeout timeOut (sendAllTo sock packet addr) >>=
maybe (putStrLn "send response timeout") return
)
run :: Conf -> IO ()
run conf = withSocketsDo $ do
addrinfos <- getAddrInfo
(Just (defaultHints {addrFlags = [AI_PASSIVE]}))
Nothing (Just "domain")
addrinfo <- maybe (fail "no addr info") return (listToMaybe addrinfos)
sock <- socket (addrFamily addrinfo) Datagram defaultProtocol
bindSocket sock (addrAddress addrinfo)
forever $ do
(s, addr) <- recvFrom sock (bufSize conf)
forkIO $ handlePacket conf sock addr s
{-- parse config file. --}
readConf :: FilePath -> IO [HostName]
readConf filename = do
content <- B.readFile filename
either (fail . ("fail parsing conf: " ++)) return $ parseHosts content
where
parseHosts :: B.ByteString -> Either String [HostName]
parseHosts s = let (serverLines, _) = partition (B.isPrefixOf "nameserver") (B.lines s)
in mapM (parseOnly nameserver) serverLines
nameserver :: Parser HostName
nameserver = do
void $ string "nameserver"
void $ space
skipSpace
B.unpack <$> takeWhile (not . isSpace)
main :: IO ()
main = do
args <- getArgs
servers <- readConf $ fromMaybe "./resolv.conf" (listToMaybe args)
print servers
run def{nameservers=servers}
|
etandel/filter52
|
src/Main.hs
|
gpl-3.0
| 4,633
| 0
| 18
| 1,362
| 1,338
| 687
| 651
| 104
| 4
|
module State where
import Spieler
import Wurf
import Bank
import Chart
import Data.Acid
import Control.Concurrent.STM
import Control.Monad ( guard )
import Data.Time
import qualified Data.Map as M
import qualified Data.Set as S
import Text.PrettyPrint.HughesPJ
message_queue_length = 1000
protocol_messages_display_length = 50
game_messages_display_length = 50
data Message = Login Spieler Bool
| Callback_Mismatch Spieler Name
| Logout Spieler Bool
| Game [ Spieler ]
| Round [ Spieler ]
| Bid Wurf
| Game_Won_By Spieler
| Round_Lost_By Spieler
| Protocol_Error_By [ Spieler ]
| RPC_Call Spieler String
| RPC_Return_OK
| RPC_Error String
| Rating_Snapshot
| Taxman
deriving Show
is_game_message m = case m of
Game _ -> True
Round _ -> True
Bid _ -> True
Game_Won_By _ -> True
Round_Lost_By _ -> True
_ -> False
type Registry = M.Map Name Spieler
data Server = Server { registry :: TVar Registry
, passwords :: M.Map Name Password
, bank_lock :: TVar Bool
, bank :: AcidState Bank
, messages :: TVar [ ( UTCTime, Message ) ]
, offenders :: TVar ( S.Set Spieler )
, chart :: AcidState Chart
}
pretty :: [ (UTCTime, Message) ] -> Doc
pretty ums = contents ums $$ protocol ums
contents ums =
text "most recent (game) actions:" $$ nest 4 ( vcat
$ take game_messages_display_length $ do
(u, m) <- ums
guard $ is_game_message m
let sized n s = s ++ replicate ( n - length s ) ' '
return $ text ( sized 60 $ show m ) <+> text ( show u )
)
protocol ums =
text "most recent (protocol) actions:" $$ nest 4 ( vcat
$ take protocol_messages_display_length $ do
(u, m) <- ums
let sized n s = s ++ replicate ( n - length s ) ' '
return $ text ( sized 60 $ show m ) <+> text ( show u )
)
message :: Server -> Message -> IO ()
message s m = do
t <- getCurrentTime
atomically $ do
let p = messages s
ms <- readTVar p
writeTVar p $ take message_queue_length $ (t, m) : ms
print ( t, m )
make passwd_map = do
bank_state <- openLocalState $ Bank.empty
createCheckpoint bank_state
chart_state <- openLocalState $ Chart.empty
createCheckpoint chart_state
re <- atomically $ newTVar M.empty
os <- atomically $ newTVar S.empty
ms <- atomically $ newTVar []
lo <- atomically $ newTVar True
return $ Server { passwords = passwd_map
, registry = re, bank = bank_state, bank_lock = lo
, offenders = os , messages = ms
, chart = chart_state
}
|
jwaldmann/mex
|
src/State.hs
|
gpl-3.0
| 2,948
| 0
| 18
| 1,060
| 876
| 451
| 425
| 81
| 6
|
type Lst a = forall i. Monoid i => (a -> i) -> i
|
hmemcpy/milewski-ctfp-pdf
|
src/content/3.11/code/haskell/snippet04.hs
|
gpl-3.0
| 48
| 0
| 9
| 13
| 31
| 17
| 14
| -1
| -1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DFAReporting.Reports.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves list of reports.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.reports.list@.
module Network.Google.Resource.DFAReporting.Reports.List
(
-- * REST Resource
ReportsListResource
-- * Creating a Request
, reportsList
, ReportsList
-- * Request Lenses
, rlProFileId
, rlSortOrder
, rlScope
, rlPageToken
, rlSortField
, rlMaxResults
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.reports.list@ method which the
-- 'ReportsList' request conforms to.
type ReportsListResource =
"dfareporting" :>
"v2.7" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"reports" :>
QueryParam "sortOrder" ReportsListSortOrder :>
QueryParam "scope" ReportsListScope :>
QueryParam "pageToken" Text :>
QueryParam "sortField" ReportsListSortField :>
QueryParam "maxResults" (Textual Int32) :>
QueryParam "alt" AltJSON :> Get '[JSON] ReportList
-- | Retrieves list of reports.
--
-- /See:/ 'reportsList' smart constructor.
data ReportsList = ReportsList'
{ _rlProFileId :: !(Textual Int64)
, _rlSortOrder :: !ReportsListSortOrder
, _rlScope :: !ReportsListScope
, _rlPageToken :: !(Maybe Text)
, _rlSortField :: !ReportsListSortField
, _rlMaxResults :: !(Maybe (Textual Int32))
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ReportsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rlProFileId'
--
-- * 'rlSortOrder'
--
-- * 'rlScope'
--
-- * 'rlPageToken'
--
-- * 'rlSortField'
--
-- * 'rlMaxResults'
reportsList
:: Int64 -- ^ 'rlProFileId'
-> ReportsList
reportsList pRlProFileId_ =
ReportsList'
{ _rlProFileId = _Coerce # pRlProFileId_
, _rlSortOrder = RLSODescending
, _rlScope = Mine
, _rlPageToken = Nothing
, _rlSortField = RLSFLastModifiedTime
, _rlMaxResults = Nothing
}
-- | The DFA user profile ID.
rlProFileId :: Lens' ReportsList Int64
rlProFileId
= lens _rlProFileId (\ s a -> s{_rlProFileId = a}) .
_Coerce
-- | Order of sorted results, default is \'DESCENDING\'.
rlSortOrder :: Lens' ReportsList ReportsListSortOrder
rlSortOrder
= lens _rlSortOrder (\ s a -> s{_rlSortOrder = a})
-- | The scope that defines which results are returned, default is \'MINE\'.
rlScope :: Lens' ReportsList ReportsListScope
rlScope = lens _rlScope (\ s a -> s{_rlScope = a})
-- | The value of the nextToken from the previous result page.
rlPageToken :: Lens' ReportsList (Maybe Text)
rlPageToken
= lens _rlPageToken (\ s a -> s{_rlPageToken = a})
-- | The field by which to sort the list.
rlSortField :: Lens' ReportsList ReportsListSortField
rlSortField
= lens _rlSortField (\ s a -> s{_rlSortField = a})
-- | Maximum number of results to return.
rlMaxResults :: Lens' ReportsList (Maybe Int32)
rlMaxResults
= lens _rlMaxResults (\ s a -> s{_rlMaxResults = a})
. mapping _Coerce
instance GoogleRequest ReportsList where
type Rs ReportsList = ReportList
type Scopes ReportsList =
'["https://www.googleapis.com/auth/dfareporting"]
requestClient ReportsList'{..}
= go _rlProFileId (Just _rlSortOrder) (Just _rlScope)
_rlPageToken
(Just _rlSortField)
_rlMaxResults
(Just AltJSON)
dFAReportingService
where go
= buildClient (Proxy :: Proxy ReportsListResource)
mempty
|
rueshyna/gogol
|
gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/Reports/List.hs
|
mpl-2.0
| 4,621
| 0
| 18
| 1,119
| 727
| 421
| 306
| 101
| 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.AdSense.Metadata.Metrics.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- List the metadata for the metrics available to this AdSense account.
--
-- /See:/ <https://developers.google.com/adsense/management/ AdSense Management API Reference> for @adsense.metadata.metrics.list@.
module Network.Google.Resource.AdSense.Metadata.Metrics.List
(
-- * REST Resource
MetadataMetricsListResource
-- * Creating a Request
, metadataMetricsList
, MetadataMetricsList
) where
import Network.Google.AdSense.Types
import Network.Google.Prelude
-- | A resource alias for @adsense.metadata.metrics.list@ method which the
-- 'MetadataMetricsList' request conforms to.
type MetadataMetricsListResource =
"adsense" :>
"v1.4" :>
"metadata" :>
"metrics" :>
QueryParam "alt" AltJSON :> Get '[JSON] Metadata
-- | List the metadata for the metrics available to this AdSense account.
--
-- /See:/ 'metadataMetricsList' smart constructor.
data MetadataMetricsList =
MetadataMetricsList'
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'MetadataMetricsList' with the minimum fields required to make a request.
--
metadataMetricsList
:: MetadataMetricsList
metadataMetricsList = MetadataMetricsList'
instance GoogleRequest MetadataMetricsList where
type Rs MetadataMetricsList = Metadata
type Scopes MetadataMetricsList =
'["https://www.googleapis.com/auth/adsense",
"https://www.googleapis.com/auth/adsense.readonly"]
requestClient MetadataMetricsList'{}
= go (Just AltJSON) adSenseService
where go
= buildClient
(Proxy :: Proxy MetadataMetricsListResource)
mempty
|
brendanhay/gogol
|
gogol-adsense/gen/Network/Google/Resource/AdSense/Metadata/Metrics/List.hs
|
mpl-2.0
| 2,489
| 0
| 12
| 528
| 226
| 141
| 85
| 42
| 1
|
module SumFusion where
import Either
sumFusionLeft, sumFusionRight :: (c -> d) -> (a -> c) -> (b -> c) -> Either a b -> d
sumFusionLeft f g h = f . Either.either g h
sumFusionRight f g h = Either.either (f . g) (f . h)
sfl,sfl',sfr,sfr' :: Int
sfl = sumFusionLeft ((*10) . read) (show) (id) $ Left 3
sfl' = sumFusionLeft ((*10) . read) ((show)::Int -> String) (id) $ Right "3"
sfr = sumFusionRight ((*10) . read) (show) (id) $ Left 3
sfr' = sumFusionRight ((*10) . read) ((show)::Int -> String) (id) $ Right "3"
-- End
|
haroldcarr/learn-haskell-coq-ml-etc
|
haskell/book/2019-Program_Design_by_Calculation-Oliveira/2015-05-LambdaConf/SumFusion.hs
|
unlicense
| 592
| 0
| 9
| 173
| 288
| 162
| 126
| 10
| 1
|
module Git.Command.Branch (run) where
run :: [String] -> IO ()
run args = return ()
|
wereHamster/yag
|
Git/Command/Branch.hs
|
unlicense
| 84
| 0
| 7
| 15
| 42
| 23
| 19
| 3
| 1
|
module Coins.A263135 (derivative, a263135) where
import Helpers.ListHelpers (concatReplicate)
a263135 :: Int -> Integer
a263135 n = a263135_list !! n
a263135_list :: [Integer]
a263135_list = [0,0,1,2,3,4] ++ list where
list = scanl (+) 6 $ concatMap f derivative where
f k = replicate k 1 ++ [2]
derivative :: [Int]
derivative = [3, 2, 2, 2] ++ remainder 0
remainder :: Int -> [Int]
remainder n = sideA ++ sideB ++ sides ++ remainder (n + 1) where
sideA = 2 : replicate (n + 1) 1
sideB = 2 : replicate n 1
sides = concatReplicate 4 sideA
|
peterokagey/haskellOEIS
|
src/Coins/A263135.hs
|
apache-2.0
| 554
| 0
| 10
| 114
| 246
| 136
| 110
| 15
| 1
|
#!/usr/bin/env stack
-- stack runghc --resolver ghc-7.10.3
{-# LANGUAGE OverloadedStrings #-}
import System.Environment (getArgs)
import qualified Data.ByteString.Char8 as S
main :: IO ()
main = getArgs >>= mapM_ go
go :: FilePath -> IO ()
go fp = S.readFile fp >>= S.writeFile fp . S.unlines . go' . S.lines . S.filter (/= '\r')
go' :: [S.ByteString] -> [S.ByteString]
go' [] = []
go' ("<articleinfo>":rest) = drop 1 $ dropWhile (/= "</articleinfo>") rest
go' (x:xs) = x : go' xs
|
maxigit/yesodweb.com-content
|
book/tools/strip-article-info.hs
|
bsd-2-clause
| 484
| 0
| 11
| 82
| 192
| 102
| 90
| 11
| 1
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Controller
( withMySite
, withDevelApp
) where
import MySite
import Settings
import Yesod.Helpers.Static
import Yesod.Auth
import Database.Persist.GenericSql
import Data.ByteString (ByteString)
import Data.Dynamic (Dynamic, toDyn)
import Network.Wai (Application)
-- Import all relevant handler modules here.
import Handler.Root
import Handler.View
-- This line actually creates our YesodSite instance. It is the second half
-- of the call to mkYesodData which occurs in MySite.hs. Please see
-- the comments there for more details.
mkYesodDispatch "MySite" resourcesMySite
-- Some default handlers that ship with the Yesod site template. You will
-- very rarely need to modify this.
getFaviconR :: Handler ()
getFaviconR = sendFile "image/x-icon" "config/favicon.ico"
getRobotsR :: Handler RepPlain
getRobotsR = return $ RepPlain $ toContent ("User-agent: *" :: ByteString)
-- This function allocates resources (such as a database connection pool),
-- performs initialization and creates a WAI application. This is also the
-- place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
withMySite :: (Application -> IO a) -> IO a
withMySite f = Settings.withConnectionPool $ \p -> do
runConnectionPool (runMigration migrateAll) p
let h = MySite s p
toWaiApp h >>= f
where
s = static Settings.staticdir
withDevelApp :: Dynamic
withDevelApp = toDyn (withMySite :: (Application -> IO ()) -> IO ())
|
Tarrasch/Nollform
|
Controller.hs
|
bsd-2-clause
| 1,622
| 0
| 12
| 261
| 281
| 156
| 125
| 30
| 1
|
module Drasil.GamePhysics.Unitals where
import Language.Drasil
import Language.Drasil.ShortHands
import Data.Drasil.SI_Units(kilogram, metre, m_2, newton, second)
import qualified Data.Drasil.Concepts.Physics as CP (rigidBody)
import qualified Data.Drasil.Quantities.Physics as QP (acceleration, angularAccel,
angularDisplacement, angularVelocity, chgInVelocity, displacement, distance,
final, force, gravitationalAccel, gravitationalConst, gravitationalConstValue,
height, impulseS, impulseV, initial, kEnergy, linearAccel, linearDisplacement,
linearVelocity, momentOfInertia, position, potEnergy, restitutionCoef, time,
torque, velocity, fOfGravity, positionVec)
import qualified Data.Drasil.Quantities.Math as QM (euclidNorm, normalVect,
orientation, perpVect, pi_, unitVect)
import qualified Data.Drasil.Quantities.PhysicalProperties as QPP (len, mass)
import Data.Drasil.Units.Physics (accelU, angVelU, impulseU, momtInertU,
torqueU, velU)
import Control.Lens((^.))
import Data.Drasil.Constraints (gtZeroConstr)
defSymbols :: [DefinedQuantityDict]
defSymbols = map dqdWr unitSymbs ++ map dqdWr inputConstraints ++
map dqdWr outputConstraints
unitSymbs :: [UnitaryConceptDict]
unitSymbs = map ucw unitalChunks ++ map ucw [iVect, jVect, normalVect,
force_1, force_2, forceI, mass_1, mass_2,
dispNorm, sqrDist, velA, velB, velO, rOB, angVelA, angVelB,
posCM, massI, posI, accI, mTot, velI, torqueI, timeC, initRelVel,
massA, massB, massIRigidBody, normalLen, contDispA, contDispB,
perpLenA, momtInertA, perpLenB, momtInertB, timeT, inittime,
momtInertK, pointOfCollision, contDispK, collisionImpulse, velAP,
velBP, time_1, time_2, velo_1, velo_2, rRot, mLarger, distMass, dVect]
----------------------
-- TABLE OF SYMBOLS --
----------------------
symbols, symbolsAll, inputSymbols, outputSymbols :: [QuantityDict]
symbolsAll = symbols ++ inputSymbols ++ outputSymbols
symbols = map qw unitalChunks ++
map qw unitless ++
map qw inputConstraints
inputSymbols = map qw [QP.position, QP.velocity, QP.force, QM.orientation,
QP.angularVelocity, QP.linearVelocity, QP.gravitationalConst, QPP.mass,
QPP.len, QP.momentOfInertia, QP.torque, QP.kEnergy, QP.chgInVelocity, QP.potEnergy, QP.fOfGravity, QP.positionVec] ++
[qw QP.restitutionCoef]
outputSymbols = map qw [QP.position, QP.velocity, QM.orientation,
QP.angularVelocity]
unitalChunks :: [UnitalChunk]
unitalChunks = [QP.acceleration, QP.angularAccel, QP.gravitationalAccel,
QP.impulseV, QP.impulseS, iVect, jVect, normalVect, QP.distance, QP.displacement,
QP.time, QP.angularDisplacement, posCM, posI, massI, mTot, accI, velI,
QP.linearDisplacement, QP.linearVelocity, QP.linearAccel, initRelVel, normalLen,
perpLenA, perpLenB, forceI, torqueI, timeC, velA, velB, massA, massB,
angVelA, angVelB, force_1, force_2, mass_1, mass_2,
dispNorm, sqrDist, velO, rOB, massIRigidBody, contDispA, contDispB,
momtInertA, momtInertB, timeT, inittime, momtInertK, pointOfCollision,
contDispK, collisionImpulse, QP.kEnergy, finRelVel, velAP, velBP, time_1, time_2, velo_1, velo_2,
QP.chgInVelocity, QP.potEnergy, QP.height, rRot, mLarger, QP.fOfGravity, QP.positionVec, distMass, dVect]
-----------------------
-- PARAMETRIZED HACK --
-----------------------
--FIXME: parametrized hack
--FIXME: "A" is not being capitalized when it should be.
forceParam, massParam, timeParam :: String -> String -> Symbol -> UnitalChunk
forceParam n w s = ucs'
(dccWDS ("force" ++ n) (cn $ "force exerted by the " ++ w ++
" body (on another body)") (phrase QP.force))
(sub (eqSymb QP.force) s) Real newton
massParam n w s = ucs'
(dccWDS ("mass" ++ n) (cn $ "mass of the " ++ w ++ " body")
(phrase QPP.mass)) (sub (eqSymb QPP.mass) s) Real kilogram
timeParam n w s = ucs'
(dccWDS ("time" ++ n) (cn $ "time at a point in " ++ w ++ " body ")
(phrase QP.time)) (sub (eqSymb QP.time) s) Real second
contParam :: String -> String -> Symbol -> Symbol -> UnitalChunk
contParam n m w s = ucs'
(dccWDS ("r_" ++ n ++ m) contdispN (phrase QP.displacement))
(sub (eqSymb QP.displacement) (Concat [w, s])) Real metre
where contdispN = cn $ "displacement vector between the centre of mass of rigid body " ++
n ++ " and contact point " ++ m
angParam, momtParam, perpParam, rigidParam, velBodyParam, velParam :: String -> Symbol -> UnitalChunk
angParam n w = ucs'
(dccWDS ("angular velocity" ++ n) (compoundPhrase'
(cn $ n ++ " body's") (QP.angularVelocity ^. term))
(phrase QP.angularVelocity)) (sub (eqSymb QP.angularVelocity) w) Real angVelU
momtParam n w = ucs'
(dccWDS ("momentOfInertia" ++ n) (compoundPhrase'
(QP.momentOfInertia ^. term) (cn $ "of rigid body " ++ n))
(phrase QP.momentOfInertia)) (sub (eqSymb QP.momentOfInertia) w) Real momtInertU
perpParam n w = ucs'
(dccWDS ("|| r_A" ++ n ++ " x n ||")
(compoundPhrase' (compoundPhrase (cn' "length of the") (QM.perpVect ^. term))
(cn $ "to the contact displacement vector of rigid body " ++ n))
(phrase QM.perpVect)) (Concat [Label "||", w, Label "*", --should be x for cross
eqSymb QM.perpVect, Label "||"]) Real metre
rigidParam n w = ucs'
(dccWDS ("rig_mass" ++ n) (compoundPhrase' (QPP.mass ^. term)
(cn $ "of rigid body " ++ n)) (phrase QPP.mass)) (sub (eqSymb QPP.mass) w) Real kilogram
velBodyParam n w = ucs'
(dccWDS ("velocity" ++ n) (compoundPhrase' (QP.velocity ^. term)
(cn $ "of the " ++ n ++ " body")) (phrase QP.velocity)) (sub (eqSymb QP.velocity) w) Real velU
velParam n w = ucs'
(dccWDS ("velocity" ++ n) ( compoundPhrase' (QP.velocity ^. term)
(cn $ "at point " ++ n)) (phrase QP.velocity)) (sub (eqSymb QP.velocity) w) Real velU
-----------------------
-- CHUNKS WITH UNITS --
-----------------------
iVect, jVect, normalVect, force_1, force_2, forceI, mass_1, mass_2,
dispNorm, sqrDist, velA, velB, velO, rOB, angVelA, angVelB,
posCM, massI, posI, accI, mTot, velI, torqueI, timeC, initRelVel,
massA, massB, massIRigidBody, normalLen, contDispA, contDispB,
perpLenA, momtInertA, perpLenB, momtInertB, timeT, inittime,
momtInertK, pointOfCollision, contDispK, collisionImpulse, finRelVel,
velAP, velBP, time_1, time_2, velo_1, velo_2, rRot, mLarger, distMass, dVect :: UnitalChunk
iVect = ucs' (dccWDS "unitVect" (compoundPhrase' (cn "horizontal")
(QM.unitVect ^. term)) (phrase QM.unitVect))
(eqSymb QM.unitVect) Real metre
jVect = ucs' (dccWDS "unitVectJ" (compoundPhrase' (cn "vertical")
(QM.unitVect ^. term)) (phrase QM.unitVect)) (vec $ hat lJ) Real metre
normalVect = ucs' (dccWDS "normalVect" (compoundPhrase' (cn "collision")
(QM.normalVect ^. term)) (phrase QM.normalVect))
(eqSymb QM.normalVect) Real metre
dVect = ucs' (dccWDS "unitVect"
(cn "unit vector directed from the center of the large mass to the center of the smaller mass")
(phrase QM.unitVect)) (vec (hat lD)) Real metre
dispNorm = ucs' (dccWDS "euclideanNormDisp" (cn "Euclidean norm of the distance between the center of mass of two bodies")
(phrase QM.euclidNorm) ) (eqSymb QM.euclidNorm) Real metre
distMass = ucs' (dccWDS "distMass" (cn "distance between the center of mass of the rigid bodies")
(phrase QP.distance)) (vec lD) Real metre
sqrDist = ucs' (dccWDS "euclideanNorm" (cn' "squared distance")
(phrase QM.euclidNorm)) (sup (eqSymb QM.euclidNorm)
label2) Real m_2
rOB = uc' "rOB"
(nounPhraseSP "displacement vector between the origin and point B")
"FIXME: Define this or remove the need for definitions"
(sub (eqSymb QP.displacement) (Concat [lOrigin, lBodyB])) metre
posCM = ucs "p_CM" (nounPhraseSP "Center of Mass")
--"mass-weighted average position of a rigid " ++
-- "body's particles")
"FIXME: Define this or remove the need for definitions"
(sub (eqSymb QP.position) lCMass) Real metre
massI = ucs' (dccWDS "m_j" (compoundPhrase' (QPP.mass ^. term)
(cn "of the j-th particle")) (phrase QPP.mass))
(sub (eqSymb QPP.mass) lJ) Real kilogram
posI = ucs' (dccWDS "p_j" (compoundPhrase' (QP.position ^. term)
(cn "vector of the j-th particle")) (phrase QP.position))
(sub (eqSymb QP.position) lJ) Real metre
accI = ucs' (dccWDS "accI" (compoundPhrase' (cn "the i-th body's")
(QP.acceleration ^. term)) (phrase QP.acceleration))
(sub (eqSymb QP.acceleration) lI) Real accelU
velI = ucs' (dccWDS "velI" (compoundPhrase' (QP.velocity ^. term)
(cn "of the i-th body's velocity")) (phrase QP.velocity))
(sub (eqSymb QP.velocity) lI) Real velU
torqueI = ucs' (dccWDS "torqueI"
(cn "torque applied to the i-th body")
(phrase QP.torque)) (sub (eqSymb QP.torque) lI) Real torqueU
mTot = ucs' (dccWDS "M_T" (compoundPhrase' (cn "total mass of the")
(CP.rigidBody ^. term)) (phrase QPP.mass))
(sub (eqSymb QPP.mass) cT) Real kilogram
mLarger = ucs' (dccWDS "mLarger" (compoundPhrase' (cn "mass of the larger")
(CP.rigidBody ^. term)) (phrase QPP.mass)) cM Real kilogram
timeC = ucs' (dccWDS "timeC" (cn "denotes the time at collision")
(phrase QP.time)) (sub (eqSymb QP.time) lColl) Real second
initRelVel = ucs' (dccWDS "v_i^AB" (compoundPhrase'
(compoundPhrase' (cn "initial relative") (QP.velocity ^. term))
(cn "between rigid bodies of A and B")) (phrase QP.velocity))
(sup (sub (eqSymb QP.velocity) QP.initial) (Concat [lBodyA, lBodyB])) Real velU
finRelVel = ucs' (dccWDS "v_f^AB" (compoundPhrase'
(compoundPhrase' (cn "final relative") (QP.velocity ^. term))
(cn "between rigid bodies of A and B")) (phrase QP.velocity))
(sup (sub (eqSymb QP.velocity) QP.final) (Concat [lBodyA, lBodyB])) Real velU
massIRigidBody = ucs' (dccWDS "massI" (compoundPhrase' (QPP.mass ^. term)
(cn "of the i-th rigid body")) (phrase QPP.mass))
(sub (eqSymb QPP.mass) lI) Real kilogram
normalLen = ucs' (dccWDS "length of the normal vector" (compoundPhrase'
(cn "length of the") (QM.normalVect ^. term))
(phrase QM.normalVect))
(Concat [Label "||", eqSymb QM.normalVect, Label "||"]) Real metre
rRot = ucs' (dccWDS "r_j" (compoundPhrase' (QP.distance ^. term)
(cn "between the j-th particle and the axis of rotation")) (phrase QP.distance))
(sub (eqSymb QP.distance) lJ) Real metre
timeT = ucs' (dccWDS "t" (cn "point in time") (phrase QP.time))
(eqSymb QP.time) Real second
inittime = ucs' (dccWDS "t_0" (cn "denotes the initial time")
(phrase QP.time)) (sub (eqSymb QP.time) label0) Real second
pointOfCollision = ucs' (dccWDS "point_c" (cn "point of collision")
(S "point")) cP Real metre
collisionImpulse = ucs' (dccWDS "collisionImp" (compoundPhrase'
(cn "collision") (QP.impulseS ^. term)) (phrase QP.impulseS))
(eqSymb QP.impulseS) Real impulseU
forceI = ucs' (dccWDS "forceI" (compoundPhrase'
(QP.force ^. term) (cn "applied to the i-th body at time t"))
(phrase QP.force)) (sub (eqSymb QP.force) lI) Real newton
velAP = ucs' (dccWDS "v^AP" (compoundPhrase' (QP.velocity ^. term)
(cn "of the point of collision P in body A"))
(phrase QP.velocity)) (sup (eqSymb QP.velocity)(Concat [lBodyA, lPoint])) Real velU
velBP = ucs' (dccWDS "v^BP" (compoundPhrase' (QP.velocity ^. term)
(cn "of the point of collision P in body B"))
(phrase QP.velocity)) (sup (eqSymb QP.velocity)(Concat [lBodyB, lPoint])) Real velU
force_1 = forceParam "1" "first" label1
force_2 = forceParam "2" "second" label2
mass_1 = massParam "1" "first" label1
mass_2 = massParam "2" "second" label2
velA = velParam "A" lBodyA
velB = velParam "B" lBodyB
velO = velParam "origin" lOrigin
angVelA = angParam "A" lBodyA
angVelB = angParam "B" lBodyB
perpLenA = perpParam "A" $ eqSymb contDispA
perpLenB = perpParam "B" $ eqSymb contDispB
momtInertA = momtParam "A" lBodyA
momtInertB = momtParam "B" lBodyB
momtInertK = momtParam "k" lK
contDispA = contParam "A" "P" lBodyA lPoint
contDispB = contParam "B" "P" lBodyB lPoint
contDispK = contParam "k" "P" lK lPoint
massA = rigidParam "A" lBodyA
massB = rigidParam "B" lBodyB
velo_1 = velBodyParam "first" label1
velo_2 = velBodyParam "second" label2
time_1 = timeParam "1" "first" label1
time_2 = timeParam "2" "second" label2
label0, label1, label2, lBodyA, lBodyB, lCMass, lColl, lOrigin, lPoint :: Symbol
label0 = Integ 0
label1 = Integ 1
label2 = Integ 2
lBodyA = Label "A"
lBodyB = Label "B"
lCMass = Label "CM"
lColl = Label "c"
lOrigin = Label "O"
lPoint = Label "P"
--------------------------
-- CHUNKS WITHOUT UNITS --
--------------------------
unitless :: [QuantityDict]
unitless = qw QM.pi_ : [numParticles]
numParticles :: QuantityDict
numParticles = vc "n" (nounPhraseSP "number of particles in a rigid body") lN Integer
-----------------------
-- CONSTRAINT CHUNKS --
-----------------------
lengthCons, massCons, mmntOfInCons, gravAccelCons, posCons, orientCons,
angVeloCons, forceCons, torqueCons, veloCons, restCoefCons, veloOutCons,
angVeloOutCons, orientOutCons, posOutCons :: ConstrConcept
inputConstraints :: [UncertQ]
inputConstraints = map (`uq` defaultUncrt)
[lengthCons, massCons, mmntOfInCons, gravAccelCons, orientCons,
veloCons, angVeloCons, forceCons, torqueCons, restCoefCons, posCons]
outputConstraints :: [UncertQ]
outputConstraints = map (`uq` defaultUncrt)
[posOutCons, veloOutCons, orientOutCons, angVeloOutCons]
lengthCons = constrained' QPP.len [gtZeroConstr] (dbl 44.2)
massCons = constrained' QPP.mass [gtZeroConstr] (dbl 56.2)
mmntOfInCons = constrained' QP.momentOfInertia [gtZeroConstr] (dbl 74.5)
gravAccelCons = constrained' QP.gravitationalConst [] (QP.gravitationalConstValue ^. defnExpr)
posCons = constrained' QP.position [] (dbl 0.412) --FIXME: should be (0.412, 0.502) vector
veloCons = constrained' QP.velocity [] (dbl 2.51)
orientCons = constrained' QM.orientation [physc $ Bounded (Inc, 0) (Inc, 2 * sy QM.pi_)] (sy QM.pi_ / 2) -- physical constraint not needed space is radians
angVeloCons = constrained' QP.angularVelocity [] (dbl 2.1)
forceCons = constrained' QP.force [] (dbl 98.1)
torqueCons = constrained' QP.torque [] (dbl 200)
restCoefCons = constrained' QP.restitutionCoef [physc $ Bounded (Inc,0) (Inc,1)] (dbl 0.8)
posOutCons = constrained' QP.position [] (dbl 0.0)
veloOutCons = constrained' QP.velocity [] (dbl 0.0)
orientOutCons = constrained' QM.orientation [physc $ Bounded (Inc, 0) (Inc, 2 * sy QM.pi_)] (dbl 0)
angVeloOutCons = constrained' QP.angularVelocity [] (dbl 0.0)
---------------------
-- INSTANCE MODELS --
---------------------
---------------------
-- GOAL STATEMENTS --
---------------------
|
JacquesCarette/literate-scientific-software
|
code/drasil-example/Drasil/GamePhysics/Unitals.hs
|
bsd-2-clause
| 15,407
| 0
| 14
| 3,216
| 4,843
| 2,685
| 2,158
| 245
| 1
|
{- Directive to allow Text and String to be mixed -}
{-# LANGUAGE OverloadedStrings #-}
module Dropbox.Types.Content (Content(..)) where
import Data.Aeson ((.:), (.:?), decode, eitherDecode, FromJSON(..), Value(..))
import Control.Applicative ((<$>), (<*>))
import Data.Attoparsec.Number (Number(..))
{-
{
"size": "0 bytes",
"rev": "35c1f029684fe",
"thumb_exists": false,
"bytes": 0,
"modified": "Mon, 18 Jul 2011 20:13:43 +0000",
"client_mtime": "Wed, 20 Apr 2011 16:20:19 +0000",
"path": "/Public/latest.txt",
"is_dir": false,
"icon": "page_white_text",
"root": "dropbox",
"mime_type": "text/plain",
"revision": 220191
}
-}
data Content = Content { size :: String
, rev :: String
, thumbExists :: Bool
, bytes :: Int
, modified :: String
, clientMTime :: String
, path :: String
, isDir :: Bool
, icon :: String
, root :: String
, mimeType :: String
} deriving (Show)
instance FromJSON Content where
parseJSON (Object v) =
Content <$>
(v .: "size") <*>
(v .: "rev") <*>
(v .: "thumb_exists") <*>
(v .: "bytes") <*>
(v .: "modified") <*>
(v .: "client_mtime") <*>
(v .: "path") <*>
(v .: "is_dir") <*>
(v .: "icon") <*>
(v .: "root") <*>
(v .: "mime_type")
|
tinkhaven/haskell-dropbox-api
|
Dropbox/Types/Content.hs
|
bsd-3-clause
| 2,015
| 0
| 18
| 1,034
| 313
| 192
| 121
| 31
| 0
|
{-# LANGUAGE Rank2Types #-}
-----------------------------------------------------------------------------
-- |
-- Module : Codec.Compression.Zlib.Lens
-- Copyright : (C) 2012-14 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : provisional
-- Portability : portable
--
-- @lens@ support for the @zlib@ library
----------------------------------------------------------------------------
module Codec.Compression.Zlib.Lens
( -- * High-Level API
gzipped,
zlibbed,
deflated,
compressed,
Format,
gzip,
zlib,
deflate,
-- * Low-Level API
zlibbed',
gzipped',
deflated',
compressed',
Params,
defaultParams,
levelC,
methodC,
windowBitsC,
windowBitsD,
memoryLevelC,
strategyC,
bufferSizeC,
bufferSizeD,
dictionary,
CompressionLevel,
defaultCompression,
noCompression,
bestSpeed,
bestCompression,
compressionLevel,
Method,
deflateMethod,
WindowBits,
defaultWindowBits,
windowBits,
MemoryLevel,
defaultMemoryLevel,
minMemoryLevel,
maxMemoryLevel,
memoryLevel,
CompressionStrategy,
defaultStrategy,
filteredStrategy,
huffmanOnlyStrategy
) where
import Control.Applicative
import Codec.Compression.Zlib.Internal
import Control.Lens
import qualified Data.ByteString as S (ByteString)
import qualified Data.ByteString.Lazy as L (ByteString)
-- |
-- The 'zlib' compression format.
zlib :: Format
zlib = zlibFormat
{-# INLINE zlib #-}
-- |
-- The 'gzip' compression format.
gzip :: Format
gzip = gzipFormat
{-# INLINE gzip #-}
-- |
-- The 'deflate' compression format.
deflate :: Format
deflate = rawFormat
{-# INLINE deflate #-}
-- |
-- Compresses a 'L.ByteString' using the 'gzip' compression format.
--
-- @
-- 'gzipped' = 'compressed' 'gzip'
-- 'gzipped' = 'gzipped'' 'defaultParams'
-- @
gzipped :: Iso' L.ByteString L.ByteString
gzipped = compressed gzip
{-# INLINE gzipped #-}
-- |
-- Compresses a 'L.ByteString' using the 'zlib' compression format.
--
-- @
-- 'zlibbed' = 'compressed' 'zlib'
-- 'zlibbed' = 'zlibbed\'' 'defaultParams'
-- @
zlibbed :: Iso' L.ByteString L.ByteString
zlibbed = compressed zlib
{-# INLINE zlibbed #-}
-- |
-- Compresses a 'L.ByteString' using the 'deflate' compression format.
--
-- @
-- 'deflated' = 'compressed' 'deflate'
-- 'deflated' = 'deflated'' 'defaultParams'
-- @
deflated :: Iso' L.ByteString L.ByteString
deflated = compressed deflate
{-# INLINE deflated #-}
-- |
-- Compresses a 'L.ByteString' using the given compression format.
--
-- @
-- 'compressed' fmt = 'compressed'' fmt 'defaultParams'
-- @
compressed :: Format -> Iso' L.ByteString L.ByteString
compressed fmt = compressed' fmt defaultParams
{-# INLINE compressed #-}
-- |
-- Compresses a 'L.ByteString' using the 'gzip' compression format and the given advanced parameters.
--
-- @
-- 'gzipped' = 'compressed' 'gzip'
-- 'gzipped' = 'gzipped'' 'defaultParams'
-- @
gzipped' :: Params -> Iso' L.ByteString L.ByteString
gzipped' = compressed' gzip
{-# INLINE gzipped' #-}
-- |
-- Compresses a 'L.ByteString' using the 'zlib' compression format and the given advanced parameters.
--
-- @
-- 'zlibbed' = 'compressed' 'zlib'
-- 'zlibbed' = 'zlibbed'' 'defaultParams'
-- @
zlibbed' :: Params -> Iso' L.ByteString L.ByteString
zlibbed' = compressed' zlib
{-# INLINE zlibbed' #-}
-- |
-- Compresses a 'L.ByteString' using the 'deflate' compression format and the given advanced parameters.
--
-- @
-- 'deflated' = 'compressed' 'deflate'
-- 'deflated' = 'deflated'' 'defaultParams'
-- @
deflated' :: Params -> Iso' L.ByteString L.ByteString
deflated' = compressed' deflate
{-# INLINE deflated' #-}
-- |
-- Compresses a 'L.ByteString' using the given compression format and the given advanced parameters.
compressed' :: Format -> Params -> Iso' L.ByteString L.ByteString
compressed' fmt (Params c d) = iso (compress fmt c) (decompress fmt d)
{-# INLINE compressed' #-}
-- |
-- The advanced parameters needed by 'gzipped'', 'zlibbed'', 'deflated'', and 'compressed''.
--
-- Use 'defaultParams' and the provided 'Lens'es to construct custom 'Params'.
data Params = Params !CompressParams !DecompressParams
-- |
-- The default advanced parameters for compression and decompression.
defaultParams :: Params
defaultParams = Params defaultCompressParams defaultDecompressParams
{-# INLINE defaultParams #-}
-- |
-- The compression level.
levelC :: Lens' Params CompressionLevel
levelC = \ f (Params c d) -> (\l -> Params (c {compressLevel = l}) d) <$> f (compressLevel c)
{-# INLINE levelC #-}
-- |
-- The compression method.
methodC :: Lens' Params Method
methodC = \ f (Params c d) -> (\m -> Params (c {compressMethod = m}) d) <$> f (compressMethod c)
{-# INLINE methodC #-}
-- |
-- The number of bits in the compression window.
windowBitsC :: Lens' Params WindowBits
windowBitsC = \ f (Params c d) -> (\wb -> Params (c {compressWindowBits = wb}) d) <$> f (compressWindowBits c)
{-# INLINE windowBitsC #-}
-- |
-- The number of bits in the decompression window.
windowBitsD :: Lens' Params WindowBits
windowBitsD = \ f (Params c d) -> (\wb -> Params c (d {decompressWindowBits = wb})) <$> f (decompressWindowBits d)
{-# INLINE windowBitsD #-}
-- |
-- The amount of memory allowed for the internal compression state.
memoryLevelC :: Lens' Params MemoryLevel
memoryLevelC = \ f (Params c d) -> (\ml -> Params (c {compressMemoryLevel = ml}) d) <$> f (compressMemoryLevel c)
{-# INLINE memoryLevelC #-}
-- |
-- The compression strategy.
strategyC :: Lens' Params CompressionStrategy
strategyC = \ f (Params c d) -> (\s -> Params (c {compressStrategy = s}) d) <$> f (compressStrategy c)
{-# INLINE strategyC #-}
-- |
-- The initial buffer size during compression.
bufferSizeC :: Lens' Params Int
bufferSizeC = \ f (Params c d) -> (\bs -> Params (c {compressBufferSize = bs}) d) <$> f (compressBufferSize c)
{-# INLINE bufferSizeC #-}
-- |
-- The initial buffer size during decompression.
bufferSizeD :: Lens' Params Int
bufferSizeD = \ f (Params c d) -> (\bs -> Params c (d {decompressBufferSize = bs})) <$> f (decompressBufferSize d)
{-# INLINE bufferSizeD #-}
-- |
-- 'Just' the custom (de)compression dictionary to use, or 'Nothing' to not use a custom dictionary.
dictionary :: Lens' Params (Maybe S.ByteString)
dictionary = \f (Params c d) -> (\mbs -> Params (c {compressDictionary = mbs}) (d {decompressDictionary = mbs})) <$> f (compressDictionary c <|> decompressDictionary d)
{-# INLINE dictionary #-}
|
hvr/lens
|
src/Codec/Compression/Zlib/Lens.hs
|
bsd-3-clause
| 6,583
| 0
| 12
| 1,149
| 1,221
| 725
| 496
| 119
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import CodeGen
import Prelude hiding (take, drop, head, tail)
import Data.Text hiding (reverse, zip, filter)
import System.Environment
import Language.Haskell.Exts as HS hiding (prettyPrint)
-- main
main :: IO ()
main = do
args <- getArgs
case args of
[x] -> do
program <- fromParseResult `fmap` parseFile x
swift <- return $ transform program
putStrLn $ unpack swift
-- TODO: check file exits before writing
_ -> putStrLn "USAGE: file.swift.gen"
|
mxswd/swift-gen
|
main/Main.hs
|
bsd-3-clause
| 539
| 0
| 14
| 115
| 151
| 85
| 66
| 16
| 2
|
{-# LANGUAGE RankNTypes #-}
{-| An ST Monad based interface to the CUDD BDD library
This is a straightforward wrapper around the C library. See <http://vlsi.colorado.edu/~fabio/CUDD/> for documentation.
Exampe usage:
> import Control.Monad.ST
> import Cudd.Imperative
>
> main = do
> res <- stToIO $ withManagerDefaults $ \manager -> do
> v1 <- ithVar manager 0
> v2 <- ithVar manager 1
> conj <- bAnd manager v1 v2
> implies <- lEq manager conj v1
> deref manager conj
> return implies
> print res
-}
module Cudd.Imperative (
DDManager(..),
DDNode(..),
cuddInit,
cuddInitDefaults,
withManager,
withManagerDefaults,
withManagerIO,
withManagerIODefaults,
shuffleHeap,
bZero,
bOne,
ithVar,
bAnd,
bOr,
bNand,
bNor,
bXor,
bXnor,
bNot,
bIte,
bExists,
bForall,
deref,
setVarMap,
varMap,
lEq,
swapVariables,
ref,
largestCube,
makePrime,
support,
supportIndices,
indicesToCube,
computeCube,
nodesToCube,
readSize,
bddToCubeArray,
compose,
andAbstract,
xorExistAbstract,
leqUnless,
equivDC,
xEqY,
debugCheck,
checkKeys,
pickOneMinterm,
toInt,
checkZeroRef,
readInvPerm,
readPerm,
dagSize,
readNodeCount,
readPeakNodeCount,
regular,
readMaxCache,
readMaxCacheHard,
setMaxCacheHard,
readCacheSlots,
readCacheUsedSlots,
cudd_unique_slots,
cudd_cache_slots,
andLimit,
readTree,
newVarAtLevel,
liCompaction,
squeeze,
minimize,
newVar,
vectorCompose,
quit,
readIndex,
printMinterm,
checkCube,
Cube,
Prime,
DDGen(..),
genFree,
isGenEmpty,
firstCube,
nextCube,
firstPrime,
nextPrime,
module Cudd.Common
) where
import Foreign hiding (void)
import Foreign.Ptr
import Foreign.C.Types
import Control.Monad.ST
import Control.Monad.ST.Unsafe
import Control.Monad
import Control.Monad.IO.Class
import Data.List
import System.IO.Unsafe
import Cudd.C
import Cudd.MTR
import Cudd.Common
newtype DDManager s u = DDManager {unDDManager :: Ptr CDDManager}
newtype DDNode s u = DDNode {unDDNode :: Ptr CDDNode} deriving (Ord, Eq, Show)
cuddInit :: Int -> Int -> Int -> Int -> Int -> ST s (DDManager s u)
cuddInit numVars numVarsZ numSlots cacheSize maxMemory = unsafeIOToST $ do
cm <- c_cuddInit (fromIntegral numVars) (fromIntegral numVarsZ) (fromIntegral numSlots) (fromIntegral cacheSize) (fromIntegral maxMemory)
return $ DDManager cm
cuddInitDefaults :: ST s (DDManager s u)
cuddInitDefaults = cuddInit 0 0 cudd_unique_slots cudd_cache_slots 0
withManager :: Int -> Int -> Int -> Int -> Int -> (forall u. DDManager s u -> ST s a) -> ST s a
withManager numVars numVarsZ numSlots cacheSize maxMemory f = do
res <- cuddInit numVars numVarsZ numSlots cacheSize maxMemory
f res
withManagerDefaults :: (forall u. DDManager s u -> ST s a) -> ST s a
withManagerDefaults f = do
res <- cuddInitDefaults
f res
withManagerIO :: MonadIO m => Int -> Int -> Int -> Int -> Int -> (forall u. DDManager RealWorld u -> m a) -> m a
withManagerIO numVars numVarsZ numSlots cacheSize maxMemory f = do
res <- liftIO $ stToIO $ cuddInit numVars numVarsZ numSlots cacheSize maxMemory
f res
withManagerIODefaults :: MonadIO m => (forall u. DDManager RealWorld u -> m a) -> m a
withManagerIODefaults f = do
res <- liftIO $ stToIO cuddInitDefaults
f res
shuffleHeap :: DDManager s u -> [Int] -> ST s ()
shuffleHeap (DDManager m) order = unsafeIOToST $
withArrayLen (map fromIntegral order) $ \size ptr -> do
when (sort order /= [0..size-1]) (error "shuffleHeap: order does not contain each variable once")
res1 <- c_cuddBddIthVar m (fromIntegral (size - 1))
when (res1 == nullPtr) (error "shuffleHeap: Failed to resize table")
res2 <- c_cuddShuffleHeap m ptr
when (fromIntegral res2 /= 1) (error "shuffleHeap: Cudd_ShuffleHeap failed")
return ()
toInt :: DDNode s u -> Int
toInt (DDNode n) = fromIntegral $ ptrToIntPtr n
arg0 :: (Ptr CDDManager -> IO (Ptr CDDNode)) -> DDManager s u -> ST s (DDNode s u)
arg0 f (DDManager m) = liftM DDNode $ unsafeIOToST $ f m
arg1 :: (Ptr CDDManager -> Ptr CDDNode -> IO (Ptr CDDNode)) -> DDManager s u -> DDNode s u -> ST s (DDNode s u)
arg1 f (DDManager m) (DDNode x) = liftM DDNode $ unsafeIOToST $ f m x
arg2 :: (Ptr CDDManager -> Ptr CDDNode -> Ptr CDDNode -> IO (Ptr CDDNode)) -> DDManager s u -> DDNode s u -> DDNode s u -> ST s (DDNode s u)
arg2 f (DDManager m) (DDNode x) (DDNode y) = liftM DDNode $ unsafeIOToST $ f m x y
arg3 :: (Ptr CDDManager -> Ptr CDDNode -> Ptr CDDNode -> Ptr CDDNode -> IO (Ptr CDDNode)) -> DDManager s u -> DDNode s u -> DDNode s u -> DDNode s u -> ST s (DDNode s u)
arg3 f (DDManager m) (DDNode x) (DDNode y) (DDNode z) = liftM DDNode $ unsafeIOToST $ f m x y z
bZero, bOne :: DDManager s u -> DDNode s u
bZero (DDManager m) = DDNode $ unsafePerformIO $ c_cuddReadLogicZero m
bOne (DDManager m) = DDNode $ unsafePerformIO $ c_cuddReadOne m
bAnd = arg2 c_cuddBddAnd
bOr = arg2 c_cuddBddOr
bNand = arg2 c_cuddBddNand
bNor = arg2 c_cuddBddNor
bXor = arg2 c_cuddBddXor
bXnor = arg2 c_cuddBddXnor
bIte = arg3 c_cuddBddIte
bExists = arg2 c_cuddBddExistAbstract
bForall = arg2 c_cuddBddUnivAbstract
andAbstract = arg3 c_cuddBddAndAbstract
xorExistAbstract = arg3 c_cuddBddXorExistAbstract
bNot :: DDNode s u -> DDNode s u
bNot (DDNode x) = DDNode $ unsafePerformIO $ c_cuddNotNoRef x
ithVar :: DDManager s u -> Int -> ST s (DDNode s u)
ithVar (DDManager m) i = liftM DDNode $ unsafeIOToST $ c_cuddBddIthVar m (fromIntegral i)
deref :: DDManager s u -> DDNode s u -> ST s ()
deref (DDManager m) (DDNode x) = unsafeIOToST $ c_cuddIterDerefBdd m x
setVarMap :: DDManager s u -> [DDNode s u] -> [DDNode s u] -> ST s ()
setVarMap (DDManager m) xs ys = unsafeIOToST $
withArrayLen (map unDDNode xs) $ \xl xp ->
withArrayLen (map unDDNode ys) $ \yl yp -> do
when (xl /= yl) (error "setVarMap: lengths not equal")
void $ c_cuddSetVarMap m xp yp (fromIntegral xl)
varMap :: DDManager s u -> DDNode s u -> ST s (DDNode s u)
varMap (DDManager m) (DDNode x) = liftM DDNode $ unsafeIOToST $ c_cuddBddVarMap m x
lEq :: DDManager s u -> DDNode s u -> DDNode s u -> ST s Bool
lEq (DDManager m) (DDNode x) (DDNode y) = liftM (==1) $ unsafeIOToST $ c_cuddBddLeq m x y
swapVariables :: DDManager s u -> [DDNode s u] -> [DDNode s u] -> DDNode s u -> ST s (DDNode s u)
swapVariables (DDManager m) nodesx nodesy (DDNode x) = unsafeIOToST $
withArrayLen (map unDDNode nodesx) $ \lx xp ->
withArrayLen (map unDDNode nodesy) $ \ly yp -> do
when (lx /= ly) $ error "CuddExplicitDeref: shift: lengths not equal"
res <- c_cuddBddSwapVariables m x xp yp (fromIntegral lx)
return $ DDNode res
ref :: DDNode s u -> ST s ()
ref (DDNode x) = unsafeIOToST $ cuddRef x
largestCube :: DDManager s u -> DDNode s u -> ST s (DDNode s u, Int)
largestCube (DDManager m) (DDNode x) = unsafeIOToST $
alloca $ \lp -> do
res <- c_cuddLargestCube m x lp
l <- peek lp
return (DDNode res, fromIntegral l)
makePrime :: DDManager s u -> DDNode s u -> DDNode s u -> ST s (DDNode s u)
makePrime = arg2 c_cuddBddMakePrime
support :: DDManager s u -> DDNode s u -> ST s (DDNode s u)
support = arg1 c_cuddSupport
supportIndices :: DDManager s u -> DDNode s u -> ST s [Int]
supportIndices (DDManager m) (DDNode x) = unsafeIOToST $
alloca $ \arrp -> do
sz <- c_cuddSupportIndices m x arrp
aaddr <- peek arrp
res <- peekArray (fromIntegral sz) aaddr
return $ map fromIntegral res
indicesToCube :: DDManager s u -> [Int] -> ST s (DDNode s u)
indicesToCube (DDManager m) indices = unsafeIOToST $
withArrayLen (map fromIntegral indices) $ \sz pt -> do
res <- c_cuddIndicesToCube m pt (fromIntegral sz)
return $ DDNode res
computeCube :: DDManager s u -> [DDNode s u] -> [Bool] -> ST s (DDNode s u)
computeCube (DDManager m) nodes phases = unsafeIOToST $
withArrayLen (map unDDNode nodes) $ \szn ptn ->
withArrayLen (map (fromIntegral . fromBool) phases) $ \szp ptp -> do
when (szn /= szp) $ error "computeCube: lists are different lengths"
res <- c_cuddBddComputeCube m ptn ptp (fromIntegral szn)
return $ DDNode res
nodesToCube :: DDManager s u -> [DDNode s u] -> ST s (DDNode s u)
nodesToCube (DDManager m) nodes = unsafeIOToST $
withArrayLen (map unDDNode nodes) $ \sz pt -> do
res <- c_cuddBddComputeCube m pt nullPtr (fromIntegral sz)
return $ DDNode res
readSize :: DDManager s u -> ST s Int
readSize (DDManager m) = liftM fromIntegral $ unsafeIOToST $ c_cuddReadSize m
bddToCubeArray :: DDManager s u -> DDNode s u -> ST s [SatBit]
bddToCubeArray ma@(DDManager m) (DDNode x) = unsafeIOToST $ do
size <- liftM fromIntegral $ c_cuddReadSize m
allocaArray size $ \resptr -> do
c_cuddBddToCubeArray m x resptr
res <- peekArray size resptr
return $ map (toSatBit . fromIntegral) res
compose :: DDManager s u -> DDNode s u -> DDNode s u -> Int -> ST s (DDNode s u)
compose (DDManager m) (DDNode f) (DDNode g) v = liftM DDNode $ unsafeIOToST $ c_cuddBddCompose m f g (fromIntegral v)
arg3Bool :: (Ptr CDDManager -> Ptr CDDNode -> Ptr CDDNode -> Ptr CDDNode -> IO CInt) -> DDManager s u -> DDNode s u -> DDNode s u -> DDNode s u -> ST s Bool
arg3Bool f (DDManager m) (DDNode x) (DDNode y) (DDNode z) = liftM (==1) $ unsafeIOToST $ f m x y z
leqUnless, equivDC :: DDManager s u -> DDNode s u -> DDNode s u -> DDNode s u -> ST s Bool
leqUnless = arg3Bool c_cuddBddLeqUnless
equivDC = arg3Bool c_cuddEquivDC
xEqY :: DDManager s u -> [DDNode s u] -> [DDNode s u] -> ST s (DDNode s u)
xEqY (DDManager m) xs ys = unsafeIOToST $
withArrayLen (map unDDNode xs) $ \xl xp ->
withArrayLen (map unDDNode ys) $ \yl yp -> do
when (xl /= yl) (error "xeqy: lengths not equal")
res <- c_cuddXeqy m (fromIntegral xl) xp yp
return $ DDNode res
debugCheck :: DDManager s u -> ST s Int
debugCheck (DDManager m) = liftM fromIntegral $ unsafeIOToST $ c_cuddDebugCheck m
checkKeys :: DDManager s u -> ST s Int
checkKeys (DDManager m) = liftM fromIntegral $ unsafeIOToST $ c_cuddCheckKeys m
pickOneMinterm :: DDManager s u -> DDNode s u -> [DDNode s u] -> ST s (DDNode s u)
pickOneMinterm (DDManager m) (DDNode d) vars = unsafeIOToST $
withArrayLen (map unDDNode vars) $ \vl vp -> do
res <- c_cuddBddPickOneMinterm m d vp (fromIntegral vl)
return $ DDNode res
checkZeroRef :: DDManager s u -> ST s Int
checkZeroRef (DDManager m) = liftM fromIntegral $ unsafeIOToST $ c_cuddCheckZeroRef m
readInvPerm :: DDManager s u -> Int -> ST s Int
readInvPerm (DDManager m) offs = liftM fromIntegral $ unsafeIOToST $ c_cuddReadInvPerm m (fromIntegral offs)
readPerm :: DDManager s u -> Int -> ST s Int
readPerm (DDManager m) offs = liftM fromIntegral $ unsafeIOToST $ c_cuddReadPerm m (fromIntegral offs)
dagSize :: DDNode s u -> ST s Int
dagSize (DDNode d) = liftM fromIntegral $ unsafeIOToST $ c_cuddDagSize d
readNodeCount :: DDManager s u -> ST s Integer
readNodeCount (DDManager m) = liftM fromIntegral $ unsafeIOToST $ c_cuddReadNodeCount m
readPeakNodeCount :: DDManager s u -> ST s Integer
readPeakNodeCount (DDManager m) = liftM fromIntegral $ unsafeIOToST $ c_cuddReadPeakNodeCount m
regular :: DDNode s u -> DDNode s u
regular (DDNode x) = DDNode $ unsafePerformIO $ c_wrappedRegular x
readMaxCache :: DDManager s u -> ST s Int
readMaxCache (DDManager m) = liftM fromIntegral $ unsafeIOToST $ c_cuddReadMaxCache m
readMaxCacheHard :: DDManager s u -> ST s Int
readMaxCacheHard (DDManager m) = liftM fromIntegral $ unsafeIOToST $ c_cuddReadMaxCacheHard m
setMaxCacheHard :: DDManager s u -> Int -> ST s ()
setMaxCacheHard (DDManager m) x = unsafeIOToST $ c_cuddSetMaxCacheHard m (fromIntegral x)
readCacheSlots :: DDManager s u -> ST s Int
readCacheSlots (DDManager m) = liftM fromIntegral $ unsafeIOToST $ c_cuddReadCacheSlots m
readCacheUsedSlots :: DDManager s u -> ST s Int
readCacheUsedSlots (DDManager m) = liftM fromIntegral $ unsafeIOToST $ c_cuddReadCacheUsedSlots m
andLimit :: DDManager s u -> DDNode s u -> DDNode s u -> Int -> ST s (Maybe (DDNode s u))
andLimit (DDManager m) (DDNode x) (DDNode y) lim = unsafeIOToST $ do
res <- c_cuddBddAndLimit m x y (fromIntegral lim)
if res==nullPtr then
return Nothing
else do
cuddRef res
return $ Just $ DDNode res
readTree :: DDManager s u -> ST s (MtrNode s)
readTree (DDManager m) = liftM MtrNode $ unsafeIOToST $ c_cuddReadTree m
newVarAtLevel :: DDManager s u -> Int -> ST s (DDNode s u)
newVarAtLevel (DDManager m) level = liftM DDNode $ unsafeIOToST $ c_cuddBddNewVarAtLevel m (fromIntegral level)
liCompaction = arg2 c_cuddBddLICompaction
squeeze = arg2 c_cuddBddSqueeze
minimize = arg2 c_cuddBddMinimize
newVar :: DDManager s u -> ST s (DDNode s u)
newVar (DDManager m) = liftM DDNode $ unsafeIOToST $ c_cuddBddNewVar m
vectorCompose :: DDManager s u -> DDNode s u -> [DDNode s u] -> ST s (DDNode s u)
vectorCompose (DDManager m) (DDNode f) nodes = liftM DDNode $ unsafeIOToST $ withArrayLen (map unDDNode nodes) $ \len ptr -> do
sz <- c_cuddReadSize m
when (fromIntegral sz /= len) (error "vectorCompose: not one entry for each variable in manager")
c_cuddBddVectorCompose m f ptr
quit :: DDManager s u -> ST s ()
quit (DDManager m) = unsafeIOToST $ c_cuddQuit m
readIndex :: DDNode s u -> ST s Int
readIndex (DDNode x) = liftM fromIntegral $ unsafeIOToST $ c_cuddNodeReadIndex x
printMinterm :: DDManager s u -> DDNode s u -> ST s ()
printMinterm (DDManager m) (DDNode x) = unsafeIOToST $ c_cuddPrintMinterm m x
checkCube :: DDManager s u -> DDNode s u -> ST s Bool
checkCube (DDManager m) (DDNode x) = liftM (==1) $ unsafeIOToST $ c_cuddCheckCube m x
data Cube
data Prime
data DDGen s u t = DDGen (Ptr CDDGen)
genFree :: DDGen s u t -> ST s ()
genFree (DDGen g) = void $ unsafeIOToST $ c_cuddGenFree g
isGenEmpty :: DDGen s u t -> ST s Bool
isGenEmpty (DDGen g) = liftM (==1) $ unsafeIOToST $ c_cuddIsGenEmpty g
firstCube :: DDManager s u -> DDNode s u -> ST s (Maybe ([SatBit], DDGen s u Cube))
firstCube (DDManager m) (DDNode n) = unsafeIOToST $ do
sz <- c_cuddReadSize m
alloca $ \cubePP ->
alloca $ \valP -> do
gen <- c_cuddFirstCube m n cubePP valP
empty <- c_cuddIsGenEmpty gen
if empty == 1 then do
c_cuddGenFree gen
return Nothing
else do
cubeP <- peek cubePP
cube <- peekArray (fromIntegral sz) cubeP
return $ Just (map (toSatBit . fromIntegral) cube, DDGen gen)
nextCube :: DDManager s u -> DDGen s u Cube -> ST s (Maybe [SatBit])
nextCube (DDManager m) (DDGen g) = unsafeIOToST $ do
sz <- c_cuddReadSize m
alloca $ \cubePP ->
alloca $ \valP -> do
c_cuddNextCube g cubePP valP
empty <- c_cuddIsGenEmpty g
if empty == 1 then do
c_cuddGenFree g
return Nothing
else do
cubeP <- peek cubePP
cube <- peekArray (fromIntegral sz) cubeP
return $ Just $ map (toSatBit . fromIntegral) cube
firstPrime :: DDManager s u -> DDNode s u -> DDNode s u -> ST s (Maybe ([SatBit], DDGen s u Prime))
firstPrime (DDManager m) (DDNode x) (DDNode y) = unsafeIOToST $ do
sz <- c_cuddReadSize m
alloca $ \cubePP -> do
gen <- c_cuddFirstPrime m x y cubePP
empty <- c_cuddIsGenEmpty gen
if empty == 1 then do
c_cuddGenFree gen
return Nothing
else do
cubeP <- peek cubePP
cube <- peekArray (fromIntegral sz) cubeP
return $ Just (map (toSatBit . fromIntegral) cube, DDGen gen)
nextPrime :: DDManager s u -> DDGen s u Prime -> ST s (Maybe [SatBit])
nextPrime (DDManager m) (DDGen g) = unsafeIOToST $ do
sz <- c_cuddReadSize m
alloca $ \cubePP -> do
c_cuddNextPrime g cubePP
empty <- c_cuddIsGenEmpty g
if empty == 1 then do
c_cuddGenFree g
return Nothing
else do
cubeP <- peek cubePP
cube <- peekArray (fromIntegral sz) cubeP
return $ Just $ map (toSatBit . fromIntegral) cube
|
maweki/haskell_cudd
|
Cudd/Imperative.hs
|
bsd-3-clause
| 16,491
| 0
| 22
| 3,951
| 6,344
| 3,090
| 3,254
| -1
| -1
|
module Rotate where
import Tip.Prelude
import qualified Prelude
rotate :: Nat -> [a] -> [a]
rotate Z xs = xs
rotate (S _) [] = []
rotate (S n) (x:xs) = rotate n (xs ++ [x])
rotlen xs = rotate (length xs) xs === xs
|
danr/emna
|
examples/Rotate.hs
|
bsd-3-clause
| 229
| 0
| 8
| 60
| 123
| 66
| 57
| 8
| 1
|
import Control.Concurrent
import Control.Monad
import Data.Time
import Hypervisor.Console
import System.CPUTime
import System.Environment
import Data.Time.Format
main :: IO ()
main = do
con <- initXenConsole
args <- getArgs
let count = case args of
[arg] | take 6 arg == "count=" -> read $ drop 6 arg
_ -> 100
replicateM_ count $ do
utc_time <- getZonedTime
cputime <- getCPUTime
writeConsole con $ formatTime defaultTimeLocale "%c%n" utc_time
writeConsole con $ show cputime ++ "\n"
threadDelay (1 * 1000 * 1000)
|
GaloisInc/HaLVM
|
examples/Core/Time/Time.hs
|
bsd-3-clause
| 603
| 0
| 17
| 168
| 193
| 92
| 101
| 20
| 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.