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 TupleSections #-} module Data.TypedGraph.MorphismSpec where import Test.Hspec import Test.HUnit import Abstract.Category import Category.TypedGraph () import Base.Valid import Data.Graphs (Node(..), Edge(..)) import qualified Data.Graphs as Graph import qualified Data.Graphs.Morphism as Graph import Data.TypedGraph import Data.TypedGraph.Morphism import qualified Data.Relation as Relation tg = Graph.fromNodesAndEdges [Node 0 Nothing] [Edge 0 0 0 Nothing] makeGraph ns es = fromNodesAndEdges tg (map (,0) ns) (map (,0) es) spec :: Spec spec = do describe "fromGraphsAndLists" $ do let g1 = makeGraph [Node 0 Nothing, Node 1 Nothing, Node 2 Nothing] [Edge 0 0 1 Nothing, Edge 1 1 0 Nothing, Edge 2 1 1 Nothing, Edge 3 1 2 Nothing] let g2 = makeGraph [Node 3 Nothing, Node 4 Nothing, Node 5 Nothing] [Edge 4 3 3 Nothing, Edge 5 3 3 Nothing, Edge 6 3 4 Nothing, Edge 7 4 5 Nothing] let f = fromGraphsAndLists g1 g2 [(0,3), (1,3), (2,4)] [(0,4), (1,4), (2,5), (3,6)] it "is valid" $ validate f `shouldBe` IsValid it "has the correct domain" $ do domain f `shouldBe` g1 assertEqual "domain of node map" (Relation.domain . Graph.nodeRelation $ mapping f) (nodeIds g1) assertEqual "domain of edge map" (Relation.domain . Graph.edgeRelation $ mapping f) (edgeIds g1) it "has the correct codomain" $ do codomain f `shouldBe` g2 assertEqual "codomain of node map" (Relation.codomain . Graph.nodeRelation $ mapping f) (nodeIds g2) assertEqual "codomain of edge map" (Relation.codomain . Graph.edgeRelation $ mapping f) (edgeIds g2) describe "makeInclusion" $ do let testInclusion dom cod expected = do let actual = makeInclusion dom cod assertEqual "domain" (domain actual) (domain expected) assertEqual "codomain" (codomain actual) (codomain expected) assertEqual "mapping - domainGraph" (Graph.domainGraph $ mapping actual) (Graph.domainGraph $ mapping expected) assertEqual "mapping - codomainGraph" (Graph.codomainGraph $ mapping actual) (Graph.codomainGraph $ mapping expected) assertEqual "mapping - nodeRelation" (Graph.nodeRelation $ mapping actual) (Graph.nodeRelation $ mapping expected) assertEqual "mapping - edgeRelation" (Graph.edgeRelation $ mapping actual) (Graph.edgeRelation $ mapping expected) assertEqual "mapping" (mapping actual) (mapping expected) actual `shouldBe` expected it "produces the identity when domain = codomain" $ let g = makeGraph [Node 0 Nothing, Node 1 Nothing] [Edge 0 0 0 Nothing, Edge 1 0 1 Nothing, Edge 2 1 0 Nothing] in testInclusion g g $ fromGraphsAndLists g g [(0,0), (1,1)] [(0,0), (1,1), (2,2)] it "produces an inclusion when nodes are absent from domain" $ let g = makeGraph [Node 0 Nothing, Node 1 Nothing, Node 2 Nothing] [Edge 0 0 0 Nothing, Edge 1 0 1 Nothing, Edge 2 1 0 Nothing] g' = makeGraph [Node 0 Nothing, Node 1 Nothing] [Edge 0 0 0 Nothing, Edge 1 0 1 Nothing, Edge 2 1 0 Nothing] in testInclusion g' g $ fromGraphsAndLists g' g [(0,0), (1,1)] [(0,0), (1,1), (2,2)] it "produces an inclusion when edges are absent from domain" $ let g = makeGraph [Node 0 Nothing, Node 1 Nothing] [Edge 0 0 0 Nothing, Edge 1 0 1 Nothing, Edge 2 1 0 Nothing] g' = makeGraph [Node 0 Nothing, Node 1 Nothing] [Edge 0 0 0 Nothing, Edge 2 1 0 Nothing] in testInclusion g' g $ fromGraphsAndLists g' g [(0,0), (1,1)] [(0,0), (2,2)]
rodrigo-machado/verigraph
tests/Data/TypedGraph/MorphismSpec.hs
gpl-3.0
3,600
0
18
834
1,423
733
690
55
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="en-GB"> <title>Customizable HTML Report</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/customreport/src/main/javahelp/org/zaproxy/zap/extension/customreport/resources/help/helpset.hs
apache-2.0
982
96
29
170
408
217
191
-1
-1
{-# LANGUAGE CPP #-} module GDAL ( GDAL , GDALType , HasLayerTransaction , ApproxOK (..) , DataType (..) , IsComplex , Pair (..) , pFst , pSnd , Envelope (..) , Size , BlockIx , GDALException (..) , GDALRasterException (..) , ProgressException (..) , ErrorType (..) , ErrorNum (..) , OpenFlag(..) , identifyDriver , identifyDriverEx , openReadOnlyEx , openReadWriteEx , isGDALException , isBindingException , isProgressFunException , isInterruptedException , ColorInterp(..) , Georeference (..) , Geotransform (..) , GroundControlPoint (..) , Resampling (..) , Driver , DriverName , Dataset , OptionList , ReadWrite , ReadOnly , RWDataset , RODataset , RWBand , ROBand , Band , MaskType (MaskPerBand, MaskPerDataset) , Value (..) , ProgressFun , HasProgressFun (..) , HasOptions (..) , ContinueOrStop (..) , SQLDialect (..) , Layer , ROLayer , RWLayer , OGR , OGRConduit , OGRSource , OGRSink , OGRError (..) , OGRException (..) , OGRFeature (..) , OGRFeatureDef (..) , OGRField (..) , OGRTimeZone (..) , Fid (..) , FieldType (..) , Field (..) , Feature (..) , Justification (..) , FeatureDef (..) , GeomFieldDef (..) , FieldDef (..) , GeometryType (..) , Geometry (..) , WkbByteOrder (..) , EnvelopeReal , dataType , runGDAL , runGDAL_ , withGDAL , initializeGDAL , cleanupGDAL , isNoData , fromValue , unValueVector , catValues , driverByName , driverShortName , driverLongName , driverCreationOptionList , registerDriver , deregisterDriver , deleteDriver , create , createMem , delete , rename , copyFiles , flushCache , openReadOnly , openReadWrite , closeDataset , unsafeToReadOnly , createCopy , buildOverviews , bandAs , datasetDriver , datasetSize , datasetFileList , datasetProjection , setDatasetProjection , datasetProjectionWkt , setDatasetProjectionWkt , datasetGeotransform , setDatasetGeotransform , datasetGCPs , setDatasetGCPs , datasetBandCount , bandColorInterpretation , setBandColorInterpretation , bandDataType , bandProjection , bandGeotransform , bandBlockSize , bandBlockCount , bandBlockLen , bandSize , bandHasArbitraryOverviews , bandOverviewCount , allBand , sizeLen , bandNodataValue , setBandNodataValue , bandOffset , setBandOffset , bandScale , setBandScale , bandUnitType , setBandUnitType , addBand , getBand , readDatasetRGBA , readBand , createBandMask , readBandBlock , writeBand , writeBandBlock , copyBand , bandConduit , unsafeBandConduit , bandSink , bandSinkGeo , fillBand , fmapBand , blockConduit , unsafeBlockConduit , blockSink , allBlocks , blockSource , unsafeBlockSource , metadataDomains , metadata , metadataItem , setMetadataItem , description , setDescription , gcp , foldl' , ifoldl' , foldlWindow' , ifoldlWindow' , version , gcpGeotransform , northUpGeotransform , applyGeotransform , (|$|) , invertGeotransform , inv , composeGeotransforms , (|.|) , geoEnvelopeTransformer , liftIO , withConfigOption , setConfigOption , getConfigOption , def , ensureDataExists , runOGR , envelopeSize , geomFromWkt , geomFromWkb , geomFromGml , geomToWkt , geomToWkb , geomToGml , geomToKml , geomToJson , geomSpatialReference , geomType , geomEnvelope , geomIntersects , geomEquals , geomDisjoint , geomTouches , geomCrosses , geomWithin , geomContains , geomOverlaps , geomSimplify , geomSimplifyPreserveTopology , geomSegmentize , geomBoundary , geomConvexHull , geomBuffer , geomIntersection , geomUnion , geomUnionCascaded , geomPointOnSurface , geomDifference , geomSymDifference , geomDistance , geomLength , geomArea , geomCentroid , geomIsEmpty , geomIsValid , geomIsSimple , geomIsRing , geomPolygonize , fieldTypedAs , (.:) , (.=) , aGeom , aNullableGeom , theGeom , theNullableGeom , feature , isOGRException , closeLayer , canCreateMultipleGeometryFields , layerCount , executeSQL , createLayer , createLayerWithDef , getLayer , getLayerByName , sourceLayer , sourceLayer_ , conduitInsertLayer , conduitInsertLayer_ , sinkInsertLayer , sinkInsertLayer_ , sinkUpdateLayer , syncLayerToDisk , layerExtent , layerName , layerFeatureDef , layerFeatureCount , layerSpatialFilter , layerSpatialReference , setLayerSpatialFilter , setLayerSpatialFilterRect , clearLayerSpatialFilter , createFeature , createFeatureWithFid , createFeature_ , getFeature , updateFeature , deleteFeature , unsafeToReadOnlyLayer , zipSources , getMemFileBuffer , module Data.Conduit ) where import Control.Exception (bracket_) import Control.Monad.IO.Class (liftIO) import Data.Default (def) import Data.Conduit import Data.Conduit.Internal (zipSources) import GDAL.Internal.CPLConv import GDAL.Internal.CPLError import GDAL.Internal.CPLString import GDAL.Internal.CPLProgress import GDAL.Internal.GCP import GDAL.Internal.GDAL as GDAL import GDAL.Internal.Types import GDAL.Internal.Layer import GDAL.Internal.OGRError import GDAL.Internal.OGRGeometry import GDAL.Internal.OGRFeature import GDAL.Internal.Types.Value import GDAL.Internal.Common import GDAL.Internal.HSDriver import GDAL.Internal.VSI import OGR (Envelope(..)) import qualified GDAL.Internal.OGR as OGR import qualified GDAL.Internal.OSR as OSR #if HAVE_EMBEDDED_DATA import qualified GDAL.Internal.GDALData as GD ensureDataExists :: IO () ensureDataExists = GD.ensureExists #else import System.IO ensureDataExists :: IO () ensureDataExists = hPutStrLn stderr "WARNING: bindingsr-gdal have not been compiled with embeded GDAL_DATA" #endif -- | Performs process-wide initialization and cleanup -- Should only be called from the main thread withGDAL :: IO a -> IO a withGDAL = bracket_ initializeGDAL cleanupGDAL initializeGDAL, cleanupGDAL :: IO () initializeGDAL = #if HAVE_EMBEDDED_DATA ensureDataExists >> #endif GDAL.allRegister >> OGR.registerAll >> OSR.initialize cleanupGDAL = OGR.cleanupAll >> GDAL.destroyDriverManager >> OSR.cleanup
meteogrid/bindings-gdal
src/GDAL.hs
bsd-3-clause
6,343
0
8
1,341
1,268
852
416
310
1
{- Copyright (C) 2006 John Goerzen <jgoerzen@complete.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -} {- | Module : Database.HDBC.ColTypes Copyright : Copyright (C) 2006 John Goerzen License : GNU LGPL, version 2.1 or above Maintainer : John Goerzen <jgoerzen@complete.org> Stability : provisional Portability: portable Definitions of, and utilities for, specifying what type of data is represented by a column. Written by John Goerzen, jgoerzen\@complete.org -} module Database.HDBC.ColTypes (SqlColDesc(..), SqlTypeId(..), SqlInterval(..) ) where import Data.Dynamic {- | The description of a column. Fields are Nothing if the database backend cannot supply the requested information. The colSize field works like this: For character types, the maximum width of the column. For numeric types, the total number of digits allowed. See the ODBC manual for more. The colOctetLength field is defined for character and binary types, and gives the number of bytes the column requires, regardless of encoding. -} data SqlColDesc = SqlColDesc { colType :: SqlTypeId -- ^ Type of data stored here ,colSize :: Maybe Int -- ^ The size of a column ,colOctetLength :: Maybe Int -- ^ The maximum size in octets ,colDecDigits :: Maybe Int -- ^ Digits to the right of the period ,colNullable :: Maybe Bool -- ^ Whether NULL is acceptable } deriving (Eq, Read, Show) sqlColDescTc :: TyCon sqlColDescTc = mkTyCon "Database.HDBC.SqlColDesc" instance Typeable SqlColDesc where typeOf _ = mkTyConApp sqlColDescTc [] {- | The type identifier for a given column. This represents the type of data stored in the column in the underlying SQL engine. It does not form the entire column type; see 'SqlColDesc' for that. These types correspond mainly to those defined by ODBC. -} data SqlTypeId = SqlCharT -- ^ Fixed-width character strings | SqlVarCharT -- ^ Variable-width character strings | SqlLongVarCharT -- ^ Variable-width character strings, max length implementation dependant | SqlWCharT -- ^ Fixed-width Unicode strings | SqlWVarCharT -- ^ Variable-width Unicode strings | SqlWLongVarCharT -- ^ Variable-width Unicode strings, max length implementation dependant | SqlDecimalT -- ^ Signed exact values | SqlNumericT -- ^ Signed exact integer values | SqlSmallIntT -- ^ 16-bit integer values | SqlIntegerT -- ^ 32-bit integer values | SqlRealT | SqlFloatT -- ^ Signed inexact floating-point values | SqlDoubleT -- ^ Signed inexact double-precision values | SqlBitT -- ^ A single bit | SqlTinyIntT -- ^ 8-bit integer values | SqlBigIntT -- ^ 64-bit integer values | SqlBinaryT -- ^ Fixed-length binary data | SqlVarBinaryT -- ^ Variable-length binary data | SqlLongVarBinaryT -- ^ Variable-length binary data, max length implementation dependant | SqlDateT -- ^ A date | SqlTimeT -- ^ A time | SqlTimestampT -- ^ Combined date and time | SqlUTCDateTimeT -- ^ UTC date\/time | SqlUTCTimeT -- ^ UTC time | SqlIntervalT SqlInterval -- ^ A time or date difference | SqlGUIDT -- ^ Global unique identifier | SqlUnknownT String -- ^ A type not represented here; implementation-specific information in the String deriving (Eq, Show, Read) sqlTypeIdTc :: TyCon sqlTypeIdTc = mkTyCon "Database.HDBC.SqlTypeId" instance Typeable SqlTypeId where typeOf _ = mkTyConApp sqlTypeIdTc [] {- | The different types of intervals in SQL. -} data SqlInterval = SqlIntervalMonthT -- ^ Difference in months | SqlIntervalYearT -- ^ Difference in years | SqlIntervalYearToMonthT -- ^ Difference in years+months | SqlIntervalDayT -- ^ Difference in days | SqlIntervalHourT -- ^ Difference in hours | SqlIntervalMinuteT -- ^ Difference in minutes | SqlIntervalSecondT -- ^ Difference in seconds | SqlIntervalDayToHourT -- ^ Difference in days+hours | SqlIntervalDayToMinuteT -- ^ Difference in days+minutes | SqlIntervalDayToSecondT -- ^ Difference in days+seconds | SqlIntervalHourToMinuteT -- ^ Difference in hours+minutes | SqlIntervalHourToSecondT -- ^ Difference in hours+seconds | SqlIntervalMinuteToSecondT -- ^ Difference in minutes+seconds deriving (Eq, Show, Read) sqlIntervalTc :: TyCon sqlIntervalTc = mkTyCon "Database.HDBC.SqlInterval" instance Typeable SqlInterval where typeOf _ = mkTyConApp sqlIntervalTc []
abuiles/turbinado-blog
tmp/dependencies/hdbc-1.1.5/Database/HDBC/ColTypes.hs
bsd-3-clause
5,713
0
9
1,617
420
266
154
68
1
{-# LANGUAGE OverloadedStrings #-} ------------------------------------------------------------------------------ -- File: -- Creation Date: -- Last Modified: Oct 25 2013 [03:06:53] -- Created By: Samuli Thomasson [SimSaladin] samuli.thomassonAtpaivola.fi ------------------------------------------------------------------------------ import Tavutus import Data.Monoid import Control.Applicative import Test.HUnit import Test.QuickCheck import qualified Test.QuickCheck.Property as P instance Arbitrary Tavu where arbitrary = fmap Tavu arbitrary exsuc :: (String, Runo) -> Test exsuc (s, expected) = TestCase $ either (\er -> assertFailure $ "ParseError on " ++ s ++ ": " ++ show er) (\calc -> if expected == calc then return () else assertFailure $ "=== " ++ s ++ " === Expected: " ++ show expected ++ ". Parsed: " ++ show calc) $ tavutaRuno s exact = [ ("a o e i u y ö ä" , [[["a"],["o"],["e"],["i"],["u"],["y"],["ö"],["ä"]]] ) -- Weak diphthongs begin , ("mieti", [[["mie", "ti" ]]]) , ("nuotio", [[["nuo", "ti", "o"]]]) , ("yössä", [[["yös", "sä" ]]]) , ("suomuin", [[["suo", "muin" ]]]) -- Weak diphtongs not begin , ("värien", [[["vä", "ri", "en" ]]]) , ("nuottien", [[["nuot", "ti", "en"]]]) -- Weak diphtong begins a compound work , ("katovuosi", [[["ka", "to", "vuo", "si" ]]]) , ("asfalttitie", [[["as", "falt", "ti", "tie" ]]]) -- Poem separator , ("" , [ [] ]) , (";" , [ [],[] ]) , (";;", [ [],[] ]) , (" ;; ", [ [],[] ]) , ("a;", [ [["a"]], [] ]) , (";;a", [ [], [["a"]] ]) , (";a;", [ [], [["a"]], [] ]) -- a full puem , ( "eka ; toka ;;; kolmas" , [ [["e","ka"]],[["to","ka"]],[["kol","mas"]]] ) -- ignored punctuation , ("a - bee", [[ ["a"], ["bee"]]]) ] tests = TestList $ [ TestLabel "Exact" $ TestList (map exsuc exact) ] prop_does_not_fail :: String -> P.Result prop_does_not_fail s = either (\err -> P.failed{ P.reason = show err }) (const P.succeeded) (tavutaRuno s) main = runTestTT tests >> quickCheck prop_does_not_fail
SimSaladin/haikubot
TavutusTest.hs
bsd-3-clause
2,435
8
14
778
779
473
306
48
2
module Main where import Criterion.Main import HList import Data.Function (fix) {-# INLINE repR #-} repR :: ([a] -> [a]) -> ([a] -> H a) repR f = repH . f {-# INLINE absR #-} absR :: ([a] -> H a) -> ([a] -> [a]) absR g = absH . g {-# RULES "ww" forall body. fix body = absR (fix (repR . body . absR)) #-} -- {-# RULES "inline-fix" forall f . fix f = let w = f w in w #-} -- rev :: [a] -> [a] rev [] = [] rev (x:xs) = rev xs ++ [x] main = defaultMain [ bench (show n) $ whnf (\n -> sum $ rev [1..n]) n | n <- take 8 $ [50,100..] ]
conal/hermit
examples/original_reverse/Reverse.hs
bsd-2-clause
561
0
13
156
228
126
102
16
1
module Main where import Data.Graph.Inductive import Data.Graph.Inductive.Example main :: IO () main = return () m486 :: NodeMap String m486 = fromGraph clr486 t1 :: Gr String () t1 = insMapEdge m486 ("shirt", "watch", ()) clr486 t2 :: Gr String () t2 = insMapEdge m486 ("watch", "pants", ()) t1 t3 :: Gr Char String t3 = run_ empty $ do insMapNodeM 'a' insMapNodeM 'b' insMapNodeM 'c' insMapEdgesM [('a', 'b', "right"), ('b', 'a', "left"), ('b', 'c', "down"), ('c', 'a', "up")] t4 :: Gr String () t4 = run_ clr486 $ insMapEdgeM ("shirt", "watch", ())
zydeon/fglext
test/test.old.hs
bsd-3-clause
605
6
10
146
261
142
119
22
1
type Foo = Bar type Bar = Foo main :: IO Foo main = return ()
hvr/jhc
regress/tests/1_typecheck/4_fail/rectypes.hs
mit
63
1
6
17
34
17
17
4
1
{-@ LIQUID "--short-names" @-} {-@ LIQUID "--no-warnings" @-} {-@ LIQUID "--no-termination" @-} module Refinements where import Prelude hiding (map, foldr, foldr1) ----------------------------------------------------------------------- -- | 1. Simple Refinement Types ----------------------------------------------------------------------- -- Nat {-@ type Nat = {v: Int | v >= 0} @-} -- Pos {-@ type Pos = {v: Int | v > 0} @-} ----------------------------------------------------------------------- -- | 2. Function Contracts: Preconditions & Dead Code ----------------------------------------------------------------------- {-@ dead :: {v:String | false} -> a @-} dead :: String -> a dead = undefined ----------------------------------------------------------------------- -- | 3. Function Contracts: Safe Division ----------------------------------------------------------------------- {-@ divide :: Int -> Pos -> Int @-} divide :: Int -> Int -> Int divide n 0 = dead "dbz" divide n k = n `div` k ----------------------------------------------------------------------- -- | 4. Dividing Safely ----------------------------------------------------------------------- {-@ foo :: Int -> Nat -> Int @-} foo :: Int -> Int -> Int foo x y = if y == 0 then foo x y else divide x y ----------------------------------------------------------------------- -- | 4. Data Types ----------------------------------------------------------------------- data List a = N | C a (List a) infixr 9 `C` ----------------------------------------------------------------------- -- | 4. A few Higher-Order Functions ----------------------------------------------------------------------- {-@ map :: (a -> b) -> xs:_ -> {v:_ | size v = size xs} @-} map f N = N map f (C x xs) = f x `C` (map f xs) -- foldr foldr f b N = b foldr f b (C x xs) = f x (foldr f b xs) -- foldr1 {-@ foldr1 :: (a -> a -> a) -> {v:List a | size v > 0} -> a @-} foldr1 f (C x xs) = foldr f x xs foldr1 _ N = dead "EMPTY!!!" ----------------------------------------------------------------------- -- | 5. Measuring the Size of Data ----------------------------------------------------------------------- {-@ measure size @-} size :: List a -> Int size N = 0 size (C x xs) = 1 + size xs -- measures = strengthened constructors -- data List a where -- N :: forall a. {List a | size v = 0}... -- C :: forall a. x:a -> xs:List a -> {v:List a | size v = 1 + size xs} ----------------------------------------------------------------------- -- | 5. Weighted-Averages ----------------------------------------------------------------------- {-@ wtAverage :: {v:List (Pos, Int) | size v > 0} -> Int @-} wtAverage :: List (Int, Int) -> Int wtAverage wxs = total `divide` weights where total = foldr1 (+) (map (\(w,x) -> w * x) wxs) weights = foldr1 (+) (map (\(w,_) -> w) wxs) -- Exercise: How would you modify the types to get output `Pos` above? ----------------------------------------------------------------------- -- | 5. Ordered Lists: Take 1 ----------------------------------------------------------------------- -- You can do a lot with strengthened constructors -- Ordered Lists {-@ data List a = N | C {x :: a, xs :: List {v:a | x <= v}} @-} okList = 1 `C` 2 `C` 4 `C` N ----------------------------------------------------------------------- -- | 6. Sorting Lists ----------------------------------------------------------------------- insert x N = x `C` N insert x (C y ys) | x < y = x `C` (y `C` ys) | otherwise = y `C` (insert x ys) insertSort [] = N insertSort (x:xs) = insert x (insertSort xs) -- Note that adding ordering BREAKS `map`, but ...
abakst/liquidhaskell
docs/slides/NEU14/00_Refinements-blank.hs
bsd-3-clause
3,789
0
12
721
622
361
261
31
2
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} module T14991 where import Data.Kind type family Promote (k :: Type) :: Type type family PromoteX (a :: k) :: Promote k type family Demote (k :: Type) :: Type type family DemoteX (a :: k) :: Demote k ----- -- Type ----- type instance Demote Type = Type type instance Promote Type = Type type instance DemoteX (a :: Type) = Demote a type instance PromoteX (a :: Type) = Promote a ----- -- Arrows ----- data TyFun :: Type -> Type -> Type type a ~> b = TyFun a b -> Type infixr 0 ~> type instance Demote (a ~> b) = DemoteX a -> DemoteX b type instance Promote (a -> b) = PromoteX a ~> PromoteX b
sdiehl/ghc
testsuite/tests/dependent/should_compile/T14991.hs
bsd-3-clause
758
0
6
154
235
142
93
-1
-1
{-# LANGUAGE BangPatterns,CPP #-} module MVarListLockCoupling where import Control.Monad import Data.IORef import Control.Concurrent import Control.Concurrent.Chan import System.Environment import Data.Time -- #define USE_UNPACK -- #define USE_STRICT #if defined(USE_UNPACK) #define UNPACK(p) {-# UNPACK #-} !(p) #elif defined(USE_STRICT) #define UNPACK(p) !(p) #else #define UNPACK(p) p #endif data List a = Node { val :: a , next :: UNPACK(MVar (List a)) } | Null | Head { next :: UNPACK(MVar (List a)) } deriving Eq data ListHandle a = ListHandle { headList :: IORef (MVar (List a)), tailList :: IORef (MVar (List a)) } -- we assume a static head pointer, pointing to the first node which must be Head -- the deleted field of Head is always False, it's only there to make some of the code -- more uniform -- tail points to the last node which must be Null -- head is static, therefore IORef -- tail will be adjusted, therefore MVar type Iterator a = IORef (MVar (List a)) -- iterators are private ------------------------------------------- -- auxiliary functions while b cmd = if b then do {cmd; while b cmd} else return () repeatUntil cmd = do { b <- cmd; if b then return () else repeatUntil cmd } atomCAS :: Eq a => IORef a -> a -> a -> IO Bool atomCAS ptr old new = atomicModifyIORef ptr (\ cur -> if cur == old then (new, True) else (cur, False)) atomicWrite :: IORef a -> a -> IO () atomicWrite ptr x = atomicModifyIORef ptr (\ _ -> (x,())) ---------------------------------------------- -- functions operating on lists -- we create a new list newList :: IO (ListHandle a) newList = do null <- newMVar Null hd <- newMVar (Head {next = null }) hdPtr <- newIORef hd tailPtr <- newIORef null return (ListHandle {headList = hdPtr, tailList = tailPtr}) -- we add a new node, by overwriting the null tail node -- we only need to adjust tailList but not headList because -- of the static Head -- we return the location of the newly added node addToTail :: Eq a => ListHandle a -> a -> IO () addToTail (ListHandle {tailList = tailPtrPtr}) x = do null <- newMVar Null tailPtr <- readIORef tailPtrPtr takeMVar tailPtr writeIORef tailPtrPtr null putMVar tailPtr (Node {val = x, next = null}) find :: Eq a => ListHandle a -> a -> IO Bool find (ListHandle { headList = head }) x = let go prevPtr prevNode = do let curPtr = next prevNode -- head/node/delnode have all next curNode <- takeMVar curPtr case curNode of Node {val = y, next = nextNode } -> if (x == y) then -- node found do putMVar prevPtr prevNode putMVar curPtr curNode return True else do putMVar prevPtr prevNode go curPtr curNode -- continue Null -> do putMVar prevPtr prevNode putMVar curPtr curNode return False -- reached end of list in do startPtr <- readIORef head startNode <- takeMVar startPtr go startPtr startNode delete :: Eq a => ListHandle a -> a -> IO Bool delete (ListHandle { headList = head }) x = let go prevPtr prevNode = do do let curPtr = next prevNode -- head/node/delnode have all next curNode <- takeMVar curPtr case curNode of Node {val = y, next = nextNode } -> if (x == y) then -- delink node do case prevNode of Node {} -> do putMVar prevPtr (Node {val = val prevNode, next = nextNode}) putMVar curPtr curNode return True Head {} -> do putMVar prevPtr (Head {next = nextNode}) putMVar curPtr curNode return True else do putMVar prevPtr prevNode go curPtr curNode -- continue Null -> do putMVar curPtr curNode putMVar prevPtr prevNode return False -- reached end of list in do startPtr <- readIORef head startNode <- takeMVar startPtr go startPtr startNode --printing and counting printList :: Show a => ListHandle a -> IO () printList (ListHandle {headList = ptrPtr}) = do startptr <- ( do ptr <- readIORef ptrPtr Head {next = startptr} <- readMVar ptr return startptr) printListHelp startptr printListHelp :: Show a => MVar (List a) -> IO () printListHelp curNodePtr = do { curNode <- readMVar curNodePtr ; case curNode of Null -> putStr "Nil" Node {val = curval, next = curnext} -> do { putStr (show curval ++ " -> ") ; printListHelp curnext } } cntList :: Show a => ListHandle a -> IO Int cntList (ListHandle {headList = ptrPtr}) = do startptr <- ( do ptr <- readIORef ptrPtr Head {next = startptr} <- readMVar ptr return startptr) cntListHelp startptr 0 cntListHelp :: Show a => MVar (List a) -> Int -> IO Int cntListHelp curNodePtr i = do { curNode <- readMVar curNodePtr ; case curNode of Null -> return i Node {val = curval, next = curnext} -> cntListHelp curnext (i+1) }
ezyang/ghc
testsuite/tests/concurrent/prog003/MVarListLockCoupling.hs
bsd-3-clause
5,863
0
28
2,192
1,553
775
778
113
4
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[ListSetOps]{Set-like operations on lists} -} {-# LANGUAGE CPP #-} module ListSetOps ( unionLists, minusList, insertList, -- Association lists Assoc, assoc, assocMaybe, assocUsing, assocDefault, assocDefaultUsing, -- Duplicate handling hasNoDups, runs, removeDups, findDupsEq, equivClasses, equivClassesByUniq, -- Indexing getNth ) where #include "HsVersions.h" import Outputable import Unique import UniqFM import Util import Data.List {- --------- #ifndef DEBUG getNth :: [a] -> Int -> a getNth xs n = xs !! n #else getNth :: Outputable a => [a] -> Int -> a getNth xs n = ASSERT2( xs `lengthAtLeast` n, ppr n $$ ppr xs ) xs !! n #endif ---------- -} getNth :: Outputable a => [a] -> Int -> a getNth xs n = ASSERT2( xs `lengthExceeds` n, ppr n $$ ppr xs ) xs !! n {- ************************************************************************ * * Treating lists as sets Assumes the lists contain no duplicates, but are unordered * * ************************************************************************ -} insertList :: Eq a => a -> [a] -> [a] -- Assumes the arg list contains no dups; guarantees the result has no dups insertList x xs | isIn "insert" x xs = xs | otherwise = x : xs unionLists :: (Outputable a, Eq a) => [a] -> [a] -> [a] -- Assumes that the arguments contain no duplicates unionLists xs ys = WARN(length xs > 100 || length ys > 100, ppr xs $$ ppr ys) [x | x <- xs, isn'tIn "unionLists" x ys] ++ ys minusList :: (Eq a) => [a] -> [a] -> [a] -- Everything in the first list that is not in the second list: minusList xs ys = [ x | x <- xs, isn'tIn "minusList" x ys] {- ************************************************************************ * * \subsection[Utils-assoc]{Association lists} * * ************************************************************************ Inefficient finite maps based on association lists and equality. -} -- A finite mapping based on equality and association lists type Assoc a b = [(a,b)] assoc :: (Eq a) => String -> Assoc a b -> a -> b assocDefault :: (Eq a) => b -> Assoc a b -> a -> b assocUsing :: (a -> a -> Bool) -> String -> Assoc a b -> a -> b assocMaybe :: (Eq a) => Assoc a b -> a -> Maybe b assocDefaultUsing :: (a -> a -> Bool) -> b -> Assoc a b -> a -> b assocDefaultUsing _ deflt [] _ = deflt assocDefaultUsing eq deflt ((k,v) : rest) key | k `eq` key = v | otherwise = assocDefaultUsing eq deflt rest key assoc crash_msg list key = assocDefaultUsing (==) (panic ("Failed in assoc: " ++ crash_msg)) list key assocDefault deflt list key = assocDefaultUsing (==) deflt list key assocUsing eq crash_msg list key = assocDefaultUsing eq (panic ("Failed in assoc: " ++ crash_msg)) list key assocMaybe alist key = lookup alist where lookup [] = Nothing lookup ((tv,ty):rest) = if key == tv then Just ty else lookup rest {- ************************************************************************ * * \subsection[Utils-dups]{Duplicate-handling} * * ************************************************************************ -} hasNoDups :: (Eq a) => [a] -> Bool hasNoDups xs = f [] xs where f _ [] = True f seen_so_far (x:xs) = if x `is_elem` seen_so_far then False else f (x:seen_so_far) xs is_elem = isIn "hasNoDups" equivClasses :: (a -> a -> Ordering) -- Comparison -> [a] -> [[a]] equivClasses _ [] = [] equivClasses _ stuff@[_] = [stuff] equivClasses cmp items = runs eq (sortBy cmp items) where eq a b = case cmp a b of { EQ -> True; _ -> False } {- The first cases in @equivClasses@ above are just to cut to the point more quickly... @runs@ groups a list into a list of lists, each sublist being a run of identical elements of the input list. It is passed a predicate @p@ which tells when two elements are equal. -} runs :: (a -> a -> Bool) -- Equality -> [a] -> [[a]] runs _ [] = [] runs p (x:xs) = case (span (p x) xs) of (first, rest) -> (x:first) : (runs p rest) removeDups :: (a -> a -> Ordering) -- Comparison function -> [a] -> ([a], -- List with no duplicates [[a]]) -- List of duplicate groups. One representative from -- each group appears in the first result removeDups _ [] = ([], []) removeDups _ [x] = ([x],[]) removeDups cmp xs = case (mapAccumR collect_dups [] (equivClasses cmp xs)) of { (dups, xs') -> (xs', dups) } where collect_dups _ [] = panic "ListSetOps: removeDups" collect_dups dups_so_far [x] = (dups_so_far, x) collect_dups dups_so_far dups@(x:_) = (dups:dups_so_far, x) findDupsEq :: (a->a->Bool) -> [a] -> [[a]] findDupsEq _ [] = [] findDupsEq eq (x:xs) | null eq_xs = findDupsEq eq xs | otherwise = (x:eq_xs) : findDupsEq eq neq_xs where (eq_xs, neq_xs) = partition (eq x) xs equivClassesByUniq :: (a -> Unique) -> [a] -> [[a]] -- NB: it's *very* important that if we have the input list [a,b,c], -- where a,b,c all have the same unique, then we get back the list -- [a,b,c] -- not -- [c,b,a] -- Hence the use of foldr, plus the reversed-args tack_on below equivClassesByUniq get_uniq xs = eltsUFM (foldr add emptyUFM xs) where add a ufm = addToUFM_C tack_on ufm (get_uniq a) [a] tack_on old new = new++old
urbanslug/ghc
compiler/utils/ListSetOps.hs
bsd-3-clause
6,162
0
11
1,939
1,585
858
727
83
3
-- Tests that when the StaticPointers extension is not enabled -- the static identifier can be used as a regular Haskell -- identifier. module RdrNoStaticPointers01 where f :: Int -> Int f static = static
urbanslug/ghc
testsuite/tests/parser/should_compile/RdrNoStaticPointers01.hs
bsd-3-clause
206
0
5
36
24
15
9
3
1
{-# htermination when :: Bool -> [] () -> [] () #-} import Monad
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Monad_when_2.hs
mit
65
0
3
14
5
3
2
1
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleInstances #-} module CovenantEyes.Nestify.CLI where import Data.List (intercalate) import Data.List.Split (splitOn) import Data.Version (showVersion) import Options.Applicative import Paths_nestify (version) import CovenantEyes.Nestify (nestify) data CmdOptions = CmdOptions { _delim :: String } (<$$>) :: (Functor f, Functor f1) => (a -> b) -> f (f1 a) -> f (f1 b) (<$$>) = fmap fmap fmap cmdOptions :: Parser CmdOptions cmdOptions = CmdOptions <$> strOption ( long "delimiter" <> short 'd' <> metavar "DELIM" <> value "," <> showDefault <> help "Use DELIM to delimit columns in the input" ) addVersion :: Parser (a -> a) addVersion = infoOption ("nestify version " ++ showVersion version) ( long "version" <> help "Show version information" ) go :: CmdOptions -> IO () go (CmdOptions delim) = interact $ unlines . (intercalate delim <$>) . nestifyStr . (splitOn delim <$>) . lines nestifyStr :: [[String]] -> [[String]] nestifyStr = postProcess . nestify where postProcess (result, danglers) = result ++ (annotate <$> danglers) where annotate = (:[]) . ("-> Dangling: " ++) main :: IO () main = execParser opts >>= go where opts = info (helper <*> addVersion <*> cmdOptions) ( fullDesc <> progDesc "Indent the last column using the penultimate column as a scope name" )
3noch/nestify
nestify-cli/CovenantEyes/Nestify/CLI.hs
mit
1,482
0
13
362
446
242
204
37
1
import Data.Char main=print.length.filter(isAlpha)=<<getLine
Shakadak/tinker
alphalen.hs
mit
61
2
7
3
33
14
19
2
1
{-# LANGUAGE OverloadedStrings #-} module Expr where import Data.ByteString.Char8 (ByteString) import Data.Set (Set) import qualified Data.Set as Set import Data.Map.Lazy (Map, (!)) import qualified Data.Map.Lazy as Map data Ident = Ident ByteString deriving (Eq, Ord, Show, Read) infixl 9 :$ infixr 7 :^ data Expr = Expr :$ Expr | Ident :^ Expr | Var Ident deriving (Eq, Show, Read) type Context = Map Ident Expr emptyContext = Map.empty -------------------------------------------------------------------------------- i :: Expr i = Var (Ident "i") k :: Expr k = Var (Ident "k") s :: Expr s = Var (Ident "s") -------------------------------------------------------------------------------- -- | 式中の全てのλ抽象をSKコンビネーターに展開する unlambda :: Expr -> Expr unlambda e@(Var _) = e unlambda (e :$ e') = unlambda e :$ unlambda e' unlambda (x :^ e) = unlambda $ resolve x e -- | λ式の中から変数を取り除く resolve :: Ident -> Expr -> Expr resolve x e@(Var y) -- ^x.x === i | x == y = i -- ^x.y === `ky | otherwise = k :$ e resolve x e@(e' :$ e''@(Var y)) -- ^x.M === `kM | not (x `isFreeIn` e) = k :$ e -- ^x.`Mx === M | not (x `isFreeIn` e') = e' -- ^x.`MN === ``s ^x.M ^x.N | otherwise = s :$ resolve x e' :$ resolve x e'' resolve x e@(e' :$ e'') -- ^x.M === `kM | not (x `isFreeIn` e) = k :$ e -- ^x.`M N === ``s ^x.M ^x.N | otherwise = s :$ resolve x e' :$ resolve x e'' resolve x e@(y :^ e') | x == y = k :$ e | otherwise = resolve x $ resolve y e' -------------------------------------------------------------------------------- -- | 変数が式の中に自由変数として含まれるかどうか判定する isFreeIn :: Ident -> Expr -> Bool x `isFreeIn` (Var y) | x == y = True | otherwise = False x `isFreeIn` (y :^ e) | x == y = False | otherwise = x `isFreeIn` e x `isFreeIn` (e :$ e') = x `isFreeIn` e || x `isFreeIn` e' -------------------------------------------------------------------------------- -- | 式に含まれる定義済み変数を展開する subst :: Context -> Expr -> Expr subst = subst' Set.empty subst' :: Set Ident -> Context -> Expr -> Expr subst' vs context x@(Var v) | v `Set.notMember` vs && v `Map.member` context = subst context $ context ! v | otherwise = x subst' vs context (v :^ e) = v :^ subst' (v `Set.insert` vs) context e subst' vs context (e :$ e') = subst' vs context e :$ subst' vs context e' -------------------------------------------------------------------------------- compile :: Context -> Expr -> Expr compile context x@(Var v) | v `Map.member` context = compile context $ subst context x | otherwise = x compile context l@(_ :^ _) = compile context $ unlambda l compile context (e :$ e') = compile context e :$ compile context e'
todays-mitsui/lambda2ski
src/Expr.hs
mit
3,018
0
11
740
1,025
542
483
64
1
module Graphics.Cogh.Color ( Color(..) , color , colorAlpha , red , green , blue , black , white , transparent ) where data Color = Color Float Float Float Float color :: Float -> Float -> Float -> Color color r g b = Color r g b 1 colorAlpha :: Float -> Float -> Float -> Float -> Color colorAlpha = Color red :: Color red = Color 1 0 0 1 green :: Color green = Color 0 1 0 1 blue :: Color blue = Color 0 0 1 1 black :: Color black = Color 0 0 0 1 white :: Color white = Color 1 1 1 1 transparent :: Color transparent = Color 0 0 0 0
ivokosir/cogh
src/Graphics/Cogh/Color.hs
mit
590
0
8
178
233
128
105
31
1
module Data.AER.WindowedStream where import qualified Data.AER.Types as AER import Data.Thyme.Clock import Data.List import Data.List.Split windowedStream :: NominalDiffTime -> [AER.Event a] -> [[AER.Event a]] windowedStream dt xs = go t0 xs where t0 = AER.timestamp (head xs) go _ [] = [] go tn xs' = now : go (tn+dt) later where (now,later) = partition (\e -> AER.timestamp e < tn + dt) xs'
fhaust/aer-utils
src/Data/AER/WindowedStream.hs
mit
474
0
15
144
178
97
81
11
2
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} module Operator (EndoOperator(..)) where -- | Class for an operator from a vector space into itself. class EndoOperator o where -- | Type of the eigenvalue. In general (Complex Double), but some -- operators may have real, positive, etc. eigenvectors. type Eigenvalue o :: * -- | Array type for eigenvalue storage. Usually 'Data.Vector.Unboxed' is useful for numeric types. type EigenvalueStorage o :: * -> * -- | Storage for eigenvectors. type EigenvectorStorage o :: * -- | Find the eigenvalues, optionally passing eigenvalue indices of interest (both inclusive). eigvals :: o -> Maybe (Int, Int) -> (EigenvalueStorage o) (Eigenvalue o) -- | Find the eigenvectors, optionally passing eigenvalue indices of interest (both inclusive). eigvecs :: o -> Maybe (Int, Int) -> EigenvectorStorage o -- | Equivalent to @('eigvals' o n, 'eigvecs' o n)@, but possibly more performant. eigsys :: o -> Maybe (Int, Int) -> ((EigenvalueStorage o) (Eigenvalue o), EigenvectorStorage o) eigsys o n = (eigvals o n, eigvecs o n) -- | In terms of the inner product space. adjoint :: o -> o
lensky/hs-matrix
lib/Operator.hs
mit
1,178
0
12
222
201
115
86
12
0
{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Spellcheck.HolbrookCorpus -- Copyright : (C) 2013 Yorick Laupa -- License : (see the file LICENSE) -- -- Maintainer : Yorick Laupa <yo.eight@gmail.com> -- Stability : provisional -- Portability : non-portable -- ---------------------------------------------------------------------------- module Data.Spellcheck.HolbrookCorpus ( HolbrookCorpus , corpusLoad , mkCorpus , loadHolbrook , trainCorpus , devCorpus , corpusTestCases ) where import Prelude hiding (lines, takeWhile) import Data.Char (isAlphaNum, isPunctuation, isSpace) import Data.IORef import Data.Maybe (fromMaybe) import Control.Applicative ((<*>), (<$>)) import Control.Monad (mzero, mplus) import Control.Monad.Trans.Resource import Data.Attoparsec.Text import Data.Conduit import Data.Conduit.Binary (sourceFile) import Data.Conduit.Text (decode, utf8, lines) import qualified Data.Text as T import Data.Spellcheck.Datum import Data.Spellcheck.Sentence import Data.Spellcheck.Utils newtype HolbrookCorpus = HC (IO [Sentence]) mkCorpus :: FilePath -> IO HolbrookCorpus mkCorpus filepath = fmap go (newIORef Nothing) where go ref = HC $ do v <- readIORef ref case v of Just xs -> return xs _ -> do xs <- loadHolbrook filepath writeIORef ref (Just xs) return xs trainCorpus, devCorpus :: IO HolbrookCorpus trainCorpus = mkCorpus "data/holbrook-tagged-train.dat" devCorpus = mkCorpus "data/holbrook-tagged-dev.dat" corpusLoad :: HolbrookCorpus -> IO [Sentence] corpusLoad (HC run) = run corpusTestCases :: HolbrookCorpus -> IO [Sentence] corpusTestCases = fmap go . corpusLoad where go = filter sentenceHasError -- | Load HolbrookCorpus format corpus into list of Sentence loadHolbrook :: FilePath -> IO [Sentence] loadHolbrook filepath = runResourceT process where toText = decode utf8 source = sourceFile filepath process = source $= toText =$= lines $$ mkSentences mkSentences :: Sink T.Text (ResourceT IO) [Sentence] mkSentences = maybe (return []) go =<< await where go t = (:) <$> mkSentence t <*> mkSentences mkSentence = either (monadThrow . PE) return . parseOnly parser parser :: Parser Sentence parser = takeWhile isAlphaNum >>= go where go xs | T.null xs = do end <- atEnd if end then return [SEnd] else peekChar' >>= loop | otherwise = do cOpt <- peekChar case cOpt of Nothing -> return [mkDatum xs, SEnd] Just c -> fmap (mkDatum xs:) (loop c) loop c | isBreaker c = anyChar >> parser | c == '<' = (:) <$> parseError <*> parser | otherwise = fail ("Unexpected " ++ [c]) isBreaker c = isSpace c || isPunctuation c || c == '`' mkDatum xs = SDatum $ datumCorrect $ T.toLower xs parseError :: Parser SentenceToken parseError = do word <- "<ERR targ=" .*> takeWhile1 (/= '>') char '>' err <- takeWhile1 (/= '<') string "</ERR>" `mplus` fail "Not ended by </ERR>" let dat = datum word (Just err) return $ SDatum dat
YoEight/spellcheck
lib/Data/Spellcheck/HolbrookCorpus.hs
mit
3,403
0
17
899
906
477
429
79
3
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE CPP #-} -- | -- Module : Pinboard.ApiTypes -- Copyright : (c) Jon Schoning, 2015 -- Maintainer : jonschoning@gmail.com -- Stability : experimental -- Portability : POSIX module Pinboard.ApiTypes where import Data.Aeson import Data.Aeson.Types (Parser) import Data.HashMap.Strict (HashMap, member, toList) import Data.Data (Data, Typeable) import Data.Text (Text, words, unwords, unpack, pack) import Data.Time (UTCTime, parseTimeM) import Data.Time.Calendar (Day) import GHC.Generics (Generic) import qualified Data.HashMap.Strict as HM #if !MIN_VERSION_aeson(1,0,0) import qualified Data.Vector as V #endif import Data.Time.Format (formatTime, defaultTimeLocale) import Control.Applicative import Prelude hiding (words, unwords) -- * Posts data Posts = Posts { postsDate :: !UTCTime , postsUser :: !Text , postsPosts :: [Post] } deriving (Show, Eq, Data, Typeable, Generic, Ord) instance FromJSON Posts where parseJSON (Object o) = Posts <$> o .: "date" <*> o .: "user" <*> o .: "posts" parseJSON _ = fail "bad parse" instance ToJSON Posts where toJSON Posts {..} = object [ "date" .= toJSON postsDate , "user" .= toJSON postsUser , "posts" .= toJSON postsPosts ] data Post = Post { postHref :: !Text , postDescription :: !Text , postExtended :: !Text , postMeta :: !Text , postHash :: !Text , postTime :: !UTCTime , postShared :: !Bool , postToRead :: !Bool , postTags :: [Tag] } deriving (Show, Eq, Data, Typeable, Generic, Ord) instance FromJSON Post where parseJSON (Object o) = Post <$> o .: "href" <*> o .: "description" <*> o .: "extended" <*> o .: "meta" <*> o .: "hash" <*> o .: "time" <*> (boolFromYesNo <$> o .: "shared") <*> (boolFromYesNo <$> o .: "toread") <*> (words <$> o .: "tags") parseJSON _ = fail "bad parse" instance ToJSON Post where toJSON Post {..} = object [ "href" .= toJSON postHref , "description" .= toJSON postDescription , "extended" .= toJSON postExtended , "meta" .= toJSON postMeta , "hash" .= toJSON postHash , "time" .= toJSON postTime , "shared" .= boolToYesNo postShared , "toread" .= boolToYesNo postToRead , "tags" .= unwords postTags ] boolFromYesNo :: Text -> Bool boolFromYesNo "yes" = True boolFromYesNo _ = False boolToYesNo :: Bool -> Text boolToYesNo True = "yes" boolToYesNo _ = "no" data PostDates = PostDates { postDatesUser :: !Text , postDatesTag :: !Text , postDatesCount :: [(Day, Int)] } deriving (Show, Eq, Data, Typeable, Generic, Ord) instance FromJSON PostDates where parseJSON (Object o) = PostDates <$> o .: "user" <*> o .: "tag" <*> (parseDates <$> o .: "dates") where parseDates :: Value -> [DateCount] parseDates (Object o') = do (dateStr, String countStr) <- toList o' return (read (unpack dateStr), read (unpack countStr)) parseDates _ = [] parseJSON _ = fail "bad parse" instance ToJSON PostDates where toJSON PostDates {..} = object [ "user" .= toJSON postDatesUser , "tag" .= toJSON postDatesTag , "dates" .= object (dateCountToPair <$> postDatesCount) ] where dateCountToPair (day, count) = ((pack . show) day, String $ (pack . show) count) type DateCount = (Day, Int) -- * Notes data NoteList = NoteList { noteListCount :: !Int , noteListItems :: [NoteListItem] } deriving (Show, Eq, Data, Typeable, Generic, Ord) instance FromJSON NoteList where parseJSON (Object o) = NoteList <$> o .: "count" <*> o .: "notes" parseJSON _ = fail "bad parse" instance ToJSON NoteList where toJSON NoteList {..} = object ["count" .= toJSON noteListCount, "notes" .= toJSON noteListItems] data NoteListItem = NoteListItem { noteListItemId :: !Text , noteListItemHash :: !Text , noteListItemTitle :: !Text , noteListItemLength :: !Int , noteListItemCreatedAt :: !UTCTime , noteListItemUpdatedAt :: !UTCTime } deriving (Show, Eq, Data, Typeable, Generic, Ord) instance FromJSON NoteListItem where parseJSON (Object o) = NoteListItem <$> o .: "id" <*> o .: "hash" <*> o .: "title" <*> (read <$> (o .: "length")) <*> (readNoteTime =<< o .: "created_at") <*> (readNoteTime =<< o .: "updated_at") parseJSON _ = fail "bad parse" instance ToJSON NoteListItem where toJSON NoteListItem {..} = object [ "id" .= toJSON noteListItemId , "hash" .= toJSON noteListItemHash , "title" .= toJSON noteListItemTitle , "length" .= toJSON (show noteListItemLength) , "created_at" .= toJSON (showNoteTime noteListItemCreatedAt) , "updated_at" .= toJSON (showNoteTime noteListItemUpdatedAt) ] data Note = Note { noteId :: !Text , noteHash :: !Text , noteTitle :: !Text , noteText :: !Text , noteLength :: !Int , noteCreatedAt :: !UTCTime , noteUpdatedAt :: !UTCTime } deriving (Show, Eq, Data, Typeable, Generic, Ord) instance FromJSON Note where parseJSON (Object o) = Note <$> o .: "id" <*> o .: "hash" <*> o .: "title" <*> o .: "text" <*> o .: "length" <*> (readNoteTime =<< o .: "created_at") <*> (readNoteTime =<< o .: "updated_at") parseJSON _ = fail "bad parse" instance ToJSON Note where toJSON Note {..} = object [ "id" .= toJSON noteId , "hash" .= toJSON noteHash , "title" .= toJSON noteTitle , "text" .= toJSON noteText , "length" .= toJSON noteLength , "created_at" .= toJSON (showNoteTime noteCreatedAt) , "updated_at" .= toJSON (showNoteTime noteUpdatedAt) ] readNoteTime :: MonadFail m => String -> m UTCTime readNoteTime = parseTimeM True defaultTimeLocale "%F %T" showNoteTime :: UTCTime -> String showNoteTime = formatTime defaultTimeLocale "%F %T" -- * Tags type TagMap = HashMap Tag Int newtype JsonTagMap = ToJsonTagMap { fromJsonTagMap :: TagMap } deriving (Show, Eq, Data, Typeable, Generic) instance FromJSON JsonTagMap where parseJSON = toTags where toTags (Object o) = return . ToJsonTagMap $ HM.map (\(String s) -> read (unpack s)) o toTags _ = fail "bad parse" instance ToJSON JsonTagMap where toJSON (ToJsonTagMap o) = toJSON $ show <$> o data Suggested = Popular [Text] | Recommended [Text] deriving (Show, Eq, Data, Typeable, Generic, Ord) instance FromJSON Suggested where parseJSON (Object o) | member "popular" o = Popular <$> (o .: "popular") | member "recommended" o = Recommended <$> (o .: "recommended") | otherwise = fail "bad parse" parseJSON _ = fail "bad parse" #if !MIN_VERSION_aeson(1,0,0) instance ToJSON [Suggested] where toJSON xs = Array $ toJSON <$> V.fromList xs #endif instance ToJSON Suggested where toJSON (Popular tags) = object ["popular" .= toJSON tags] toJSON (Recommended tags) = object ["recommended" .= toJSON tags] -- * Scalars newtype DoneResult = ToDoneResult { fromDoneResult :: () } deriving (Show, Eq, Data, Typeable, Generic, Ord) instance FromJSON DoneResult where parseJSON (Object o) = parseDone =<< (o .: "result" <|> o .: "result_code") where parseDone :: Text -> Parser DoneResult parseDone "done" = return $ ToDoneResult () parseDone msg = (fail . unpack) msg parseJSON _ = fail "bad parse" newtype TextResult = ToTextResult { fromTextResult :: Text } deriving (Show, Eq, Data, Typeable, Generic, Ord) instance FromJSON TextResult where parseJSON (Object o) = ToTextResult <$> (o .: "result") parseJSON _ = fail "bad parse" newtype UpdateTime = ToUpdateTime { fromUpdateTime :: UTCTime } deriving (Show, Eq, Data, Typeable, Generic, Ord) instance FromJSON UpdateTime where parseJSON (Object o) = ToUpdateTime <$> (o .: "update_time") parseJSON _ = error "bad parse" -- prettyString :: String -> String -- prettyString s = case parseExp s of -- ParseOk x -> prettyPrint x -- ParseFailed{} -> s -- pretty :: Show a => a -> String -- pretty = prettyString . show -- * Aliases -- | as defined by RFC 3986. Allowed schemes are http, https, javascript, mailto, ftp and file. The Safari-specific feed scheme is allowed but will be treated as a synonym for http. type Url = Text -- | up to 255 characters long type Description = Text -- | up to 65536 characters long. Any URLs will be auto-linkified when displayed. type Extended = Text -- | up to 255 characters. May not contain commas or whitespace. type Tag = Text type Old = Tag type New = Tag type Count = Int type NumResults = Int type StartOffset = Int type Shared = Bool type Replace = Bool type ToRead = Bool -- | UTC date in this format: 2010-12-11. Same range as datetime above type Date = Day -- | UTC timestamp in this format: 2010-12-11T19:48:02Z. Valid date range is Jan 1, 1 AD to January 1, 2100 (but see note below about future timestamps). type DateTime = UTCTime type FromDateTime = DateTime type ToDateTime = DateTime type Meta = Int type NoteId = Text
jonschoning/pinboard
src/Pinboard/ApiTypes.hs
mit
9,180
0
20
2,000
2,673
1,435
1,238
280
1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.RTCConfiguration (js_getIceServers, getIceServers, js_getIceTransports, getIceTransports, js_getRequestIdentity, getRequestIdentity, RTCConfiguration, castToRTCConfiguration, gTypeRTCConfiguration) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"iceServers\"]" js_getIceServers :: RTCConfiguration -> IO JSVal -- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCConfiguration.iceServers Mozilla RTCConfiguration.iceServers documentation> getIceServers :: (MonadIO m) => RTCConfiguration -> m [Maybe RTCIceServer] getIceServers self = liftIO ((js_getIceServers (self)) >>= fromJSValUnchecked) foreign import javascript unsafe "$1[\"iceTransports\"]" js_getIceTransports :: RTCConfiguration -> IO JSVal -- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCConfiguration.iceTransports Mozilla RTCConfiguration.iceTransports documentation> getIceTransports :: (MonadIO m) => RTCConfiguration -> m RTCIceTransportsEnum getIceTransports self = liftIO ((js_getIceTransports (self)) >>= fromJSValUnchecked) foreign import javascript unsafe "$1[\"requestIdentity\"]" js_getRequestIdentity :: RTCConfiguration -> IO JSVal -- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCConfiguration.requestIdentity Mozilla RTCConfiguration.requestIdentity documentation> getRequestIdentity :: (MonadIO m) => RTCConfiguration -> m RTCIdentityOptionEnum getRequestIdentity self = liftIO ((js_getRequestIdentity (self)) >>= fromJSValUnchecked)
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/RTCConfiguration.hs
mit
2,410
18
10
310
519
315
204
37
1
module ProjectEuler.Problem009 (solve) where import Data.Maybe import Data.Ratio isWhole :: Double -> Bool isWhole n = (denominator . toRational) n == 1 solveM :: (Int, Int) -> Maybe Int solveM (x, y) | isWhole m = Just $ floor (m :: Double) | otherwise = Nothing where a = fromIntegral x b = fromIntegral y m = (-a + sqrt (a ^ (2 :: Int) + (2 * b))) / 2 solveMN :: Int -> Maybe (Int, Int) solveMN x | null ys = Nothing | otherwise = Just $ head ys where ys = [(fromJust m, n) | n <- [1..x], let m = solveM (n, x), isJust m] pythagoreanTriple :: (Int, Int) -> Maybe (Int, Int, Int) pythagoreanTriple (x, y) | y > x || all (< 1) [x, y, a, b, c] = Nothing | otherwise = Just pt where e = 2 :: Int pt@(a, b, c) = (x ^ e - y ^ e, 2 * x * y, x ^ e + y ^ e) pythagoreanTripleFromSum :: Int -> Maybe (Int, Int, Int) pythagoreanTripleFromSum x = maybe Nothing pythagoreanTriple (solveMN x) solve :: Int -> Maybe Int solve x = (\(a, b, c) -> a * b * c) <$> pythagoreanTripleFromSum x
hachibu/project-euler
src/ProjectEuler/Problem009.hs
mit
1,052
0
14
285
541
289
252
27
1
-- Copyright © 2013 Bart Massey -- [This work is licensed under the "MIT License"] -- Please see the file COPYING in the source -- distribution of this software for license terms. -- "Genuine Sieve of Eratosthenes" -- | This is an implementation of what I believe to be "The -- Genuine Sieve of Eratosthenes". The idea is taken from -- the paper of this title by Melissa E. O'Neill, -- J. Functional Programming 19:1, January 2009 -- <http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf>. -- However, the implementation is my own, from scratch. -- -- The basic idea of this implementation is to represent the -- various sieves as infinite lists, and the whole sieve as -- a 'Set' of these lists. Since 'Data.Set' provides -- reasonably efficient routines for treating a 'Set' as a -- min-heap, and since the default 'Ord' instance on lists -- works just the way we want, we just walk up the sieve -- dropping no-longer-useful values off the front of the -- lists. -- -- Comparison of the performance of this code with -- implementations from the paper shows it to be very -- comparable. The c2 implementation, on the other hand... import Data.Set import Data.Word import DefaultMain -- | Sieve. Takes a list of candidate primes (maybe produced -- by a wheel). If a limit is supplied, this acts as a limit -- sieve, taking advantage of the known upper bound to cut -- runtime by approximately half. soe :: Maybe Word64 -> [Word64] -> [Word64] soe _ [] = [] soe limit (n : ns) = n : soe' ns (singleton (makeStrikes n ns)) where makeStrikes x xs = Prelude.map (x *) (x : xs) soe' [] _ = [] soe' xs@(x' : xs') strikes = case Data.Set.null strikes of True -> xs False -> case deleteFindMin strikes of ([], strikes') -> soe' xs strikes' (c : cs, strikes') -> case c `compare` x' of LT -> soe' xs (insert cs strikes') EQ -> soe' xs' (insert cs strikes') GT -> x' : soe' xs' limitStrikes where limitStrikes = case limit of Just l | x' * x' > l -> strikes _ -> insert (makeStrikes x' xs') strikes -- | Infinite list of primes. primes :: [Word64] primes = 2 : soe Nothing [3, 5 ..] -- | List of primes less than or equal to 'n'. primesLim :: Word64 -> [Word64] primesLim n = 2 : soe (Just n) [3, 5 .. n] -- | Test the program's operation. main :: IO () main = defaultMain (Just primes) (Just primesLim)
BartMassey/genuine-sieve
massey-sieve.hs
mit
2,547
5
20
679
494
261
233
32
7
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings #-} module HailsRock.MP ( HailsRockModule , withHailsRockDB , Game(..) , Play(..) , Move(..) , Outcome(..) , getStats ) where import Prelude hiding (lookup) import Data.Maybe (listToMaybe) import Data.Monoid (mempty) import Data.Typeable import qualified Data.ByteString.Char8 as S8 import qualified Data.Text as T import Control.Monad import LIO import LIO.DCLabel import Hails.Data.Hson import Hails.Database import Hails.Database.Structured import Hails.PolicyModule import Hails.PolicyModule.DSL import Hails.Web -- | A game contains can be public or contain a single opponent data Game = Game { gameId :: Maybe ObjectId , creator :: UserName , opponent :: Maybe UserName } deriving (Show) data Move = Rock | Paper | Scissors deriving (Eq, Read, Show, Enum, Bounded) -- | A play is a move played by a user for a game data Play = Play { playId :: Maybe ObjectId , game :: ObjectId , player :: UserName , move :: Move } deriving (Show) data Outcome = Lose | Tie | Win deriving (Show, Eq, Ord) -- | @outcome our_move their_move@ outcome :: Move -> Move -> Outcome outcome Rock Scissors = Win outcome Paper Rock = Win outcome Scissors Paper = Win outcome us them | us == them = Tie outcome _ _ = Lose instance DCRecord Game where fromDocument doc = do let _id = lookupObjId "_id" doc p1 <- lookup "creator" doc -- Ignore empty-string opponents let p2 = do op <- lookup "opponent" doc let u = T.unwords . T.words $ op if T.null u then fail "Null opponent" else return u return Game { gameId = _id , creator = p1 , opponent = p2 } toDocument game = let emptyOr f m = maybe [] (\i -> [f -: i]) m _id = emptyOr "_id" $ gameId game opp = emptyOr "opponent" $ opponent game in _id ++ [ "creator" -: creator game ] ++ opp recordCollection _ = "games" instance DCLabeledRecord HailsRockModule Game where endorseInstance _ = HailsRockModuleTCB mempty instance DCRecord Play where fromDocument doc = do let _id = lookupObjId "_id" doc gid <- lookupObjId "game" doc p <- lookup "player" doc mv <- lookupMove "move" doc return Play { playId = _id , game = gid , player = p , move = mv } toDocument play = let emptyOr f m = maybe [] (\i -> [f -: i]) m _id = emptyOr "_id" $ playId play in _id ++ [ "game" -: game play , "player" -: player play , "move" -: (show $ move play) ] recordCollection _ = "plays" instance DCLabeledRecord HailsRockModule Play where endorseInstance _ = HailsRockModuleTCB mempty -- -- -- data HailsRockModule = HailsRockModuleTCB DCPriv deriving Typeable instance PolicyModule HailsRockModule where initPolicyModule priv = do setPolicy priv $ do database $ do readers ==> unrestricted writers ==> unrestricted admins ==> this -- collection "games" $ do access $ do readers ==> unrestricted writers ==> unrestricted clearance $ do secrecy ==> this integrity ==> unrestricted document $ \doc -> do let (Just game) = fromDocument doc readers ==> unrestricted writers ==> this \/ (userToPrincipal $ creator game) -- collection "plays" $ do access $ do readers ==> unrestricted writers ==> unrestricted clearance $ do secrecy ==> this integrity ==> unrestricted document $ \doc -> do let (Just play) = fromDocument doc readers ==> this \/ (userToPrincipal $ player play) writers ==> this \/ (userToPrincipal $ player play) field "game" key field "player" key return $ HailsRockModuleTCB priv where this = privDesc priv userToPrincipal = principal . T.unpack withHailsRockDB :: DBAction a -> DC a withHailsRockDB act = withPolicyModule (\(_ :: HailsRockModule) -> act) -- -- Sensitive getStats function -- getStats :: Play -> DC [(UserName, Outcome)] getStats playA = withPolicyModule $ \(HailsRockModuleTCB priv) -> do ps <- findAllPlays $ game playA stats <- forM ps $ \lplay -> do playB <- liftLIO $ unlabelP priv lplay return $ (player playB, outcome (move playA) (move playB)) return $ filter ((/= player playA) . fst) stats -- -- Helpers -- findAllPlays :: ObjectId -> DBAction [DCLabeled Play] findAllPlays _id = do cursor <- find $ select ["game" -: _id] "plays" cursorToRecords cursor [] where cursorToRecords cur docs = do mldoc <- next cur case mldoc of Just ldoc -> do d <- fromLabeledDocument ldoc cursorToRecords cur $ d:docs _ -> return $ reverse docs -- | Generic lookup with possible type cast lookupTyped :: (HsonVal a, Read a, Monad m) => FieldName -> HsonDocument -> m a lookupTyped n d = case lookup n d of Just i -> return i _ -> case do { s <- lookup n d; maybeRead s } of Just i -> return i _ -> fail $ "lookupTyped: cannot extract id from " ++ show n -- | Get object id (may need to convert from string). lookupObjId :: Monad m => FieldName -> HsonDocument -> m ObjectId lookupObjId = lookupTyped -- | Get move (may need to convert from string). lookupMove :: Monad m => FieldName -> HsonDocument -> m Move lookupMove f d = do s <- lookupTyped f d maybe (fail "lookupMove failed to find move") return $ maybeRead s -- | Try to read a value maybeRead :: Read a => String -> Maybe a maybeRead = fmap fst . listToMaybe . reads
scslab/hails
examples/hails-rock/HailsRock/MP.hs
mit
6,200
0
22
1,954
1,807
913
894
151
3
{- Copyright (c) 2005 John Goerzen <jgoerzen@complete.org> Please see the COPYRIGHT file -} module Main where import Config import System.Environment import System.Directory import Import import Logging import Control.Exception import Utils import Versions import System.Log.Logger import System.Cmd.Utils import System.IO.HVFS.Utils import Darcs import System.Posix.Files import System.Cmd import System.Exit import Mirrors main = do initLogging ver <- getVerFromCL pkg <- getPkgFromCL let (upsv, debv) = splitVer ver case debv of Nothing -> infoM "main" "Debian-native package; not building upstream" Just dv -> do buildorig pkg upsv debv args <- getArgs buildenv <- try (getEnv "DBP_BUILDER") case buildenv of Right buildcmd -> safeSystem "/bin/sh" ["-c", buildcmd] Left _ -> safeSystem "debuild" (["-i_darcs", "-I_darcs"] ++ args) -- Build the orig.tar.gz buildorig pkg upsv debv = let tgzname = pkg ++ "_" ++ upsv ++ ".orig.tar.gz" origdirname = pkg ++ "-" ++ upsv ++ ".orig" in do e1 <- doesFileExist $ "../" ++ tgzname e2 <- doesDirectoryExist $ "../" ++ origdirname if e1 || e2 then infoM "main" $ "Upstream file or directory already exists; not re-building" else do cwd <- getCurrentDirectory (upstreamdir, _) <- getDirectories pkg upsMirrors <- getMirrors "upstream" pkg getItUps pkg upstreamdir upsMirrors bracketCWD ".." $ do ec <- rawSystem "darcs" ["get", "--partial", "--set-scripts-executable", "--tag=^" ++ quoteRe (upstreamTag pkg upsv) ++ "$", upstreamdir, origdirname] case ec of ExitSuccess -> do bracketCWD origdirname $ do safeSystem "darcs" ["dist"] rename (origdirname ++ ".tar.gz") ("../" ++ tgzname) recursiveRemove SystemFS origdirname _ -> warningM "main" "WARNING: FOUND NO UPSTREAM SOURCE FOR PACKAGE, will build native (no-diff) package"
jgoerzen/darcs-buildpackage
darcs-buildpackage.hs
gpl-2.0
2,460
0
25
940
515
258
257
53
3
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Yi.Keymap.Vim.Ex.Commands.Tag -- License : GPL-2 -- Maintainer : yi-devel@googlegroups.com -- Stability : experimental -- Portability : portable module Yi.Keymap.Vim.Ex.Commands.Tag (parse) where import Control.Applicative import Control.Monad import Data.Monoid import qualified Data.Text as T import qualified Text.ParserCombinators.Parsec as P import Yi.Keymap import Yi.Keymap.Vim.Common import qualified Yi.Keymap.Vim.Ex.Commands.Common as Common import Yi.Keymap.Vim.Ex.Types import Yi.Keymap.Vim.Tag import Yi.Tag parse :: EventString -> Maybe ExCommand parse = Common.parse $ do void $ P.string "t" parseTag <|> parseNext parseTag :: P.GenParser Char () ExCommand parseTag = do void $ P.string "a" void . P.optionMaybe $ P.string "g" t <- P.optionMaybe $ do void $ P.many1 P.space P.many1 P.anyChar case t of Nothing -> P.eof >> return (tag Nothing) Just t' -> return $! tag (Just (Tag (T.pack t'))) parseNext :: P.GenParser Char () ExCommand parseNext = do void $ P.string "next" return next tag :: Maybe Tag -> ExCommand tag Nothing = Common.impureExCommand { cmdShow = "tag" , cmdAction = YiA unpopTag , cmdComplete = return ["tag"] } tag (Just (Tag t)) = Common.impureExCommand { cmdShow = "tag " <> t , cmdAction = YiA $ gotoTag (Tag t) 0 Nothing , cmdComplete = (fmap . fmap) (mappend "tag ") $ completeVimTag t } next :: ExCommand next = Common.impureExCommand { cmdShow = "tnext" , cmdAction = YiA nextTag , cmdComplete = return ["tnext"] }
atsukotakahashi/wi
src/library/Yi/Keymap/Vim/Ex/Commands/Tag.hs
gpl-2.0
1,724
0
18
405
510
278
232
46
2
module Isabelle.IsaExport where import Text.XML.HaXml.XmlContent hiding (Const) import Text.XML.HaXml.OneOfN import Text.XML.HaXml.Types {-Type decls-} data IsaExport = IsaExport IsaExport_Attrs Imports Consts Axioms Theorems Types deriving (Eq,Show) data IsaExport_Attrs = IsaExport_Attrs { isaExportFile :: String } deriving (Eq,Show) newtype Imports = Imports [Import] deriving (Eq,Show) data Import = Import { importName :: String } deriving (Eq,Show) newtype Consts = Consts [ConstDecl] deriving (Eq,Show) data ConstDecl = ConstDecl ConstDecl_Attrs (OneOf3 TVar TFree Type) (OneOf2 Term NoTerm) deriving (Eq,Show) data ConstDecl_Attrs = ConstDecl_Attrs { constDeclName :: String } deriving (Eq,Show) newtype Axioms = Axioms [Term] deriving (Eq,Show) newtype Theorems = Theorems [Term] deriving (Eq,Show) newtype Types = Types [TypeDecl] deriving (Eq,Show) data NoTerm = NoTerm deriving (Eq,Show) data Term = TermBound Term_Attrs Bound | TermFree Term_Attrs Free | TermVar Term_Attrs Var | TermConst Term_Attrs Const | TermApp Term_Attrs App | TermAbs Term_Attrs Abs deriving (Eq,Show) data Term_Attrs = Term_Attrs { termName :: String } deriving (Eq,Show) data TypeDecl = TypeDecl TypeDecl_Attrs [RecType] deriving (Eq,Show) data TypeDecl_Attrs = TypeDecl_Attrs { typeDeclName :: String } deriving (Eq,Show) data RecType = RecType RecType_Attrs Vars Constructors deriving (Eq,Show) data RecType_Attrs = RecType_Attrs { recTypeI :: String , recTypeName :: String , recTypeAltname :: (Maybe String) } deriving (Eq,Show) newtype Vars = Vars [Vars_] deriving (Eq,Show) data Vars_ = Vars_DtTFree DtTFree | Vars_DtType DtType | Vars_DtRec DtRec deriving (Eq,Show) data DtTFree = DtTFree { dtTFreeS :: String } deriving (Eq,Show) data DtType = DtType DtType_Attrs [DtType_] deriving (Eq,Show) data DtType_Attrs = DtType_Attrs { dtTypeS :: String } deriving (Eq,Show) data DtType_ = DtType_DtTFree DtTFree | DtType_DtType DtType | DtType_DtRec DtRec deriving (Eq,Show) data DtRec = DtRec { dtRecI :: String } deriving (Eq,Show) newtype Constructors = Constructors [Constructor] deriving (Eq,Show) data Constructor = Constructor Constructor_Attrs [Constructor_] deriving (Eq,Show) data Constructor_Attrs = Constructor_Attrs { constructorVal :: String } deriving (Eq,Show) data Constructor_ = Constructor_DtTFree DtTFree | Constructor_DtType DtType | Constructor_DtRec DtRec deriving (Eq,Show) data Bound = Bound { boundIndex :: String } deriving (Eq,Show) data Free = FreeTVar Free_Attrs TVar | FreeTFree Free_Attrs TFree | FreeType Free_Attrs Type deriving (Eq,Show) data Free_Attrs = Free_Attrs { freeName :: String } deriving (Eq,Show) data Var = VarTVar Var_Attrs TVar | VarTFree Var_Attrs TFree | VarType Var_Attrs Type deriving (Eq,Show) data Var_Attrs = Var_Attrs { varName :: String , varIndex :: (Maybe String) } deriving (Eq,Show) data Const = ConstTVar Const_Attrs TVar | ConstTFree Const_Attrs TFree | ConstType Const_Attrs Type deriving (Eq,Show) data Const_Attrs = Const_Attrs { constName :: String , constInfix :: (Maybe String) , constInfixl :: (Maybe String) , constInfixr :: (Maybe String) , constMixfix_i :: (Maybe String) } deriving (Eq,Show) data App = App (OneOf6 Bound Free Var Const App Abs) (OneOf6 Bound Free Var Const App Abs) deriving (Eq,Show) data Abs = Abs Abs_Attrs (OneOf3 TVar TFree Type) (OneOf6 Bound Free Var Const App Abs) deriving (Eq,Show) data Abs_Attrs = Abs_Attrs { absVname :: String } deriving (Eq,Show) data TVar = TVar TVar_Attrs [Class] deriving (Eq,Show) data TVar_Attrs = TVar_Attrs { tVarName :: String , tVarIndex :: (Maybe String) } deriving (Eq,Show) data TFree = TFree TFree_Attrs [Class] deriving (Eq,Show) data TFree_Attrs = TFree_Attrs { tFreeName :: String } deriving (Eq,Show) data Type = Type Type_Attrs [Type_] deriving (Eq,Show) data Type_Attrs = Type_Attrs { typeName :: String } deriving (Eq,Show) data Type_ = Type_TVar TVar | Type_TFree TFree | Type_Type Type deriving (Eq,Show) data Class = Class { className :: String } deriving (Eq,Show) {-Instance decls-} instance HTypeable IsaExport where toHType _ = Defined "IsaExport" [] [] instance XmlContent IsaExport where toContents (IsaExport as a b c d e) = [CElem (Elem (N "IsaExport") (toAttrs as) (toContents a ++ toContents b ++ toContents c ++ toContents d ++ toContents e)) ()] parseContents = do { e@(Elem _ as _) <- element ["IsaExport"] ; interior e $ return (IsaExport (fromAttrs as)) `apply` parseContents `apply` parseContents `apply` parseContents `apply` parseContents `apply` parseContents } `adjustErr` ("in <IsaExport>, "++) instance XmlAttributes IsaExport_Attrs where fromAttrs as = IsaExport_Attrs { isaExportFile = definiteA fromAttrToStr "IsaExport" "file" as } toAttrs v = catMaybes [ toAttrFrStr "file" (isaExportFile v) ] instance HTypeable Imports where toHType _ = Defined "Imports" [] [] instance XmlContent Imports where toContents (Imports a) = [CElem (Elem (N "Imports") [] (concatMap toContents a)) ()] parseContents = do { e@(Elem _ [] _) <- element ["Imports"] ; interior e $ return (Imports) `apply` many parseContents } `adjustErr` ("in <Imports>, "++) instance HTypeable Import where toHType _ = Defined "Import" [] [] instance XmlContent Import where toContents as = [CElem (Elem (N "Import") (toAttrs as) []) ()] parseContents = do { (Elem _ as []) <- element ["Import"] ; return (fromAttrs as) } `adjustErr` ("in <Import>, "++) instance XmlAttributes Import where fromAttrs as = Import { importName = definiteA fromAttrToStr "Import" "name" as } toAttrs v = catMaybes [ toAttrFrStr "name" (importName v) ] instance HTypeable Consts where toHType _ = Defined "Consts" [] [] instance XmlContent Consts where toContents (Consts a) = [CElem (Elem (N "Consts") [] (concatMap toContents a)) ()] parseContents = do { e@(Elem _ [] _) <- element ["Consts"] ; interior e $ return (Consts) `apply` many parseContents } `adjustErr` ("in <Consts>, "++) instance HTypeable ConstDecl where toHType _ = Defined "ConstDecl" [] [] instance XmlContent ConstDecl where toContents (ConstDecl as a b) = [CElem (Elem (N "ConstDecl") (toAttrs as) (toContents a ++ toContents b)) ()] parseContents = do { e@(Elem _ as _) <- element ["ConstDecl"] ; interior e $ return (ConstDecl (fromAttrs as)) `apply` parseContents `apply` parseContents } `adjustErr` ("in <ConstDecl>, "++) instance XmlAttributes ConstDecl_Attrs where fromAttrs as = ConstDecl_Attrs { constDeclName = definiteA fromAttrToStr "ConstDecl" "name" as } toAttrs v = catMaybes [ toAttrFrStr "name" (constDeclName v) ] instance HTypeable Axioms where toHType _ = Defined "Axioms" [] [] instance XmlContent Axioms where toContents (Axioms a) = [CElem (Elem (N "Axioms") [] (concatMap toContents a)) ()] parseContents = do { e@(Elem _ [] _) <- element ["Axioms"] ; interior e $ return (Axioms) `apply` many parseContents } `adjustErr` ("in <Axioms>, "++) instance HTypeable Theorems where toHType _ = Defined "Theorems" [] [] instance XmlContent Theorems where toContents (Theorems a) = [CElem (Elem (N "Theorems") [] (concatMap toContents a)) ()] parseContents = do { e@(Elem _ [] _) <- element ["Theorems"] ; interior e $ return (Theorems) `apply` many parseContents } `adjustErr` ("in <Theorems>, "++) instance HTypeable Types where toHType _ = Defined "Types" [] [] instance XmlContent Types where toContents (Types a) = [CElem (Elem (N "Types") [] (concatMap toContents a)) ()] parseContents = do { e@(Elem _ [] _) <- element ["Types"] ; interior e $ return (Types) `apply` many parseContents } `adjustErr` ("in <Types>, "++) instance HTypeable NoTerm where toHType _ = Defined "NoTerm" [] [] instance XmlContent NoTerm where toContents NoTerm = [CElem (Elem (N "NoTerm") [] []) ()] parseContents = do { (Elem _ _ []) <- element ["NoTerm"] ; return NoTerm } `adjustErr` ("in <NoTerm>, "++) instance HTypeable Term where toHType _ = Defined "Term" [] [] instance XmlContent Term where toContents (TermBound as a) = [CElem (Elem (N "Term") (toAttrs as) (toContents a) ) ()] toContents (TermFree as a) = [CElem (Elem (N "Term") (toAttrs as) (toContents a) ) ()] toContents (TermVar as a) = [CElem (Elem (N "Term") (toAttrs as) (toContents a) ) ()] toContents (TermConst as a) = [CElem (Elem (N "Term") (toAttrs as) (toContents a) ) ()] toContents (TermApp as a) = [CElem (Elem (N "Term") (toAttrs as) (toContents a) ) ()] toContents (TermAbs as a) = [CElem (Elem (N "Term") (toAttrs as) (toContents a) ) ()] parseContents = do { e@(Elem _ as _) <- element ["Term"] ; interior e $ oneOf [ return (TermBound (fromAttrs as)) `apply` parseContents , return (TermFree (fromAttrs as)) `apply` parseContents , return (TermVar (fromAttrs as)) `apply` parseContents , return (TermConst (fromAttrs as)) `apply` parseContents , return (TermApp (fromAttrs as)) `apply` parseContents , return (TermAbs (fromAttrs as)) `apply` parseContents ] `adjustErr` ("in <Term>, "++) } instance XmlAttributes Term_Attrs where fromAttrs as = Term_Attrs { termName = definiteA fromAttrToStr "Term" "name" as } toAttrs v = catMaybes [ toAttrFrStr "name" (termName v) ] instance HTypeable TypeDecl where toHType _ = Defined "TypeDecl" [] [] instance XmlContent TypeDecl where toContents (TypeDecl as a) = [CElem (Elem (N "TypeDecl") (toAttrs as) (concatMap toContents a)) ()] parseContents = do { e@(Elem _ as _) <- element ["TypeDecl"] ; interior e $ return (TypeDecl (fromAttrs as)) `apply` many parseContents } `adjustErr` ("in <TypeDecl>, "++) instance XmlAttributes TypeDecl_Attrs where fromAttrs as = TypeDecl_Attrs { typeDeclName = definiteA fromAttrToStr "TypeDecl" "name" as } toAttrs v = catMaybes [ toAttrFrStr "name" (typeDeclName v) ] instance HTypeable RecType where toHType _ = Defined "RecType" [] [] instance XmlContent RecType where toContents (RecType as a b) = [CElem (Elem (N "RecType") (toAttrs as) (toContents a ++ toContents b)) ()] parseContents = do { e@(Elem _ as _) <- element ["RecType"] ; interior e $ return (RecType (fromAttrs as)) `apply` parseContents `apply` parseContents } `adjustErr` ("in <RecType>, "++) instance XmlAttributes RecType_Attrs where fromAttrs as = RecType_Attrs { recTypeI = definiteA fromAttrToStr "RecType" "i" as , recTypeName = definiteA fromAttrToStr "RecType" "name" as , recTypeAltname = possibleA fromAttrToStr "altname" as } toAttrs v = catMaybes [ toAttrFrStr "i" (recTypeI v) , toAttrFrStr "name" (recTypeName v) , maybeToAttr toAttrFrStr "altname" (recTypeAltname v) ] instance HTypeable Vars where toHType _ = Defined "Vars" [] [] instance XmlContent Vars where toContents (Vars a) = [CElem (Elem (N "Vars") [] (concatMap toContents a)) ()] parseContents = do { e@(Elem _ [] _) <- element ["Vars"] ; interior e $ return (Vars) `apply` many parseContents } `adjustErr` ("in <Vars>, "++) instance HTypeable Vars_ where toHType _ = Defined "Vars" [] [] instance XmlContent Vars_ where toContents (Vars_DtTFree a) = toContents a toContents (Vars_DtType a) = toContents a toContents (Vars_DtRec a) = toContents a parseContents = oneOf [ return (Vars_DtTFree) `apply` parseContents , return (Vars_DtType) `apply` parseContents , return (Vars_DtRec) `apply` parseContents ] `adjustErr` ("in <Vars>, "++) instance HTypeable DtTFree where toHType _ = Defined "DtTFree" [] [] instance XmlContent DtTFree where toContents as = [CElem (Elem (N "DtTFree") (toAttrs as) []) ()] parseContents = do { (Elem _ as []) <- element ["DtTFree"] ; return (fromAttrs as) } `adjustErr` ("in <DtTFree>, "++) instance XmlAttributes DtTFree where fromAttrs as = DtTFree { dtTFreeS = definiteA fromAttrToStr "DtTFree" "s" as } toAttrs v = catMaybes [ toAttrFrStr "s" (dtTFreeS v) ] instance HTypeable DtType where toHType _ = Defined "DtType" [] [] instance XmlContent DtType where toContents (DtType as a) = [CElem (Elem (N "DtType") (toAttrs as) (concatMap toContents a)) ()] parseContents = do { e@(Elem _ as _) <- element ["DtType"] ; interior e $ return (DtType (fromAttrs as)) `apply` many parseContents } `adjustErr` ("in <DtType>, "++) instance XmlAttributes DtType_Attrs where fromAttrs as = DtType_Attrs { dtTypeS = definiteA fromAttrToStr "DtType" "s" as } toAttrs v = catMaybes [ toAttrFrStr "s" (dtTypeS v) ] instance HTypeable DtType_ where toHType _ = Defined "DtType" [] [] instance XmlContent DtType_ where toContents (DtType_DtTFree a) = toContents a toContents (DtType_DtType a) = toContents a toContents (DtType_DtRec a) = toContents a parseContents = oneOf [ return (DtType_DtTFree) `apply` parseContents , return (DtType_DtType) `apply` parseContents , return (DtType_DtRec) `apply` parseContents ] `adjustErr` ("in <DtType>, "++) instance HTypeable DtRec where toHType _ = Defined "DtRec" [] [] instance XmlContent DtRec where toContents as = [CElem (Elem (N "DtRec") (toAttrs as) []) ()] parseContents = do { (Elem _ as []) <- element ["DtRec"] ; return (fromAttrs as) } `adjustErr` ("in <DtRec>, "++) instance XmlAttributes DtRec where fromAttrs as = DtRec { dtRecI = definiteA fromAttrToStr "DtRec" "i" as } toAttrs v = catMaybes [ toAttrFrStr "i" (dtRecI v) ] instance HTypeable Constructors where toHType _ = Defined "Constructors" [] [] instance XmlContent Constructors where toContents (Constructors a) = [CElem (Elem (N "Constructors") [] (concatMap toContents a)) ()] parseContents = do { e@(Elem _ [] _) <- element ["Constructors"] ; interior e $ return (Constructors) `apply` many parseContents } `adjustErr` ("in <Constructors>, "++) instance HTypeable Constructor where toHType _ = Defined "Constructor" [] [] instance XmlContent Constructor where toContents (Constructor as a) = [CElem (Elem (N "Constructor") (toAttrs as) (concatMap toContents a)) ()] parseContents = do { e@(Elem _ as _) <- element ["Constructor"] ; interior e $ return (Constructor (fromAttrs as)) `apply` many parseContents } `adjustErr` ("in <Constructor>, "++) instance XmlAttributes Constructor_Attrs where fromAttrs as = Constructor_Attrs { constructorVal = definiteA fromAttrToStr "Constructor" "val" as } toAttrs v = catMaybes [ toAttrFrStr "val" (constructorVal v) ] instance HTypeable Constructor_ where toHType _ = Defined "Constructor" [] [] instance XmlContent Constructor_ where toContents (Constructor_DtTFree a) = toContents a toContents (Constructor_DtType a) = toContents a toContents (Constructor_DtRec a) = toContents a parseContents = oneOf [ return (Constructor_DtTFree) `apply` parseContents , return (Constructor_DtType) `apply` parseContents , return (Constructor_DtRec) `apply` parseContents ] `adjustErr` ("in <Constructor>, "++) instance HTypeable Bound where toHType _ = Defined "Bound" [] [] instance XmlContent Bound where toContents as = [CElem (Elem (N "Bound") (toAttrs as) []) ()] parseContents = do { (Elem _ as []) <- element ["Bound"] ; return (fromAttrs as) } `adjustErr` ("in <Bound>, "++) instance XmlAttributes Bound where fromAttrs as = Bound { boundIndex = definiteA fromAttrToStr "Bound" "index" as } toAttrs v = catMaybes [ toAttrFrStr "index" (boundIndex v) ] instance HTypeable Free where toHType _ = Defined "Free" [] [] instance XmlContent Free where toContents (FreeTVar as a) = [CElem (Elem (N "Free") (toAttrs as) (toContents a) ) ()] toContents (FreeTFree as a) = [CElem (Elem (N "Free") (toAttrs as) (toContents a) ) ()] toContents (FreeType as a) = [CElem (Elem (N "Free") (toAttrs as) (toContents a) ) ()] parseContents = do { e@(Elem _ as _) <- element ["Free"] ; interior e $ oneOf [ return (FreeTVar (fromAttrs as)) `apply` parseContents , return (FreeTFree (fromAttrs as)) `apply` parseContents , return (FreeType (fromAttrs as)) `apply` parseContents ] `adjustErr` ("in <Free>, "++) } instance XmlAttributes Free_Attrs where fromAttrs as = Free_Attrs { freeName = definiteA fromAttrToStr "Free" "name" as } toAttrs v = catMaybes [ toAttrFrStr "name" (freeName v) ] instance HTypeable Var where toHType _ = Defined "Var" [] [] instance XmlContent Var where toContents (VarTVar as a) = [CElem (Elem (N "Var") (toAttrs as) (toContents a) ) ()] toContents (VarTFree as a) = [CElem (Elem (N "Var") (toAttrs as) (toContents a) ) ()] toContents (VarType as a) = [CElem (Elem (N "Var") (toAttrs as) (toContents a) ) ()] parseContents = do { e@(Elem _ as _) <- element ["Var"] ; interior e $ oneOf [ return (VarTVar (fromAttrs as)) `apply` parseContents , return (VarTFree (fromAttrs as)) `apply` parseContents , return (VarType (fromAttrs as)) `apply` parseContents ] `adjustErr` ("in <Var>, "++) } instance XmlAttributes Var_Attrs where fromAttrs as = Var_Attrs { varName = definiteA fromAttrToStr "Var" "name" as , varIndex = possibleA fromAttrToStr "index" as } toAttrs v = catMaybes [ toAttrFrStr "name" (varName v) , maybeToAttr toAttrFrStr "index" (varIndex v) ] instance HTypeable Const where toHType _ = Defined "Const" [] [] instance XmlContent Const where toContents (ConstTVar as a) = [CElem (Elem (N "Const") (toAttrs as) (toContents a) ) ()] toContents (ConstTFree as a) = [CElem (Elem (N "Const") (toAttrs as) (toContents a) ) ()] toContents (ConstType as a) = [CElem (Elem (N "Const") (toAttrs as) (toContents a) ) ()] parseContents = do { e@(Elem _ as _) <- element ["Const"] ; interior e $ oneOf [ return (ConstTVar (fromAttrs as)) `apply` parseContents , return (ConstTFree (fromAttrs as)) `apply` parseContents , return (ConstType (fromAttrs as)) `apply` parseContents ] `adjustErr` ("in <Const>, "++) } instance XmlAttributes Const_Attrs where fromAttrs as = Const_Attrs { constName = definiteA fromAttrToStr "Const" "name" as , constInfix = possibleA fromAttrToStr "infix" as , constInfixl = possibleA fromAttrToStr "infixl" as , constInfixr = possibleA fromAttrToStr "infixr" as , constMixfix_i = possibleA fromAttrToStr "mixfix_i" as } toAttrs v = catMaybes [ toAttrFrStr "name" (constName v) , maybeToAttr toAttrFrStr "infix" (constInfix v) , maybeToAttr toAttrFrStr "infixl" (constInfixl v) , maybeToAttr toAttrFrStr "infixr" (constInfixr v) , maybeToAttr toAttrFrStr "mixfix_i" (constMixfix_i v) ] instance HTypeable App where toHType _ = Defined "App" [] [] instance XmlContent App where toContents (App a b) = [CElem (Elem (N "App") [] (toContents a ++ toContents b)) ()] parseContents = do { e@(Elem _ [] _) <- element ["App"] ; interior e $ return (App) `apply` parseContents `apply` parseContents } `adjustErr` ("in <App>, "++) instance HTypeable Abs where toHType _ = Defined "Abs" [] [] instance XmlContent Abs where toContents (Abs as a b) = [CElem (Elem (N "Abs") (toAttrs as) (toContents a ++ toContents b)) ()] parseContents = do { e@(Elem _ as _) <- element ["Abs"] ; interior e $ return (Abs (fromAttrs as)) `apply` parseContents `apply` parseContents } `adjustErr` ("in <Abs>, "++) instance XmlAttributes Abs_Attrs where fromAttrs as = Abs_Attrs { absVname = definiteA fromAttrToStr "Abs" "vname" as } toAttrs v = catMaybes [ toAttrFrStr "vname" (absVname v) ] instance HTypeable TVar where toHType _ = Defined "TVar" [] [] instance XmlContent TVar where toContents (TVar as a) = [CElem (Elem (N "TVar") (toAttrs as) (concatMap toContents a)) ()] parseContents = do { e@(Elem _ as _) <- element ["TVar"] ; interior e $ return (TVar (fromAttrs as)) `apply` many parseContents } `adjustErr` ("in <TVar>, "++) instance XmlAttributes TVar_Attrs where fromAttrs as = TVar_Attrs { tVarName = definiteA fromAttrToStr "TVar" "name" as , tVarIndex = possibleA fromAttrToStr "index" as } toAttrs v = catMaybes [ toAttrFrStr "name" (tVarName v) , maybeToAttr toAttrFrStr "index" (tVarIndex v) ] instance HTypeable TFree where toHType _ = Defined "TFree" [] [] instance XmlContent TFree where toContents (TFree as a) = [CElem (Elem (N "TFree") (toAttrs as) (concatMap toContents a)) ()] parseContents = do { e@(Elem _ as _) <- element ["TFree"] ; interior e $ return (TFree (fromAttrs as)) `apply` many parseContents } `adjustErr` ("in <TFree>, "++) instance XmlAttributes TFree_Attrs where fromAttrs as = TFree_Attrs { tFreeName = definiteA fromAttrToStr "TFree" "name" as } toAttrs v = catMaybes [ toAttrFrStr "name" (tFreeName v) ] instance HTypeable Type where toHType _ = Defined "Type" [] [] instance XmlContent Type where toContents (Type as a) = [CElem (Elem (N "Type") (toAttrs as) (concatMap toContents a)) ()] parseContents = do { e@(Elem _ as _) <- element ["Type"] ; interior e $ return (Type (fromAttrs as)) `apply` many parseContents } `adjustErr` ("in <Type>, "++) instance XmlAttributes Type_Attrs where fromAttrs as = Type_Attrs { typeName = definiteA fromAttrToStr "Type" "name" as } toAttrs v = catMaybes [ toAttrFrStr "name" (typeName v) ] instance HTypeable Type_ where toHType _ = Defined "Type" [] [] instance XmlContent Type_ where toContents (Type_TVar a) = toContents a toContents (Type_TFree a) = toContents a toContents (Type_Type a) = toContents a parseContents = oneOf [ return (Type_TVar) `apply` parseContents , return (Type_TFree) `apply` parseContents , return (Type_Type) `apply` parseContents ] `adjustErr` ("in <Type>, "++) instance HTypeable Class where toHType _ = Defined "class" [] [] instance XmlContent Class where toContents as = [CElem (Elem (N "class") (toAttrs as) []) ()] parseContents = do { (Elem _ as []) <- element ["class"] ; return (fromAttrs as) } `adjustErr` ("in <class>, "++) instance XmlAttributes Class where fromAttrs as = Class { className = definiteA fromAttrToStr "class" "name" as } toAttrs v = catMaybes [ toAttrFrStr "name" (className v) ] {-Done-}
nevrenato/Hets_Fork
Isabelle/IsaExport.hs
gpl-2.0
25,548
0
19
7,439
8,710
4,568
4,142
618
0
{- | Module : $Header$ Description : HasCASL's sublogics Copyright : (c) Sonja Groening, C. Maeder, and Uni Bremen 2002-2006 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : experimental Portability : portable This module provides the sublogic functions (as required by Logic.hs) for HasCASL. The functions allow to compute the minimal sublogic needed by a given element, to check whether an item is part of a given sublogic, and -- not yet -- to project an element into a given sublogic. -} module HasCASL.Sublogic ( -- * datatypes Sublogic (..) , Formulas (..) , Classes (..) -- * functions for SemiLatticeWithTop instance , topLogic , sublogic_max -- * combining sublogics restrictions , sublogic_min , sublogicUp , need_hol -- * further sublogic constants , bottom , noSubtypes , noClasses , totalFuns , caslLogic -- * functions for Logic instance -- ** sublogic to string converstion , sublogic_name -- ** list of all sublogics , sublogics_all -- ** checks if element is in given sublogic , in_basicSpec , in_sentence , in_symbItems , in_symbMapItems , in_env , in_morphism , in_symbol -- * computes the sublogic of a given element , sl_basicSpec , sl_sentence , sl_symbItems , sl_symbMapItems , sl_env , sl_morphism , sl_symbol ) where import qualified Data.Map as Map import qualified Data.Set as Set import Common.AS_Annotation import Common.Id import HasCASL.As import HasCASL.AsUtils import HasCASL.Le import HasCASL.Builtin import HasCASL.FoldTerm -- | formula kinds of HasCASL sublogics data Formulas = Atomic -- ^ atomic logic | Horn -- ^ positive conditional logic | GHorn -- ^ generalized positive conditional logic | FOL -- ^ first-order logic | HOL -- ^ higher-order logic deriving (Show, Eq, Ord) data Classes = NoClasses | SimpleTypeClasses | ConstructorClasses deriving (Show, Eq, Ord) -- | HasCASL sublogics data Sublogic = Sublogic { has_sub :: Bool -- ^ subsorting , has_part :: Bool -- ^ partiality , has_eq :: Bool -- ^ equality , has_pred :: Bool -- ^ predicates , type_classes :: Classes , has_polymorphism :: Bool , has_type_constructors :: Bool , has_products :: Bool , which_logic :: Formulas } deriving (Show, Eq, Ord) -- * special sublogic elements -- | top element topLogic :: Sublogic topLogic = Sublogic { has_sub = True , has_part = True , has_eq = True , has_pred = True , type_classes = ConstructorClasses , has_polymorphism = True , has_type_constructors = True , has_products = True , which_logic = HOL } -- | top sublogic without subtypes noSubtypes :: Sublogic noSubtypes = topLogic { has_sub = False } -- | top sublogic without type classes noClasses :: Sublogic noClasses = topLogic { type_classes = NoClasses } -- | top sublogic without partiality totalFuns :: Sublogic totalFuns = topLogic { has_part = False } caslLogic :: Sublogic caslLogic = noClasses { has_polymorphism = False , has_type_constructors = False , has_products = False , which_logic = FOL } -- | bottom sublogic bottom :: Sublogic bottom = Sublogic { has_sub = False , has_part = False , has_eq = False , has_pred = False , type_classes = NoClasses , has_polymorphism = False , has_type_constructors = False , has_products = False , which_logic = Atomic } {- the following are used to add a needed feature to a given sublogic via sublogic_max, i.e. (sublogic_max given needs_part) will force partiality in addition to what features given already has included -} -- | minimal sublogic with partiality need_part :: Sublogic need_part = bottom { has_part = True } -- | minimal sublogic with equality need_eq :: Sublogic need_eq = bottom { has_eq = True } -- | minimal sublogic with predicates need_pred :: Sublogic need_pred = bottom { has_pred = True } -- | minimal sublogic with subsorting need_sub :: Sublogic need_sub = need_pred { has_sub = True } -- | minimal sublogic with polymorhism need_polymorphism :: Sublogic need_polymorphism = bottom { has_polymorphism = True } -- | minimal sublogic with simple type classes simpleTypeClasses :: Sublogic simpleTypeClasses = need_polymorphism { type_classes = SimpleTypeClasses } -- | minimal sublogic with constructor classes constructorClasses :: Sublogic constructorClasses = need_polymorphism { type_classes = ConstructorClasses } -- | minimal sublogic with type constructors need_type_constructors :: Sublogic need_type_constructors = bottom { has_type_constructors = True, has_products = True } need_product_type_constructor :: Sublogic need_product_type_constructor = bottom { has_products = True } need_horn :: Sublogic need_horn = bottom { which_logic = Horn } need_ghorn :: Sublogic need_ghorn = bottom { which_logic = GHorn } need_fol :: Sublogic need_fol = bottom { which_logic = FOL } need_hol :: Sublogic need_hol = need_pred { which_logic = HOL } -- | make sublogic consistent w.r.t. illegal combinations sublogicUp :: Sublogic -> Sublogic sublogicUp s' = let s = if has_type_constructors s' then s' { has_products = True } else s' in if which_logic s == HOL || has_sub s then s { has_pred = True } else s -- | generate a list of all sublogics for HasCASL sublogics_all :: [Sublogic] sublogics_all = let bools = [False, True] in [ Sublogic { has_sub = sub , has_part = part , has_eq = eq , has_pred = pre , type_classes = tyCl , has_polymorphism = poly , has_type_constructors = tyCon , has_products = prods || tyCon , which_logic = logic } | (tyCl, poly) <- [(NoClasses, False), (NoClasses, True), (SimpleTypeClasses, True), (ConstructorClasses, True)] , tyCon <- bools , prods <- bools , sub <- bools , part <- bools , eq <- bools , pre <- bools , logic <- [Atomic, Horn, GHorn, FOL, HOL] , pre || logic /= HOL && not sub ] -- | conversion functions to String formulas_name :: Bool -> Formulas -> String formulas_name hasPred f = case f of HOL -> "HOL" FOL -> if hasPred then "FOL" else "FOAlg" _ -> case f of Atomic -> if hasPred then "Atom" else "Eq" _ -> (case f of GHorn -> ("G" ++) _ -> id) $ if hasPred then "Horn" else "Cond" -- | the sublogic name as a singleton string list sublogic_name :: Sublogic -> String sublogic_name x = (if has_sub x then "Sub" else "") ++ (if has_part x then "P" else "") ++ (case type_classes x of NoClasses -> if has_polymorphism x then "Poly" else "" SimpleTypeClasses -> "TyCl" ConstructorClasses -> "CoCl") ++ (if has_type_constructors x then "TyCons" else "") ++ (if has_products x then "Prods" else "") ++ formulas_name (has_pred x) (which_logic x) ++ (if has_eq x then "=" else "") -- * join functions sublogic_join :: (Bool -> Bool -> Bool) -> (Classes -> Classes -> Classes) -> (Formulas -> Formulas -> Formulas) -> Sublogic -> Sublogic -> Sublogic sublogic_join joinB joinC joinF a b = Sublogic { has_sub = joinB (has_sub a) $ has_sub b , has_part = joinB (has_part a) $ has_part b , has_eq = joinB (has_eq a) $ has_eq b , has_pred = joinB (has_pred a) $ has_pred b , type_classes = joinC (type_classes a) $ type_classes b , has_polymorphism = joinB (has_polymorphism a) $ has_polymorphism b , has_type_constructors = joinB (has_type_constructors a) $ has_type_constructors b , has_products = has_products a || has_products b || has_type_constructors a || has_type_constructors b , which_logic = joinF (which_logic a) $ which_logic b } sublogic_max :: Sublogic -> Sublogic -> Sublogic sublogic_max = sublogic_join max max max sublogic_min :: Sublogic -> Sublogic -> Sublogic sublogic_min = sublogic_join min min min -- | compute union sublogic from a list of sublogics comp_list :: [Sublogic] -> Sublogic comp_list = foldl sublogic_max bottom -- Functions to analyse formulae {- --------------------------------------------------------------------------- These functions are based on Till Mossakowski's paper "Sublanguages of CASL", which is CoFI Note L-7. The functions implement an adaption of the reduced grammar given there for formulae in a specific expression logic by, checking whether a formula would match the productions from the grammar. Which function checks for which nonterminal from the paper is given as a comment before each function. They are adapted for HasCASL, especially HasCASLs abstract syntax (As.hs) --------------------------------------------------------------------------- -} -- Atomic Logic (subsection 3.4 of the paper) isPredication :: Term -> Bool isPredication = foldTerm FoldRec { foldQualVar = \ _ _ -> True , foldQualOp = \ _ b (PolyId i _ _) t _ _ _ -> b /= Fun && notElem (i, t) bList , foldApplTerm = \ _ b1 b2 _ -> b1 && b2 , foldTupleTerm = \ _ bs _ -> and bs , foldTypedTerm = \ _ b q _ _ -> q /= InType && b , foldAsPattern = \ _ _ _ _ -> False , foldQuantifiedTerm = \ _ _ _ _ _ -> False , foldLambdaTerm = \ _ _ _ _ _ -> False , foldCaseTerm = \ _ _ _ _ -> False , foldLetTerm = \ _ _ _ _ _ -> False , foldResolvedMixTerm = \ _ i _ bs _ -> notElem i (map fst bList) && and bs , foldTermToken = \ _ _ -> True , foldMixTypeTerm = \ _ q _ _ -> q /= InType , foldMixfixTerm = const and , foldBracketTerm = \ _ _ bs _ -> and bs , foldProgEq = \ _ _ _ _ -> False } -- FORMULA, P-ATOM is_atomic_t :: Term -> Bool is_atomic_t term = case term of QuantifiedTerm q _ t _ | is_atomic_q q && is_atomic_t t -> True -- P-Conjunction and ExEq ApplTerm (QualOp _ (PolyId i _ _) t _ _ _) arg _ | (case arg of TupleTerm ts@[_, _] _ -> i == andId && t == logType && all is_atomic_t ts || i == exEq && t == eqType _ -> False) || i == defId && t == defType -> True QualOp _ (PolyId i _ _) t _ _ _ | i == trueId && t == unitTypeScheme -> True _ -> isPredication term -- QUANTIFIER is_atomic_q :: Quantifier -> Bool is_atomic_q q = case q of Universal -> True _ -> False -- Positive Conditional Logic (subsection 3.2 in the paper) -- FORMULA is_horn_t :: Term -> Bool is_horn_t term = case term of QuantifiedTerm q _ f _ -> is_atomic_q q && is_horn_t f ApplTerm (QualOp _ (PolyId i _ _) t _ _ _) (TupleTerm [t1, t2] _) _ | i == implId && t == logType && is_horn_p_conj t1 && is_horn_a t2 -> True _ -> is_atomic_t term -- P-CONJUNCTION is_horn_p_conj :: Term -> Bool is_horn_p_conj term = case term of ApplTerm (QualOp _ (PolyId i _ _) t _ _ _) (TupleTerm ts@[_, _] _) _ | i == andId && t == logType && all is_horn_a ts -> True _ -> is_atomic_t term -- ATOM is_horn_a :: Term -> Bool is_horn_a term = case term of QualOp _ (PolyId i _ _) t _ _ _ | i == trueId && t == unitTypeScheme -> True ApplTerm (QualOp _ (PolyId i _ _) t _ _ _) arg _ | (case arg of TupleTerm [_, _] _ -> isEq i && t == eqType _ -> False) || i == defId && t == defType -> True _ -> is_atomic_t term -- P-ATOM is_horn_p_a :: Term -> Bool is_horn_p_a term = case term of QualOp _ (PolyId i _ _) t _ _ _ | i == trueId && t == unitTypeScheme -> True ApplTerm (QualOp _ (PolyId i _ _) t _ _ _) arg _ | (case arg of TupleTerm [_, _] _ -> i == exEq && t == eqType _ -> False) || i == defId && t == defType -> True _ -> is_atomic_t term -- Generalized Positive Conditional Logic (subsection 3.3 of the paper) -- FORMULA, ATOM is_ghorn_t :: Term -> Bool is_ghorn_t term = case term of QuantifiedTerm q _ t _ -> is_atomic_q q && is_ghorn_t t ApplTerm (QualOp _ (PolyId i _ _) t _ _ _) arg _ | (case arg of TupleTerm f@[f1, f2] _ -> t == logType && (i == andId && (is_ghorn_c_conj f || is_ghorn_f_conj f) || i == implId && is_ghorn_prem f1 && is_ghorn_conc f2 || i == eqvId && is_ghorn_prem f1 && is_ghorn_prem f2) || t == eqType && isEq i _ -> False) || t == defType && i == defId -> True _ -> is_atomic_t term -- C-CONJUNCTION is_ghorn_c_conj :: [Term] -> Bool is_ghorn_c_conj = all is_ghorn_conc -- F-CONJUNCTION is_ghorn_f_conj :: [Term] -> Bool is_ghorn_f_conj = all is_ghorn_t -- P-CONJUNCTION is_ghorn_p_conj :: [Term] -> Bool is_ghorn_p_conj = all is_ghorn_prem -- PREMISE is_ghorn_prem :: Term -> Bool is_ghorn_prem term = case term of ApplTerm (QualOp _ (PolyId i _ _) t _ _ _) (TupleTerm ts@[_, _] _) _ -> i == andId && t == logType && is_ghorn_p_conj ts _ -> is_horn_p_a term -- CONCLUSION is_ghorn_conc :: Term -> Bool is_ghorn_conc term = case term of ApplTerm (QualOp _ (PolyId i _ _) t _ _ _) (TupleTerm ts@[_, _] _) _ -> i == andId && t == logType && is_ghorn_c_conj ts _ -> is_horn_a term is_fol_t :: Term -> Bool is_fol_t t = case t of LambdaTerm {} -> False CaseTerm {} -> False LetTerm {} -> False _ -> True {- FOL: no lambda/let/case, no higher types (i.e. all types are basic, tuples, or tuple -> basic) -} -- | compute logic of a formula by checking all logics in turn get_logic :: Term -> Sublogic get_logic t | is_atomic_t t = bottom | is_horn_t t = need_horn | is_ghorn_t t = need_ghorn | is_fol_t t = need_fol | otherwise = need_hol {- Functions to compute minimal sublogic for a given element; these work by recursing into all subelements -} sl_basicSpec :: BasicSpec -> Sublogic sl_basicSpec (BasicSpec l) = sublogicUp $ comp_list $ map (sl_basicItem . item) l sl_basicItem :: BasicItem -> Sublogic sl_basicItem bIt = case bIt of SigItems l -> sl_sigItems l ProgItems l _ -> comp_list $ map (sl_progEq . item) l ClassItems _ l _ -> comp_list $ map (sl_classItem . item) l GenVarItems l _ -> comp_list $ map sl_genVarDecl l FreeDatatype l _ -> comp_list $ map (sl_datatypeDecl . item) l GenItems l _ -> comp_list $ map (sl_sigItems . item) l AxiomItems l m _ -> comp_list $ map sl_genVarDecl l ++ map (sl_term . item) m Internal l _ -> comp_list $ map (sl_basicItem . item) l sl_sigItems :: SigItems -> Sublogic sl_sigItems sIt = case sIt of TypeItems i l _ -> comp_list $ sl_instance i : map (sl_typeItem . item) l OpItems b l _ -> comp_list $ sl_opBrand b : map (sl_opItem . item) l sl_opBrand :: OpBrand -> Sublogic sl_opBrand o = case o of Pred -> need_pred _ -> bottom sl_instance :: Instance -> Sublogic sl_instance i = case i of Instance -> simpleTypeClasses _ -> bottom sl_classItem :: ClassItem -> Sublogic sl_classItem (ClassItem c l _) = comp_list $ sl_classDecl c : map (sl_basicItem . item) l sl_classDecl :: ClassDecl -> Sublogic sl_classDecl (ClassDecl _ k _) = case k of ClassKind _ -> simpleTypeClasses FunKind {} -> constructorClasses -- don't check the variance or kind of builtin type constructors sl_Variance :: Variance -> Sublogic sl_Variance v = case v of NonVar -> bottom _ -> need_sub sl_AnyKind :: (a -> Sublogic) -> AnyKind a -> Sublogic sl_AnyKind f k = case k of ClassKind i -> f i FunKind v k1 k2 _ -> comp_list [sl_Variance v, sl_AnyKind f k1, sl_AnyKind f k2] sl_Rawkind :: RawKind -> Sublogic sl_Rawkind = sl_AnyKind (const bottom) sl_kind :: Kind -> Sublogic sl_kind = sl_AnyKind $ \ i -> if i == universeId then bottom else simpleTypeClasses sl_typeItem :: TypeItem -> Sublogic sl_typeItem tyIt = case tyIt of TypeDecl l k _ -> comp_list $ sl_kind k : map sl_typePattern l SubtypeDecl l _ _ -> comp_list $ need_sub : map sl_typePattern l IsoDecl l _ -> comp_list $ need_sub : map sl_typePattern l SubtypeDefn tp _ t term _ -> comp_list [ need_sub , sl_typePattern tp , sl_type t , sl_term $ item term ] AliasType tp (Just k) ts _ -> comp_list [ sl_kind k , sl_typePattern tp , sl_typeScheme ts ] AliasType tp Nothing ts _ -> sublogic_max (sl_typePattern tp) $ sl_typeScheme ts Datatype dDecl -> sl_datatypeDecl dDecl sl_typePattern :: TypePattern -> Sublogic sl_typePattern tp = case tp of TypePattern _ l _ -> comp_list $ map sl_typeArg l -- non-empty args --> type constructor! MixfixTypePattern l -> comp_list $ map sl_typePattern l BracketTypePattern _ l _ -> comp_list $ map sl_typePattern l TypePatternArg _ _ -> need_polymorphism _ -> bottom sl_type :: Type -> Sublogic sl_type = sl_BasicFun sl_Basictype :: Type -> Sublogic sl_Basictype ty = case getTypeAppl ty of (TypeName tid _ _, _) | isProductId tid -> need_product_type_constructor _ -> case ty of TypeName _ k v -> sublogic_max (if v /= 0 then need_polymorphism else bottom) $ sl_Rawkind k KindedType t k _ -> comp_list $ sl_Basictype t : map sl_kind (Set.toList k) ExpandedType _ t -> sl_Basictype t TypeAbs v t _ -> comp_list [ need_type_constructors , sl_typeArg v , sl_Basictype t ] BracketType Parens [t] _ -> sl_Basictype t _ -> case getTypeAppl ty of (TypeName ide _ _, args) -> comp_list $ (if isArrow ide || ide == lazyTypeId then need_hol else need_type_constructors) : map sl_Basictype args (_, []) -> bottom (t, args) -> comp_list $ sl_Basictype t : map sl_Basictype args sl_BasicProd :: Type -> Sublogic sl_BasicProd ty = case getTypeAppl ty of (TypeName ide _ _, tyArgs@(_ : _ : _)) | isProductIdWithArgs ide $ length tyArgs -> comp_list $ map sl_Basictype tyArgs _ -> sl_Basictype ty isAnyUnitType :: Type -> Bool isAnyUnitType ty = case ty of BracketType Parens [] _ -> True TypeToken t -> tokStr t == unitTypeS _ -> ty == unitType sl_BasicFun :: Type -> Sublogic sl_BasicFun ty = case getTypeAppl ty of (TypeName ide _ _, [arg, res]) | isArrow ide -> comp_list [ if isPartialArrow ide then if isAnyUnitType res then need_pred else need_part else bottom , sl_BasicProd arg , sl_Basictype res ] _ -> sl_Basictype ty -- FOL, no higher types, all types are basic, tuples, or tuple -> basic sl_typeScheme :: TypeScheme -> Sublogic sl_typeScheme (TypeScheme l t _) = comp_list $ sl_type t : map sl_typeArg l sl_opItem :: OpItem -> Sublogic sl_opItem o = case o of OpDecl l t m _ -> comp_list $ sl_typeScheme t : map sl_opId l ++ map sl_opAttr m OpDefn i v ts t _ -> comp_list $ [ sl_opId i , sl_typeScheme ts , sl_term t ] ++ map sl_varDecl (concat v) sl_partiality :: Partiality -> Sublogic sl_partiality p = case p of Partial -> need_part Total -> bottom sl_opAttr :: OpAttr -> Sublogic sl_opAttr a = case a of UnitOpAttr t _ -> sl_term t _ -> need_eq sl_datatypeDecl :: DatatypeDecl -> Sublogic sl_datatypeDecl (DatatypeDecl t k l c _) = comp_list $ [ if null c then bottom else simpleTypeClasses , sl_typePattern t , sl_kind k ] ++ map (sl_alternative . item) l sl_alternative :: Alternative -> Sublogic sl_alternative a = case a of Constructor _ l p _ -> comp_list $ sl_partiality p : map sl_component (concat l) Subtype l _ -> comp_list $ need_sub : map sl_type l sl_component :: Component -> Sublogic sl_component s = case s of Selector _ p t _ _ -> sublogic_max (sl_partiality p) $ sl_type t NoSelector t -> sl_type t sl_term :: Term -> Sublogic sl_term t = sublogic_max (get_logic t) $ sl_t t {- typed in- or as-terms would also indicate subtyping but we rely on the subtypes in the signature -} sl_t :: Term -> Sublogic sl_t trm = case trm of QualVar vd -> sl_varDecl vd QualOp b i@(PolyId ri _ _) t _ _ _ -> if elem ri $ map fst bList then sl_opId i else comp_list [ sl_opBrand b , sl_opId i , sl_typeScheme t ] ApplTerm t1 t2 _ -> case getAppl trm of Just (i, _, arg) | elem i $ map fst bList -> comp_list (map sl_t arg) _ -> sublogic_max (sl_t t1) $ sl_t t2 TupleTerm l _ -> comp_list $ map sl_t l TypedTerm t _ ty _ -> sublogic_max (sl_t t) $ sl_type ty QuantifiedTerm _ l t _ -> comp_list $ sl_t t : map sl_genVarDecl l LambdaTerm l p t _ -> comp_list $ sl_partiality p : sl_t t : map sl_t l CaseTerm t l _ -> comp_list $ sl_t t : map sl_progEq l ++ map sl_progEq l LetTerm _ l t _ -> comp_list $ sl_t t : map sl_progEq l MixTypeTerm _ t _ -> sl_type t MixfixTerm l -> comp_list $ map sl_t l BracketTerm _ l _ -> comp_list $ map sl_t l AsPattern vd p2 _ -> sublogic_max (sl_varDecl vd) $ sl_t p2 _ -> bottom sl_progEq :: ProgEq -> Sublogic sl_progEq (ProgEq p t _) = sublogic_max (sl_t p) (sl_t t) sl_varDecl :: VarDecl -> Sublogic sl_varDecl (VarDecl _ t _ _) = sl_type t sl_varKind :: VarKind -> Sublogic sl_varKind vk = case vk of VarKind k -> sl_kind k Downset t -> sublogic_max need_sub $ sl_type t _ -> bottom sl_typeArg :: TypeArg -> Sublogic sl_typeArg (TypeArg _ _ k _ _ _ _) = sublogic_max need_polymorphism (sl_varKind k) sl_genVarDecl :: GenVarDecl -> Sublogic sl_genVarDecl g = case g of GenVarDecl v -> sl_varDecl v GenTypeVarDecl v -> sl_typeArg v isEq :: Id -> Bool isEq = (`elem` [exEq, eqId]) sl_opId :: PolyId -> Sublogic sl_opId (PolyId i tys _) | isEq i = need_eq | elem i [botId, defId, resId] = need_part | elem i $ map fst bList = bottom | otherwise = comp_list $ map sl_typeArg tys sl_symbItems :: SymbItems -> Sublogic sl_symbItems (SymbItems k l _ _) = comp_list $ sl_symbKind k : map sl_symb l sl_symbMapItems :: SymbMapItems -> Sublogic sl_symbMapItems (SymbMapItems k l _ _) = comp_list $ sl_symbKind k : map sl_symbOrMap l sl_symbKind :: SymbKind -> Sublogic sl_symbKind k = case k of SyKpred -> need_pred SyKclass -> simpleTypeClasses _ -> bottom sl_symb :: Symb -> Sublogic sl_symb s = case s of Symb _ Nothing _ -> bottom Symb _ (Just l) _ -> sl_symbType l sl_symbType :: SymbType -> Sublogic sl_symbType (SymbType t) = sl_typeScheme t sl_symbOrMap :: SymbOrMap -> Sublogic sl_symbOrMap m = case m of SymbOrMap s Nothing _ -> sl_symb s SymbOrMap s (Just t) _ -> sublogic_max (sl_symb s) $ sl_symb t {- the maps have no influence since all sorts,ops,preds in them must also appear in the signatures, so any features needed by them will be included by just checking the signatures -} sl_env :: Env -> Sublogic sl_env e = sublogicUp $ comp_list $ (if Map.null $ classMap e then bottom else simpleTypeClasses) : map sl_typeInfo (Map.elems $ typeMap e) ++ map sl_opInfos (Map.elems $ assumps e) sl_typeInfo :: TypeInfo -> Sublogic sl_typeInfo t = sublogic_max (if Set.null $ superTypes t then bottom else need_sub) $ sl_typeDefn $ typeDefn t sl_typeDefn :: TypeDefn -> Sublogic sl_typeDefn d = case d of DatatypeDefn de -> sl_dataEntry de AliasTypeDefn t -> sl_type t _ -> bottom sl_dataEntry :: DataEntry -> Sublogic sl_dataEntry (DataEntry _ _ _ l _ m) = comp_list $ map sl_typeArg l ++ map sl_altDefn (Set.toList m) sl_opInfos :: Set.Set OpInfo -> Sublogic sl_opInfos = comp_list . map sl_opInfo . Set.toList sl_opInfo :: OpInfo -> Sublogic sl_opInfo o = comp_list $ sl_typeScheme (opType o) : sl_opDefn (opDefn o) : map sl_opAttr (Set.toList $ opAttrs o) sl_opDefn :: OpDefn -> Sublogic sl_opDefn o = case o of NoOpDefn b -> sl_opBrand b SelectData l _ -> comp_list $ map sl_constrInfo $ Set.toList l Definition b t -> sublogic_max (sl_opBrand b) $ sl_term t _ -> bottom sl_constrInfo :: ConstrInfo -> Sublogic sl_constrInfo = sl_typeScheme . constrType sl_sentence :: Sentence -> Sublogic sl_sentence s = sublogicUp $ case s of Formula t -> sl_term t ProgEqSen _ ts pq -> sublogic_max (sl_typeScheme ts) $ sl_progEq pq DatatypeSen l -> comp_list $ map sl_dataEntry l {- a missing constructor identifier also indicates subtyping but checking super types is enough for subtype detection -} sl_altDefn :: AltDefn -> Sublogic sl_altDefn (Construct _ l p m) = comp_list $ sl_partiality p : map sl_type l ++ map sl_selector (concat m) sl_selector :: Selector -> Sublogic sl_selector (Select _ t p) = sublogic_max (sl_type t) $ sl_partiality p sl_morphism :: Morphism -> Sublogic sl_morphism m = sublogic_max (sl_env $ msource m) $ sl_env $ mtarget m sl_symbol :: Symbol -> Sublogic sl_symbol (Symbol _ t) = sl_symbolType t sl_symbolType :: SymbolType -> Sublogic sl_symbolType s = case s of OpAsItemType t -> sl_typeScheme t ClassAsItemType _ -> simpleTypeClasses _ -> bottom -- | check if the second sublogic is contained in the first sublogic sl_in :: Sublogic -> Sublogic -> Bool sl_in given new = sublogic_max given new == given in_x :: Sublogic -> a -> (a -> Sublogic) -> Bool in_x l x f = sl_in l (f x) in_basicSpec :: Sublogic -> BasicSpec -> Bool in_basicSpec l x = in_x l x sl_basicSpec in_sentence :: Sublogic -> Sentence -> Bool in_sentence l x = in_x l x sl_sentence in_symbItems :: Sublogic -> SymbItems -> Bool in_symbItems l x = in_x l x sl_symbItems in_symbMapItems :: Sublogic -> SymbMapItems -> Bool in_symbMapItems l x = in_x l x sl_symbMapItems in_env :: Sublogic -> Env -> Bool in_env l x = in_x l x sl_env in_morphism :: Sublogic -> Morphism -> Bool in_morphism l x = in_x l x sl_morphism in_symbol :: Sublogic -> Symbol -> Bool in_symbol l x = in_x l x sl_symbol
nevrenato/HetsAlloy
HasCASL/Sublogic.hs
gpl-2.0
26,070
0
35
6,614
7,927
4,082
3,845
589
16
module Test.App.Matrix (tests) where import Test.Tasty import Test.Tasty.HUnit import App.Matrix tests :: TestTree tests = testGroup "Matrix" [ matrixSizesTests , matrixValidTests , matrixIterateTests , matrixChangeTests ] matrixSizesTests = testGroup "matrixSizes" [ testCase "call a method over all element in array" $ matrixSizes [[1,2,3],[1,2,3]] @?= (2, 3) ] matrixValidTests = testGroup "matrixValid" [ testCase "valid coordinates" $ matrixValid [[1,2,3],[1,2,3]] (1, 2) @?= True , testCase "out of ranges" $ matrixValid [[1,2,3],[1,2,3]] (2, 2) @?= False ] matrixIterateTests = testGroup "matrixIterate" [ testCase "apply function on all matrix elements" $ matrixIterate [[1,2,3],[5,6,7]] (+1) @?= [[2,3,4],[6,7,8]] ] matrixChangeTests = testGroup "matrixChange" [ testCase "change elem in matrix" $ matrixChange [[1,2,3],[5,6,7]] (1,1) 8 @?= [[1,2,3],[5,8,7]] ]
triplepointfive/hapi
test/Test/App/Matrix.hs
gpl-2.0
955
0
11
197
386
230
156
24
1
module H99.Problem15 (repli) where repli :: [a] -> Int -> [a] repli xs n = concatMap (\x -> take n $ repeat x) xs
shimanekb/H-99SetTwo
problem15/src/H99/Problem15.hs
gpl-3.0
115
0
9
25
63
34
29
4
1
module Sound.Midi.Events where import Control.Monad.Free (liftF) import Data.ByteString (ByteString) import Sound.Midi.Internal.Encoding (ChunkM (..), Track, delay) import Sound.Midi.Internal.Encoding.Event (MetaChunk (..), VoiceChunk (..)) import Sound.Midi.Values -- modifiers rest :: Float -> Track -> Track rest = delay -- voice events noteOff :: Note -> Velocity -> Track noteOff note vel = liftF $ VoiceChunk 0 (NoteOff note vel) () noteOn :: Note -> Velocity -> Track noteOn note vel = liftF $ VoiceChunk 0 (NoteOn note vel) () afterTouch :: Note -> Pressure -> Track afterTouch note pres = liftF $ VoiceChunk 0 (AfterTouch note pres) () controller :: ControllerIdent -> ControllerValue -> Track controller ident value = liftF $ VoiceChunk 0 (ControlChange ident value) () patch :: Patch -> Track patch p = liftF $ VoiceChunk 0 (PatchChange p) () channelPressure :: Pressure -> Track channelPressure pres = liftF $ VoiceChunk 0 (ChannelPressure pres) () pitchWheel :: PitchWheel -> Track pitchWheel pitch = liftF $ VoiceChunk 0 (PitchWheelChange pitch) () -- meta events sequence :: Sequence -> Track sequence num = liftF $ MetaChunk 0 (SequenceNumber num) () text :: ByteString -> Track text str = liftF $ MetaChunk 0 (TextArbitrary str) () copyright :: ByteString -> Track copyright str = liftF $ MetaChunk 0 (TextCopyright str) () trackName :: ByteString -> Track trackName str = liftF $ MetaChunk 0 (TextTrackName str) () instrumentName :: ByteString -> Track instrumentName str = liftF $ MetaChunk 0 (TextInstruName str) () lyric :: ByteString -> Track lyric str = liftF $ MetaChunk 0 (TextLyric str) () marker :: ByteString -> Track marker str = liftF $ MetaChunk 0 (TextMarker str) () cuePoint :: ByteString -> Track cuePoint str = liftF $ MetaChunk 0 (TextCuePoint str) () tempo :: Tempo -> Track tempo t = liftF $ MetaChunk 0 (SetTempo t) () keySig :: KeyNote -> KeyChord -> Track keySig note chord = liftF $ MetaChunk 0 (SetKeySig $ keyOf note chord) ()
Jonplussed/midi-free
src/Sound/MIDI/Events.hs
gpl-3.0
1,994
0
9
341
757
395
362
42
1
module Text.Templar.Source ( navigate ) where import Text.Templar.Syntax import Text.Templar.Knightly navigate :: (Knight, Knight) -> Source -> Extract Knight navigate ctx (Source chain []) = navChain ctx chain navigate ctx (Source f args) = do f' <- call <$> navChain ctx f args' <- traverse (navChain ctx) args f' args' navChain :: (Knight, Knight) -> Chain -> Extract Knight navChain (root, _) (Rooted fields) = navFields root fields navChain (_, local) (Relative fields) = navFields local fields navChain _ (Immediate str) = Good . Knight $ str navFields :: Knight -> [Field] -> Extract Knight navFields knight [] = Good knight navFields knight (field:fields) = do next <- case field of NameField name -> knight `access` name CountField -> count knight navFields next fields
Zankoku-Okuno/templar
src/Text/Templar/Source.hs
gpl-3.0
828
0
11
173
323
164
159
21
2
{-# LANGUAGE OverloadedStrings, DeriveDataTypeable, ImplicitParams #-} import Types import UserInfo import Control.Exception (SomeException(..), Exception(..)) import Control.Exception.Lifted (handle) import Control.Monad.IO.Class (liftIO) import Data.Aeson (Value, encode, object, (.=), fromJSON, toJSON, Result(..)) import Data.Aeson.Parser (json) import Data.ByteString (ByteString) import Data.Conduit (ResourceT, ($$)) import Data.Conduit.Attoparsec (sinkParser) import qualified Data.Set as S import Data.Typeable import Network.HTTP.Types (status200, status400) import Network.Wai (Application, Response, requestBody, responseLBS) import Network.Wai.Handler.Warp (run) data JSONParseException = JSONParseException deriving (Show, Typeable) instance Exception JSONParseException main :: IO () main = run 8080 app app :: Application app req = handle invalidJson $ do value <- requestBody req $$ sinkParser json let val' = fromJSON value :: Result UserIn case val' of Error err -> do liftIO $ putStrLn $ "Error in parsing JSON: "++err invalidJson $ SomeException JSONParseException Success res -> do newValue <- liftIO $ modValue res return $ responseLBS status200 [("Content-Type", "application/json")] $ encode newValue invalidJson :: SomeException -> ResourceT IO Response invalidJson ex = return $ responseLBS status400 [("Content-Type", "application/json")] $ encode $ object [ ("message" .= show ex) ] -- Application-specific logic would go here. modValue :: UserIn -> IO User modValue input = let ?verbose = 0 in do putStrLn $ "Get user info for " ++ show input ui <- userInfo (userInName input) (userInToken input) print ui return $ case ui of Nothing -> User S.empty S.empty Just u -> u
gltronred/issue-recommendation-crawler
src/Service.hs
gpl-3.0
2,089
17
17
614
545
299
246
51
2
module Main where import qualified Server as S import qualified Client as C import System.Console.GetOpt import System.IO import System.Environment --import System --From the documentation on System.Console.GetOpt data Flag = ServerMode | ClientMode | Input String | Stdin | Host String deriving (Show,Eq) options :: [OptDescr Flag] options = [ Option ['s'] ["server"] (NoArg ServerMode) "Run in server mode" , Option ['c'] ["client"] (NoArg ClientMode) "Run in client mode" , Option ['i'] ["input"] (ReqArg Input "MESSAGE") "Explicit message to send" , Option ['n'] ["stdin"] (NoArg Stdin) "Transmit from standard in" , Option ['h'] ["host"] (ReqArg Host "HOSTNAME") "Host to contact" ] serverOpts :: [String] -> IO ([Flag], [String]) serverOpts argv = case getOpt Permute options argv of (o,n,[] ) -> return (o,n) (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options)) where header = "Usage Main [OPTION...]" ---- main :: IO () main = do args <- getArgs (opts,_) <- serverOpts args if elem ClientMode opts then clientmode opts else if elem ServerMode opts then S.main else error "You must use client mode or server mode." return () clientmode :: [Flag] -> IO () clientmode flags = do case pluckInput flags of Just (Input s) -> host s Just _ -> error "This is unreachable!" Nothing -> if elem Stdin flags then do sn <- hGetContents stdin host sn else error "Client requires a specified input type." where host msg = case pluckhost flags of Nothing -> error "You must supply a host address." Just (Host s) -> C.main s msg Just _ -> error "This should be unreachable...." pluckInput [] = Nothing pluckInput ((Input s):_) = Just $ Input s pluckInput (_:xs) = pluckInput xs pluckhost [] = Nothing pluckhost ((Host s):_) = Just $ Host s pluckhost (_:xs) = pluckhost xs
igraves/rabin-haskell
Main.hs
gpl-3.0
2,356
0
14
863
685
356
329
50
10
{-# LANGUAGE NamedFieldPuns #-} module System.Serverman.Actions.Manage (startService, stopService) where import System.Serverman.Types import System.Serverman.Utils import System.Serverman.Actions.Env import System.Serverman.Actions.Install import System.Serverman.Services import Control.Monad.State startService :: Service -> App () startService (Service { service }) = do (AppState { os }) <- get case os of Mac -> do liftIO $ putStrLn $ "Couldn't start " ++ service ++ " automatically. If you encounter any problems, make sure it is running." _ -> do executeRoot "systemctl" ["start", service] "" True execute "sleep" ["5s"] "" True return () stopService :: Service -> App () stopService (Service { service }) = do (AppState { os }) <- get case os of Mac -> do liftIO $ putStrLn $ "Couldn't stop " ++ service ++ " automatically." _ -> do executeRoot "systemctl" ["stop", service] "" True return ()
mdibaiee/serverman
src/System/Serverman/Actions/Start.hs
gpl-3.0
1,030
0
15
260
292
153
139
27
2
-- Module : Network.AWS.CodeDeploy -- 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. -- | Amazon CodeDeploy is a service that automates code deployments to Amazon EC2 -- instances. Amazon CodeDeploy makes it easier for you to rapidly release new -- features, helps you avoid downtime during deployment, and handles the -- complexity of updating your applications. You can use Amazon CodeDeploy to -- automate deployments, eliminating the need for error-prone manual operations, -- and the service scales with your infrastructure so you can easily deploy to -- one EC2 instance or thousands. module Network.AWS.CodeDeploy ( module Network.AWS.CodeDeploy.BatchGetApplications , module Network.AWS.CodeDeploy.BatchGetDeployments , module Network.AWS.CodeDeploy.CreateApplication , module Network.AWS.CodeDeploy.CreateDeployment , module Network.AWS.CodeDeploy.CreateDeploymentConfig , module Network.AWS.CodeDeploy.CreateDeploymentGroup , module Network.AWS.CodeDeploy.DeleteApplication , module Network.AWS.CodeDeploy.DeleteDeploymentConfig , module Network.AWS.CodeDeploy.DeleteDeploymentGroup , module Network.AWS.CodeDeploy.GetApplication , module Network.AWS.CodeDeploy.GetApplicationRevision , module Network.AWS.CodeDeploy.GetDeployment , module Network.AWS.CodeDeploy.GetDeploymentConfig , module Network.AWS.CodeDeploy.GetDeploymentGroup , module Network.AWS.CodeDeploy.GetDeploymentInstance , module Network.AWS.CodeDeploy.ListApplicationRevisions , module Network.AWS.CodeDeploy.ListApplications , module Network.AWS.CodeDeploy.ListDeploymentConfigs , module Network.AWS.CodeDeploy.ListDeploymentGroups , module Network.AWS.CodeDeploy.ListDeploymentInstances , module Network.AWS.CodeDeploy.ListDeployments , module Network.AWS.CodeDeploy.RegisterApplicationRevision , module Network.AWS.CodeDeploy.StopDeployment , module Network.AWS.CodeDeploy.Types , module Network.AWS.CodeDeploy.UpdateApplication , module Network.AWS.CodeDeploy.UpdateDeploymentGroup ) where import Network.AWS.CodeDeploy.BatchGetApplications import Network.AWS.CodeDeploy.BatchGetDeployments import Network.AWS.CodeDeploy.CreateApplication import Network.AWS.CodeDeploy.CreateDeployment import Network.AWS.CodeDeploy.CreateDeploymentConfig import Network.AWS.CodeDeploy.CreateDeploymentGroup import Network.AWS.CodeDeploy.DeleteApplication import Network.AWS.CodeDeploy.DeleteDeploymentConfig import Network.AWS.CodeDeploy.DeleteDeploymentGroup import Network.AWS.CodeDeploy.GetApplication import Network.AWS.CodeDeploy.GetApplicationRevision import Network.AWS.CodeDeploy.GetDeployment import Network.AWS.CodeDeploy.GetDeploymentConfig import Network.AWS.CodeDeploy.GetDeploymentGroup import Network.AWS.CodeDeploy.GetDeploymentInstance import Network.AWS.CodeDeploy.ListApplicationRevisions import Network.AWS.CodeDeploy.ListApplications import Network.AWS.CodeDeploy.ListDeploymentConfigs import Network.AWS.CodeDeploy.ListDeploymentGroups import Network.AWS.CodeDeploy.ListDeploymentInstances import Network.AWS.CodeDeploy.ListDeployments import Network.AWS.CodeDeploy.RegisterApplicationRevision import Network.AWS.CodeDeploy.StopDeployment import Network.AWS.CodeDeploy.Types import Network.AWS.CodeDeploy.UpdateApplication import Network.AWS.CodeDeploy.UpdateDeploymentGroup
dysinger/amazonka
amazonka-codedeploy/gen/Network/AWS/CodeDeploy.hs
mpl-2.0
3,858
0
5
460
417
310
107
53
0
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE ConstraintKinds #-} module Control.Monad.Data.Types ( BiCons(..), MList(..), MTree(..), bc, ) where import Control.Monad.Data.Class import Control.Monad.Data.Foldable import Data.Tree -- |A type that's either Nil or a pair of elements. data BiCons a b = Nil | a :# b -- |Case distinction for 'BiCons'. bc :: c -> (a -> b -> c) -> BiCons a b -> c {-# INLINE bc #-} bc nil cons c = case c of Nil -> nil (h :# t) -> cons h t -- |Monadic list that can be evaluated incrementally. newtype MList m a = ML{runML :: m (BiCons a (MList m a))} -- |Monadic tree that can be evaluated incrementally. newtype MTree m a = MT{runMT :: m (a,[MTree m a])} conc :: Monad m => MList m (MList m a) -> MList m a conc (ML xs) = ML $ do xs >>= \case {Nil -> return Nil; (h :# t) -> runML $ h `mappend` conc t} concMap :: Monad m => (a -> MList m b) -> MList m a -> MList m b concMap f = conc . fmap f instance MonadicStructure MList where type Target MList = [] toMonadic [] = ML (pure Nil) toMonadic (x:xs) = ML (pure (x :# toMonadic xs)) fromMonadic (ML xs) = xs >>= \case{Nil -> return []; (h :# t) -> (h:) <$> fromMonadic t} instance Functor m => Functor (MList m) where fmap f (ML list) = ML (fmap go list) where go Nil = Nil go (x :# xs) = f x :# fmap f xs instance Monad m => Monoid (MList m a) where mempty = ML (pure Nil) mappend (ML xs) (ML ys) = ML $ xs >>= \case {Nil -> ys; (h :# t) -> return $ h :# mappend t (ML ys)} instance Monad m => Applicative (MList m) where pure x = ML $ pure $ x :# ML (pure Nil) fs <*> xs = concMap (<$> xs) fs instance Monad m => Monad (MList m) where x >>= f = conc (fmap f x) instance FoldableM MList where type Con MList r = Monad r foldrM f acc (ML xs) = xs >>= \case{Nil -> return acc; (h :# t) -> foldrM f acc t >>= f h} instance MonadicStructure MTree where type Target MTree = Tree toMonadic (Node n []) = MT $ pure $ (n, []) toMonadic (Node n ns) = MT $ pure $ (n, map toMonadic ns) fromMonadic (MT xs) = xs >>= \case (n,[]) -> return (Node n []) (n,ns) -> Node n <$> mapM fromMonadic ns instance Functor m => Functor (MTree m) where fmap f (MT ns) = MT (fmap go ns) where go (n,[]) = (f n, []) go (n,ns) = (f n, fmap (fmap f) ns) {- instance Monad m => Applicative (MTree m) where pure x = MT $ pure $ (x,[]) fs <*> Node f tfs <*> tx@(Node x txs) = Node (f x) (map (f <$>) txs ++ map (<*> tx) tfs) Node f [] <*> tx@(Node x txs) = Node (f x) $ map (fmap f) txs ++ map (<*> tx) tfs Node (+10) [] <*> Node 2 [Node 1 [], Node 3] Node 12 $ [fmap (+10) 1, fmap (+10) 3] -} --instance FoldableM MTree where -- type Con MTree r = Monad r -- foldrM f acc (MT xs) =
ombocomp/MList
Control/Monad/Data/Types.hs
apache-2.0
2,922
0
13
839
1,168
613
555
54
2
ans' [a,b,c,d] = sum $ map (\b' -> (b'*a*2 + b'*(c - a) ) * (c - a + 1) `div` 2 ) [b..d] ans ([0]:_) = [] ans (_:c:r) = let a = ans' c a'= a `mod` (1000000007) in a':(ans r) main = do c <- getContents let i = map (map read) $ map words $ lines c :: [[Integer]] o = ans i mapM_ print o
a143753/AOJ
3209.hs
apache-2.0
357
5
14
142
245
124
121
12
1
-- | -- Task worker -- Connects PULL socket to tcp://localhost:5557 -- Collects workloads from ventilator via that socket -- Connects PUSH socket to tcp://localhost:5558 -- Sends results to sink via that socket -- -- Translated to Haskell by ERDI Gergo http://gergo.erdi.hu/ module Main where import System.ZMQ import Control.Monad (forever) import Data.ByteString.Char8 (unpack, empty) import System.Random (randomRIO) import Control.Applicative ((<$>)) import System.IO (hSetBuffering, stdout, BufferMode(..)) import Control.Concurrent (threadDelay) main :: IO () main = withContext 1 $ \context -> do withSocket context Pull $ \receiver -> do connect receiver "tcp://localhost:5557" withSocket context Push $ \sender -> do connect sender "tcp://localhost:5558" hSetBuffering stdout NoBuffering forever $ do message <- unpack <$> receive receiver [] -- Simple progress indicator for the viewer putStr $ message ++ "." -- Do the "work" threadDelay (read message * 1000)         -- Send results to sink send sender empty []
krattai/noo-ebs
docs/zeroMQ-guide2/examples/Haskell/taskwork.hs
bsd-2-clause
1,203
0
23
254
245
132
113
20
1
module Main where import Control.Monad.Reader import Control.Monad (when) import Data.Configurator import Data.Traversable (traverse) import Data.Either import qualified Data.Foldable as DF import Data.Maybe import qualified Data.Map as M import qualified Data.Aeson as A import Options.Applicative import Safe (headMay) import Text.Printf (printf) -- Local modules import Checksum import Dicom import Mytardis import MytardisRest import RestTypes import Types data Command = CmdUploadAll UploadAllOptions | CmdUploadOne UploadOneOptions | CmdShowExperiments ShowExperimentsOptions deriving (Eq, Show) data UploadAllOptions = UploadAllOptions { uploadAllDryRun :: Bool } deriving (Eq, Show) data UploadOneOptions = UploadOneOptions { uploadOneHash :: String } deriving (Eq, Show) data ShowExperimentsOptions = ShowExperimentsOptions { showFileSets :: Bool } deriving (Eq, Show) data UploaderOptions = UploaderOptions { optDirectory :: Maybe FilePath , optHost :: Maybe String , optUser :: Maybe String , optProcessedDir :: FilePath , optCommand :: Command } deriving (Eq, Show) pUploadAllOptions :: Parser Command pUploadAllOptions = CmdUploadAll <$> UploadAllOptions <$> switch (long "dry-run" <> help "Dry run.") pUploadOneOptions :: Parser Command pUploadOneOptions = CmdUploadOne <$> UploadOneOptions <$> strOption (long "hash" <> help "Hash of experiment to upload.") pShowExprOptions :: Parser Command pShowExprOptions = CmdShowExperiments <$> ShowExperimentsOptions <$> switch (long "show-file-sets" <> help "Show experiments.") pUploaderOptions :: Parser UploaderOptions pUploaderOptions = UploaderOptions <$> optional (strOption (long "input-dir" <> metavar "DIRECTORY" <> help "Directory with DICOM files.")) <*> optional (strOption (long "host" <> metavar "HOST" <> help "MyTARDIS host URL, e.g. http://localhost:8000")) <*> optional (strOption (long "user" <> metavar "USERNAME" <> help "MyTARDIS username.")) <*> (strOption (long "processed-dir" <> metavar "DIRECTORY" <> help "Directory for processed DICOM files.")) <*> subparser x where x = cmd1 <> cmd2 <> cmd3 cmd1 = command "upload-all" (info (helper <*> pUploadAllOptions) (progDesc "Upload all experiments.")) cmd2 = command "upload-one" (info (helper <*> pUploadOneOptions) (progDesc "Upload a single experiment.")) cmd3 = command "show-experiments" (info (helper <*> pShowExprOptions) (progDesc "Show local experiments.")) getDicomDir :: UploaderOptions -> FilePath getDicomDir opts = fromMaybe "." (optDirectory opts) hashFiles :: [FilePath] -> String hashFiles = sha256 . unwords dostuff :: UploaderOptions -> ReaderT MyTardisConfig IO () dostuff opts@(UploaderOptions _ _ _ _ (CmdShowExperiments cmdShow)) = do let dir = getDicomDir opts _files <- liftIO $ rights <$> (getDicomFilesInDirectory ".dcm" dir >>= mapM readDicomMetadata) let groups = groupDicomFiles _files liftIO $ print groups forM_ groups $ \files -> do let IdentifiedExperiment desc institution title metadata = identifyExperiment files hash = (sha256 . unwords) (map dicomFilePath files) liftIO $ if showFileSets cmdShow then printf "%s [%s] [%s] [%s] [%s]\n" hash institution desc title (unwords $ map dicomFilePath files) else printf "%s [%s] [%s] [%s]\n" hash institution desc title dostuff opts@(UploaderOptions _ _ _ _ (CmdUploadAll allOpts)) = uploadDicomAsMinc identifyExperiment identifyDataset identifyDatasetFile (getDicomDir opts) (optProcessedDir opts) (schemaExperiment, schemaDataset, schemaDicomFile) dostuff opts@(UploaderOptions _ _ _ _ (CmdUploadOne oneOpts)) = do let hash = uploadOneHash oneOpts let dir = getDicomDir opts _files <- liftIO $ rights <$> (getDicomFilesInDirectory ".dcm" dir >>= mapM readDicomMetadata) let groups = groupDicomFiles _files let hashes = map (hashFiles . fmap dicomFilePath) groups :: [String] matches = filter ((==) hash . snd) (zip groups hashes) :: [([DicomFile], String)] case matches of [match] -> liftIO $ print match [] -> liftIO $ putStrLn "Hash does not match any identified experiment." _ -> error "Multiple experiments with the same hash. Oh noes!" {- main = do config <- load [Required "sample.conf"] display config -} main :: IO () main = do opts' <- execParser opts let host = fromMaybe "http://localhost:8000" $ optUser opts' user = fromMaybe "admin" $ optHost opts' pass = "admin" -- FIXME Fail on no password mytardisOpts = (defaultMyTardisOptions host user pass) runReaderT (dostuff opts') mytardisOpts where opts = info (helper <*> pUploaderOptions ) (fullDesc <> header "mytardis-dicom - upload DICOM files to a MyTARDIS server" ) testtmp = flip runReaderT (defaultMyTardisOptions "http://localhost:8000" "admin" "admin") blah where blah :: ReaderT MyTardisConfig IO () blah = do {- let dir = "/tmp/dicomdump" _files <- liftIO $ rights <$> (getDicomFilesInDirectory ".dcm" dir >>= mapM readDicomMetadata) let files = head $ groupDicomFiles _files x <- getExperimentWithMetadata (identifyExperiment files) liftIO $ print x -} {- forM_ [1..50] $ \i -> do e <- createExperiment $ IdentifiedExperiment (show i) "UQ" (show i) [] liftIO $ print e -} A.Success users <- getUsers let admin = head $ filter (\x -> ruserUsername x == "admin") users A.Success cai12345 <- getOrCreateGroup "CAI 12345" liftIO $ print admin liftIO $ print cai12345 A.Success experiment <- getExperiment "/api/v1/experiment/3/" liftIO $ print experiment -- addGroupReadOnlyAccess experiment cai12345 -- liftIO $ print "Up to here..." -- newacl <- createExperimentObjectACL cai12345 experiment False True False -- liftIO $ print newacl eacl <- getOrCreateExperimentACL experiment cai12345 liftIO $ print ("eacl", eacl) -- experiment' <- addGroupReadOnlyAccess experiment cai12345 -- liftIO $ print ("experiment'", experiment') -- user' <- addGroupToUser admin cai12345 -- liftIO $ print user' liftIO $ print "done" newtype PS = PS (String, M.Map String String) deriving (Eq, Show) data Flabert = Flabert { idExperiment :: [DicomFile] -> IdentifiedExperiment -- ^ Identify an experiment. , idDataset :: RestExperiment -> [DicomFile] -> IdentifiedDataset -- ^ Given a particular experiment on MyTARDIS, identify the local dataset. -- ^ Given a particular dataset in MyTARDIS, identify , , idDatasetFile :: RestDataset -- ^ Dataset on MyTARDIS. -> FilePath -- ^ Full path to file. -> String -- ^ Md5sum. -> Integer -- ^ File size. -> [(String, M.Map String String)] -- ^ Metadata map. -> IdentifiedFile } -- [ [DicomFile] -> A.Result [PS] ] -- noFlaberts = Flabert [] mkCaiExperimentPS :: String -> PS mkCaiExperimentPS pid = PS ("http://cai.uq.edu.au/schema/1", undefined) -- FIXME hardcoded caiProjectID :: [DicomFile] -> A.Result [PS] caiProjectID files = let oneFile = headMay files in case oneFile of Nothing -> A.Error "No DICOM files; can't determine CAI Project ID." Just file -> case dicomReferringPhysicianName file of Nothing -> A.Error "Referring Physician Name field is empty; can't determine CAI Project ID." Just rphys -> if is5digits rphys then A.Success [mkCaiExperimentPS rphys] else A.Error $ "Referring Physician Name is not a 5 digit number: " ++ rphys where is5digits :: String -> Bool is5digits s = (length s == 5) && (isJust $ (readMaybe s :: Maybe Integer)) readMaybe :: (Read a) => String -> Maybe a readMaybe s = case reads s of [(a, "")] -> Just a _ -> Nothing runThingos :: [Flabert] -> [DicomFile] -> A.Result [PS] runThingos flab files = undefined where stuff = undefined -- flab <*> files -- FIXME Testing, need to work out what these will be later. experimentTitlePrefix = "CAI Test Experiment " experimentDescriptionPrefix = "CAI Test Experiment Description" datasetDescription = "CAI Dataset Description" -- FIXME These should be in a reader or something. schemaExperiment = "http://cai.uq.edu.au/schema/metadata/1" schemaDataset = "http://cai.uq.edu.au/schema/metadata/2" schemaDicomFile = "http://cai.uq.edu.au/schema/metadata/3" schemaCaiProject = "http://cai.uq.edu.au/schema/metadata/4" defaultInstitutionName = "DEFAULT INSTITUTION" identifyExperiment :: [DicomFile] -> IdentifiedExperiment identifyExperiment files = IdentifiedExperiment description institution title [(schema, m)] where oneFile = headMay files patientName = join $ dicomPatientName <$> oneFile studyDescription = join $ dicomStudyDescription <$> oneFile seriesDescription = join $ dicomSeriesDescription <$> oneFile -- Experiment title = fromMaybe "DUD TITLE FIXME" $ (experimentTitlePrefix ++) <$> patientName description = experimentDescriptionPrefix institution = fromMaybe "DEFAULT INSTITUTION FIXME" $ join $ dicomInstitutionName <$> oneFile institutionalDepartmentName = fromMaybe "DEFAULT INSTITUTION DEPT NAME FIXME" $ join $ dicomInstitutionName <$> oneFile institutionAddress = fromMaybe "DEFAULT INSTITUTION ADDRESS FIXME" $ join $ dicomInstitutionAddress <$> oneFile patientID = fromMaybe "FIXME DUD PATIENT ID" $ join $ dicomPatientID <$> oneFile -- FIXME dangerous? Always get a patient id? -- FIXME deal with multiple schemas. schema = "http://cai.uq.edu.au/schema/metadata/1" -- "DICOM Experiment Metadata" m = M.fromList [ ("InstitutionName", institution) , ("InstitutionalDepartmentName", institutionalDepartmentName) , ("InstitutionAddress", institutionAddress) , ("PatientID", patientID) ] identifyDataset :: RestExperiment -> [DicomFile] -> IdentifiedDataset identifyDataset re files = IdentifiedDataset description experiments m where oneFile = head files -- FIXME this will explode, use headMay instead description = (fromMaybe "FIXME STUDY DESCRIPTION" $ dicomStudyDescription oneFile) ++ "/" ++ (fromMaybe "FIXME SERIES DESCRIPTION" $ dicomSeriesDescription oneFile) experiments = [eiResourceURI re] schema = schemaDataset m = [] -- FIXME we should do some metadata for datasets! [(schema, m)] identifyDatasetFile :: RestDataset -> String -> String -> Integer -> [(String, M.Map String String)] -> IdentifiedFile identifyDatasetFile rds filepath md5sum size metadata = IdentifiedFile (dsiResourceURI rds) filepath md5sum size metadata grabMetadata :: DicomFile -> [(String, String)] grabMetadata file = map oops $ concatMap f metadata where oops (x, y) = (y, x) f :: (Maybe t, t) -> [(t, t)] f (Just x, desc) = [(x, desc)] f (Nothing, _) = [] metadata = [ (dicomPatientName file, "Patient Name") , (dicomPatientID file, "Patient ID") , (dicomPatientBirthDate file, "Patient Birth Date") , (dicomPatientSex file, "Patient Sex") , (dicomPatientAge file, "Patient Age") , (dicomPatientWeight file, "Patient Weight") , (dicomPatientPosition file, "Patient Position") , (dicomStudyDate file, "Study Date") , (dicomStudyTime file, "Study Time") , (dicomStudyDescription file, "Study Description") -- , (dicomStudyInstanceID file, "Study Instance ID") , (dicomStudyID file, "Study ID") , (dicomSeriesDate file, "Series Date") , (dicomSeriesTime file, "Series Time") , (dicomSeriesDescription file, "Series Description") -- , (dicomSeriesInstanceUID file, "Series Instance UID") -- , (dicomSeriesNumber file, "Series Number") -- , (dicomCSASeriesHeaderType file, "CSA Series Header Type") -- , (dicomCSASeriesHeaderVersion file, "CSA Series Header Version") -- , (dicomCSASeriesHeaderInfo file, "CSA Series Header Info") -- , (dicomSeriesWorkflowStatus file, "Series Workflow Status") -- , (dicomMediaStorageSOPInstanceUID file, "Media Storage SOP Instance UID") -- , (dicomInstanceCreationDate file, "Instance Creation Date") -- , (dicomInstanceCreationTime file, "Instance Creation Time") -- , (dicomSOPInstanceUID file, "SOP Instance UID") -- , (dicomStudyInstanceUID file, "Study Instance UID") -- , (dicomInstanceNumber file, "Instance Number") , (dicomInstitutionName file, "Institution Name") , (dicomInstitutionAddress file, "Institution Address") , (dicomInstitutionalDepartmentName file, "Institutional Department Name") , (dicomReferringPhysicianName file, "Referring Physician Name") ]
andrewjanke/mytardis-dicom
src/Main.hs
bsd-2-clause
14,266
0
17
4,046
2,791
1,482
1,309
207
5
-- 40886 import Data.List(genericLength) import Math.NumberTheory.Powers.Squares(isSquare) nn = 100 dd = 100 -- https://en.wikipedia.org/wiki/Methods_of_computing_square_roots -- #Decimal_.28base_10.29 sqrtDigit (_,(p,c)) = (x,(p2,c2)) where y = x*(20*p+x) x = genericLength $ takeWhile validX [1..9] validX i = i*(20*p+i) <= c p2 = 10*p+x c2 = 100*(c-y) sumAllSqrts d n = sum $ concatMap genDigits $ filter (not.isSquare) [1..n] where genDigits x = take d $ map fst $ drop 1 $ iterate sqrtDigit (0,(0,x)) main = putStrLn $ show $ sumAllSqrts dd nn
higgsd/euler
hs/80.hs
bsd-2-clause
601
0
11
132
267
146
121
13
1
{-# LANGUAGE OverloadedStrings #-} module ShopData.VariantOption where import qualified Snap.Snaplet.PostgresqlSimple as PS import Database.PostgreSQL.Simple import Data.Text data VariantOption = VariantOption { variantOptionId :: Int, variantId :: Int, option :: Text, productsUsing :: Int } deriving (Show) instance FromRow VariantOption where fromRow = VariantOption <$> PS.field <*> PS.field <*> PS.field <*> PS.field variantOptions :: PS.HasPostgres m => [Int] -> m [VariantOption] variantOptions voIds = do results <- PS.query "SELECT\ \ variant_option_id,\ \ variant_id,\ \ option,\ \ (SELECT COUNT(*) FROM product_variant_options pvo WHERE pvo.variant_option_id = vo.variant_option_id)\ \ FROM\ \ variant_options vo\ \ WHERE\ \ variant_option_id IN ?" (Only $ In voIds) :: PS.HasPostgres m => m [VariantOption] return (results :: [VariantOption]) addVariantOption :: PS.HasPostgres s3 => Int -> Text -> s3 Int addVariantOption parentId opt = do r <- PS.returning "INSERT INTO variant_options (variant_id, option) VALUES (?, ?) RETURNING variant_option_id" [(parentId, opt)] :: PS.HasPostgres s => s [Only Int] let x = case r of (f:_) -> f [] -> Only 0 let (Only i) = x return i delVariantOption :: PS.HasPostgres m => Int -> m () delVariantOption i = do PS.execute "DELETE FROM variant_options WHERE variant_option_id = ?" (Only i) return ()
rjohnsondev/haskellshop
src/ShopData/VariantOption.hs
bsd-2-clause
1,695
0
14
537
389
200
189
33
2
{-# LANGUAGE RecordWildCards #-} -- | Internal representation of dynamic automata nodes. module Data.DAWG.Dynamic.Node ( Node(..) , onSym , edges , children , insert ) where import Control.Applicative ((<$>), (<*>)) import Data.Binary (Binary, Get, put, get) import Data.DAWG.Types import Data.DAWG.Util (combine) import Data.DAWG.HashMap (Hash, hash) import Data.DAWG.Trans.Map (Trans) import qualified Data.DAWG.Trans as T import qualified Data.DAWG.Trans.Hashed as H -- | Two nodes (states) belong to the same equivalence class (and, -- consequently, they must be represented as one node in the graph) -- iff they are equal with respect to their values and outgoing -- edges. -- -- Since 'Leaf' nodes are distinguished from 'Branch' nodes, two values -- equal with respect to '==' function are always kept in one 'Leaf' -- node in the graph. It doesn't change the fact that to all 'Branch' -- nodes one value is assigned through the epsilon transition. -- -- Invariant: the 'eps' identifier always points to the 'Leaf' node. -- Edges in the 'edgeMap', on the other hand, point to 'Branch' nodes. data Node a = Branch { -- | Epsilon transition. eps :: {-# UNPACK #-} !ID -- | Transition map (outgoing edges). , transMap :: !(H.Hashed Trans) } | Leaf { value :: !(Maybe a) } deriving (Show, Eq, Ord) instance Ord a => Hash (Node a) where hash Branch{..} = combine eps (H.hash transMap) hash Leaf{..} = case value of Just _ -> (-1) Nothing -> (-2) instance Binary a => Binary (Node a) where put Branch{..} = put (1 :: Int) >> put eps >> put transMap put Leaf{..} = put (2 :: Int) >> put value get = do x <- get :: Get Int case x of 1 -> Branch <$> get <*> get _ -> Leaf <$> get -- | Transition function. onSym :: Sym -> Node a -> Maybe ID onSym x (Branch _ t) = T.lookup x t onSym _ (Leaf _) = Nothing {-# INLINE onSym #-} -- | List of symbol/edge pairs outgoing from the node. edges :: Node a -> [(Sym, ID)] edges (Branch _ t) = T.toList t edges (Leaf _) = [] {-# INLINE edges #-} -- | List of children identifiers. children :: Node a -> [ID] children = map snd . edges {-# INLINE children #-} -- | Substitue edge determined by a given symbol. insert :: Sym -> ID -> Node a -> Node a insert x i (Branch w t) = Branch w (T.insert x i t) insert _ _ l = l {-# INLINE insert #-}
kawu/dawg
src/Data/DAWG/Dynamic/Node.hs
bsd-2-clause
2,439
4
13
586
664
369
295
53
1
{-# LANGUAGE OverloadedStrings #-} import Test.QuickCheck import Test.Hspec import Data.Monoid ((<>)) import qualified Data.Text.Lazy as LT import qualified Data.Text.Lazy.Encoding as LTE import Web.Scotty.SignedCookies.SignedCookiesInternal stbs = LTE.encodeUtf8 . LT.fromStrict secret = stbs "secret" cookieId = stbs "id" cookieValue = stbs "valuehere" main :: IO () main = hspec $ do describe "Hash validation" $ do it "generates a hash from a bytestring" $ do length (generateHash cookieId cookieValue) `shouldBe` 64 generateHash secret (cookieId <> cookieValue) `shouldBe` "895673090f6d4d7ae837bee687e23205f6c267a4de4e87df2bcc9415f02771cc"
kgwinnup/signed-cookies
test/Spec.hs
bsd-2-clause
669
0
17
100
167
93
74
17
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Main where import ClassyPrelude import Criterion.Main import Help.Logging.Parse import Data.Attoparsec.Text import Database.MongoDB.Internal.Protocol import Database.MongoDB import System.IO main :: IO () main = do -- For me, dd if=/dev/zero of=/dev/null runs at about 1.3GB/s, so /dev/null should be fast enough. devnull <- openFile "/dev/null" ReadWriteMode pipe <- newPipe devnull defaultMain [ bench_takeChars , bench_goTill , bench_realParsers , bench_mongoSerialize pipe ] close pipe -- Experiment design: -- My parsers -- * takeChars -- ** Long string, short string -- Should be linear relationship bench_takeChars :: Benchmark bench_takeChars = bgroup "takeChars" [ bench_takeCharsShortString, bench_takeCharsLongString, bench_takeCharsVeryLongString ] bench_takeCharsShortString :: Benchmark bench_takeCharsShortString = let parser = takeChars "fakeLabel" 1 "" text = pack $ replicate 1000 'a' in bench "1 character" $ whnf (parse parser) text bench_takeCharsLongString :: Benchmark bench_takeCharsLongString = let parser = takeChars "fakeLabel" 1000 "" text = pack $ replicate 1000 'a' in bench "1000 characters" $ whnf (parse parser) text bench_takeCharsVeryLongString :: Benchmark bench_takeCharsVeryLongString = let parser = takeChars "fakeLabel" 10000 "" text = pack $ replicate 10000 'a' in bench "10000 characters" $ whnf (parse parser) text -- * goTill -- ** Long string, short string -- Should be linear relationship with length bench_goTill :: Benchmark bench_goTill = bgroup "goTill" [ bench_goTillShortString, bench_goTillLongString, bench_goTillVeryLongString ] bench_goTillShortString :: Benchmark bench_goTillShortString =let parser = goTill "fakeLabel" '_' "" text = pack $ "a_" in bench "1 character" $ whnf (parse parser) text bench_goTillLongString :: Benchmark bench_goTillLongString = let parser = goTill "fakeLabel" '_' "" text = pack $ replicate 1000 'a' ++ "_" in bench "1000 characters" $ whnf (parse parser) text bench_goTillVeryLongString :: Benchmark bench_goTillVeryLongString = let parser = goTill "fakeLabel" '_' "" text = pack $ replicate 10000 'a' ++ "_" in bench "10000 characters" $ whnf (parse parser) text -- * Real parsers (combination) -- ** Multi-record, single record with same string length singleLog :: Text singleLog = "00:00:01, 01/Jan/1970 - Error - xbmspts owtt cube zndm iegwlqq nnlqdr oqnn qurq bpypdx\n" bench_realParsers :: Benchmark bench_realParsers = bgroup "Log parsing" [ bench_singleRecord, bench_multiRecord ] bench_singleRecord :: Benchmark bench_singleRecord = let parser = makeRecordParser $ "%s_`message`" in bench "Single-record" $ whnf (parse parser) singleLog bench_multiRecord :: Benchmark bench_multiRecord = let parser = makeRecordParser $ "%s8`time`, %s11`date` - %s' '`status` - %s_`message`" in bench "Multi-record" $ whnf (parse parser) singleLog -- Insertion process -- * Single document bench_mongoSerialize :: Pipe -> Benchmark bench_mongoSerialize pipe = bgroup "MongoDB Serialization" [ bench_singleDocument pipe, bench_multiDocument pipe ] bench_singleDocument :: Pipe -> Benchmark bench_singleDocument pipe = bgroup "1 record" [ bench_mongoSingleShort pipe, bench_mongoSingleLong pipe, bench_mongoSingleVeryLong pipe, bench_mongoSingleOneDocument pipe ] bench_mongoSingleShort :: Pipe -> Benchmark bench_mongoSingleShort pipe = do let record = ["cats" := String "a" ]:[] db = "help" col = "benchmark" bench "1 character" $ whnfIO $ (access pipe UnconfirmedWrites db $ insertMany_ col record) >>= (\(Right _) -> return ()) bench_mongoSingleLong :: Pipe -> Benchmark bench_mongoSingleLong pipe = do let record = ["cats" := String (pack $ replicate 1000 'a') ]:[] db = "help" col = "benchmark" bench "1000 characters" $ whnfIO $ (access pipe UnconfirmedWrites db $ insertMany_ col record) >>= (\(Right _) -> return ()) bench_mongoSingleVeryLong :: Pipe -> Benchmark bench_mongoSingleVeryLong pipe = do let record = ["cats" := String (pack $ replicate 10000 'a') ]:[] db = "help" col = "benchmark" bench "10000 character" $ whnfIO $ (access pipe UnconfirmedWrites db $ insertMany_ col record) >>= (\(Right _) -> return ()) bench_mongoSingleOneDocument :: Pipe -> Benchmark bench_mongoSingleOneDocument pipe = do let db = "help" col = "benchmark" parser = makeRecordParser $ "%s_`message`" (Right doc) = parseOnly parser singleLog insertable = doc:[] bench "1 document" $ whnfIO $ (access pipe UnconfirmedWrites db $ insertMany_ col insertable) >>= (\(Right _) -> return ()) -- * Multi-record bench_multiDocument :: Pipe -> Benchmark bench_multiDocument pipe = bgroup "4 record" [ bench_mongoMultiOneDocument pipe ] -- , bench_mongoMulti50Document pipe, bench_mongoMulti100Document pipe ] bench_mongoMultiOneDocument :: Pipe -> Benchmark bench_mongoMultiOneDocument pipe = do let db = "help" col = "benchmark" parser = makeRecordParser $ "%s8`time`, %s11`date` - %s' '`status` - %s_`message`" (Right doc) = parseOnly parser singleLog insertable = doc:[] bench "1 document" $ whnfIO $ (access pipe UnconfirmedWrites db $ insertMany_ col insertable) >>= (\(Right _) -> return ()) bench_mongoMulti50Document :: Pipe -> Benchmark bench_mongoMulti50Document pipe = do let db = "help" col = "benchmark" parser = makeRecordParser $ "%s8`time`, %s11`date` - %s' '`status` - %s_`message`" (Right doc) = parseOnly parser singleLog insertable = replicate 50 doc bench "50 document" $ whnfIO $ (access pipe UnconfirmedWrites db $ insertMany_ col insertable) >>= (\(Right _) -> return ()) bench_mongoMulti100Document :: Pipe -> Benchmark bench_mongoMulti100Document pipe = do let db = "help" col = "benchmark" parser = makeRecordParser $ "%s8`time`, %s11`date` - %s' '`status` - %s_`message`" (Right doc) = parseOnly parser singleLog insertable = replicate 100 doc bench "500 document" $ whnfIO $ (access pipe UnconfirmedWrites db $ insertMany_ col insertable) >>= (\(Right _) -> return ())
argiopetech/help
bench/bench-main.hs
bsd-3-clause
6,706
0
16
1,585
1,600
812
788
113
1
{-# LANGUAGE CPP #-} module Main where import Test.Tasty (defaultMain, testGroup) import Test.Tasty.QuickCheck import Test.QuickCheck.Monadic (monadicIO, run) import System.Posix.IO import System.Posix.Memory import Control.Monad import Control.Exception (bracket) import Foreign.C.Types import Foreign.Storable import Data.Word psz :: CSize psz = fromIntegral sysconfPageSize -- create an anonymous private mapping of page-size size. withDummyMapping f = do bracket (memoryMap Nothing psz [MemoryProtectionRead,MemoryProtectionWrite] MemoryMapPrivate Nothing 0) (\mem -> memoryUnmap mem psz) f withDevZeroMapping f = withOpenFd "/dev/zero" $ \fd -> bracket (memoryMap Nothing psz [MemoryProtectionRead,MemoryProtectionWrite] MemoryMapPrivate (Just fd) 0) (\mem -> memoryUnmap mem psz) f where withOpenFd filename g = do bracket (openFd filename ReadWrite Nothing defaultFileFlags) closeFd g tests = testGroup "unix-memory" [ testProperty "page-size" $ sysconfPageSize > 0 && sysconfPageSize < (2^(20::Int)) , testGroup "anonymous" $ runTestWithMapping withDummyMapping #ifdef __APPLE__ , testGroup "fd" $ runTestWithMapping withDevZeroMapping #endif ] where runTestWithMapping mapF = [ testProperty "mmap-munmap" $ monadicIO $ run $ mapF $ \_ -> return True , testProperty "madvise" $ monadicIO $ run $ mapF $ \ptr -> memoryAdvise ptr psz MemoryAdviceRandom >> return True , testProperty "msync" $ monadicIO $ run $ mapF $ \ptr -> memorySync ptr psz [MemorySyncAsync] >> return True , testProperty "mlock-munlock" $ monadicIO $ run $ mapF $ \ptr -> do memoryLock ptr psz memoryUnlock ptr psz return True , testProperty "read" $ monadicIO $ run $ mapF $ \ptr -> do res <- forM [0..(sysconfPageSize-1)] $ \off -> do b <- peekElemOff ptr off :: IO Word8 return (b == 0) return $ and res ] main :: IO () main = defaultMain tests
vincenthz/hs-unix-memory
tests/Tests.hs
bsd-3-clause
2,257
0
19
688
614
317
297
46
1
module GHC.RTS.Events.Analyze.Reports.Timed ( Report , ReportFragment(..) , ReportLine(..) , createReport , writeReport ) where import Data.Function (on) import Data.List (sortBy, intercalate) import Data.Map (Map) import System.IO (Handle, hPutStrLn, withFile, IOMode(WriteMode)) import Text.Printf (printf) import qualified Data.Map as Map import GHC.RTS.Events.Analyze.Analysis import GHC.RTS.Events.Analyze.Script import GHC.RTS.Events.Analyze.Types import GHC.RTS.Events.Analyze.Utils {------------------------------------------------------------------------------- Types -------------------------------------------------------------------------------} type Report = [ReportFragment] data ReportFragment = ReportSection Title | ReportLine ReportLine deriving Show data ReportLine = ReportLineData { lineHeader :: String , lineEventIds :: [EventId] , lineBackground :: Maybe (Int, Int) , lineValues :: Map Int Double } deriving Show {------------------------------------------------------------------------------- Report generation -------------------------------------------------------------------------------} createReport :: EventAnalysis -> Quantized -> Script -> Report createReport analysis Quantized{..} = concatMap go where go :: Command -> [ReportFragment] go (Section title) = [ReportSection title] go (One eid title) = [ReportLine $ reportLine title (eid, quantTimesForEvent eid)] go (All f sort) = map (ReportLine . reportLine Nothing) (sorted sort $ filtered f) go (Sum f title) = [ReportLine $ sumLines title $ map (reportLine Nothing) (filtered f)] reportLine :: Maybe Title -> (EventId, Map Int Double) -> ReportLine reportLine title (eid, qs) = ReportLineData { lineHeader = showTitle (showEventId quantThreadInfo eid) title , lineEventIds = [eid] , lineBackground = background eid , lineValues = qs } -- For threads we draw a background showing the thread's lifetime background :: EventId -> Maybe (Int, Int) background EventGC = Nothing background (EventUser _ _) = Nothing background (EventThread tid) = case Map.lookup tid quantThreadInfo of Just (start, stop, _) -> Just (start, stop) Nothing -> error $ "Invalid thread ID " ++ show tid quantTimesForEvent :: EventId -> Map Int Double quantTimesForEvent eid = case Map.lookup eid quantTimes of Nothing -> Map.empty -- this event didn't happen in the window Just times -> times sorted :: Maybe EventSort -> [(EventId, a)] -> [(EventId, a)] sorted Nothing = id sorted (Just sort) = sortBy (compareEventIds analysis sort `on` fst) filtered :: EventFilter -> [(EventId, Map Int Double)] filtered f = filter (matchesFilter f . fst) (Map.toList quantTimes) sumLines :: Maybe Title -> [ReportLine] -> ReportLine sumLines title qs = ReportLineData { lineHeader = showTitle "TOTAL" title , lineEventIds = concatMap lineEventIds qs , lineBackground = foldr1 combineBG $ map lineBackground qs , lineValues = Map.unionsWith (+) $ map lineValues qs } where combineBG :: Maybe (Int, Int) -> Maybe (Int, Int) -> Maybe (Int, Int) combineBG (Just (fr, to)) (Just (fr', to')) = Just (min fr fr', max to to') combineBG _ _ = Nothing showTitle :: String -> Maybe Title -> String showTitle _ (Just title) = title showTitle def Nothing = def {------------------------------------------------------------------------------- Write the report in textual form -------------------------------------------------------------------------------} writeReport :: Report -> FilePath -> IO () writeReport report path = withFile path WriteMode $ writeReport' report writeReport' :: Report -> Handle -> IO () writeReport' report h = mapM_ writeLine $ mapEithers id (renderTable (AlignLeft : repeat AlignRight)) $ map reportFragment report where writeLine :: Either String [String] -> IO () writeLine (Left header) = hPutStrLn h $ "\n" ++ header writeLine (Right cells) = hPutStrLn h $ intercalate " " cells reportFragment :: ReportFragment -> Either String [String] reportFragment (ReportSection title) = Left title reportFragment (ReportLine line) = Right (reportLine line) reportLine :: ReportLine -> [String] reportLine ReportLineData{..} = lineHeader : map showValue (unsparse 0 lineValues) showValue :: Double -> String showValue = printf "%0.2f"
WillSewell/ghc-events-analyze
src/GHC/RTS/Events/Analyze/Reports/Timed.hs
bsd-3-clause
4,605
0
12
966
1,336
717
619
-1
-1
-- Copyright (c) 2009, Diego Souza -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright notice, -- this list of conditions and the following disclaimer in the documentation -- and/or other materials provided with the distribution. -- * Neither the name of the <ORGANIZATION> nor the names of its contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. module Network.OAuth.Http.Util where splitBy :: (a -> Bool) -> [a] -> [[a]] splitBy = split (id) where split accum p (x:xs) | p x = (accum []) : split id p xs | otherwise = split (accum . (x:)) p xs split accum _ [] = [accum []]
dgvncsz0f/hoauth
src/main/haskell/Network/OAuth/Http/Util.hs
bsd-3-clause
1,851
0
11
371
171
102
69
7
2
module Network.HTTP.Convert.Internal where
konn/http-convert
Network/HTTP/Convert/Internal.hs
bsd-3-clause
43
0
3
3
8
6
2
1
0
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} module Soundcloud.Data.Track where import Data.Aeson import Data.Aeson.Types (Options(..), defaultOptions) import Data.Text (Text) import Data.Time import GHC.Generics (Generic) data Track = Track { artwork_url :: Text , attachments_uri :: Text , bpm :: Maybe Int , comment_count :: Int , commentable :: Bool , created_at :: Text -- Can't decode as UTCTime , description :: Text , download_count :: Int , downloadable :: Bool , download_url :: Maybe Text , duration :: Int , embeddable_by :: Text , favoritings_count :: Int , id :: Int , isrc :: Maybe Text , key_signature :: Text , kind :: Text , label_id :: Maybe Int , label_name :: Maybe Text , last_modified :: Text -- Can't decode as UTCTime :( , license :: Text , original_content_size :: Int -- # bytes , original_format :: Text , permalink :: Text , permalink_url :: Text , playback_count :: Int , purchase_title :: Maybe Text , purchase_url :: Maybe Text , release :: Text , release_day :: Maybe Int , release_month :: Maybe Int , release_year :: Maybe Int , sharing :: Text , state :: Text , streamable :: Bool , stream_url :: Text , tag_list :: Text , title :: Text , track_type :: Maybe Text , uri :: Text , user :: TrackUser , user_id :: Int , user_playback_count :: Maybe Int , video_url :: Maybe Text , waveform_url :: Text } deriving (Generic, Show) instance ToJSON Track instance FromJSON Track data TrackUser = TrackUser { u_avatar_url :: Text , u_id :: Int , u_kind :: Text , u_permalink :: Text , u_permalink_url :: Text , u_uri :: Text , u_username :: Text } deriving (Generic, Show) instance ToJSON TrackUser where toEncoding = genericToEncoding $ -- remove 'u_' defaultOptions { constructorTagModifier = drop 2 } instance FromJSON TrackUser where parseJSON = genericParseJSON $ defaultOptions { fieldLabelModifier = drop 2 }
tdietert/auto-playlist
src/Soundcloud/Data/Track.hs
bsd-3-clause
2,293
0
9
712
523
321
202
73
0
{-# LANGUAGE CPP #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} module Reflex.Dom.Internal ( module Main , run , mainWidget , mainWidgetWithHead, mainWidgetWithCss, mainWidgetWithHead', mainWidgetInElementById, runApp' , mainHydrationWidgetWithHead, mainHydrationWidgetWithHead' ) where import Data.ByteString (ByteString) import Data.Text (Text) import Reflex.Dom.Core (Widget) import Reflex.Dom.Main as Main hiding (mainWidget, mainWidgetWithHead, mainWidgetWithCss, mainWidgetWithHead', mainWidgetInElementById, runApp', mainHydrationWidgetWithHead, mainHydrationWidgetWithHead') import qualified Reflex.Dom.Main as Main (mainWidget, mainWidgetWithHead, mainWidgetWithCss, mainWidgetWithHead', mainWidgetInElementById, runApp', mainHydrationWidgetWithHead, mainHydrationWidgetWithHead') #if defined(ghcjs_HOST_OS) run :: a -> a run = id #elif defined(MIN_VERSION_jsaddle_warp) import Data.Maybe (maybe) import Data.Monoid ((<>)) import Language.Javascript.JSaddle (JSM) import qualified Language.Javascript.JSaddle.Warp as JW import System.Environment (lookupEnv) run :: JSM () -> IO() run jsm = do port <- maybe 3003 read <$> lookupEnv "JSADDLE_WARP_PORT" putStrLn $ "Running jsaddle-warp server on port " <> show port JW.run port jsm #elif defined(MIN_VERSION_jsaddle_wkwebview) #if defined(ios_HOST_OS) import Data.Default import Data.Monoid ((<>)) import Language.Javascript.JSaddle (JSM) import Language.Javascript.JSaddle.WKWebView (run', mainBundleResourcePath) import Language.Javascript.JSaddle.WKWebView.Internal (jsaddleMainHTMLWithBaseURL) -- TODO: upstream to jsaddle-wkwebview run :: JSM () -> IO () run jsm = do let indexHtml = "<!DOCTYPE html><html><head></head><body></body></html>" baseUrl <- mainBundleResourcePath >>= \case Nothing -> do putStrLn "Reflex.Dom.run: unable to find main bundle resource path. Assets may not load properly." return "" Just p -> return $ "file://" <> p <> "/index.html" run' def $ jsaddleMainHTMLWithBaseURL indexHtml baseUrl jsm #else import Language.Javascript.JSaddle.WKWebView (run) #endif #elif defined(ANDROID) import Android.HaskellActivity import Control.Monad import Control.Concurrent import Data.Default import Data.String import Reflex.Dom.Android.MainWidget import System.IO import Language.Javascript.JSaddle (JSM) run :: JSM () -> IO () run jsm = do hSetBuffering stdout LineBuffering hSetBuffering stderr LineBuffering continueWithCallbacks $ def { _activityCallbacks_onCreate = \_ -> do a <- getHaskellActivity let startPage = fromString "file:///android_asset/index.html" startMainWidget a startPage jsm } forever $ threadDelay 1000000000 #else import Language.Javascript.JSaddle.WebKitGTK (run) #endif mainWidget :: (forall x. Widget x ()) -> IO () mainWidget w = run $ Main.mainWidget w {-# INLINE mainWidget #-} mainWidgetWithHead :: (forall x. Widget x ()) -> (forall x. Widget x ()) -> IO () mainWidgetWithHead h b = run $ Main.mainWidgetWithHead h b {-# INLINE mainWidgetWithHead #-} mainWidgetWithCss :: ByteString -> (forall x. Widget x ()) -> IO () mainWidgetWithCss css w = run $ Main.mainWidgetWithCss css w {-# INLINE mainWidgetWithCss #-} mainWidgetWithHead' :: (a -> Widget () b, b -> Widget () a) -> IO () mainWidgetWithHead' w = run $ Main.mainWidgetWithHead' w {-# INLINE mainWidgetWithHead' #-} mainWidgetInElementById :: Text -> (forall x. Widget x ()) -> IO () mainWidgetInElementById eid w = run $ Main.mainWidgetInElementById eid w {-# INLINE mainWidgetInElementById #-} runApp' :: (forall x. AppInput DomTimeline -> Widget x (AppOutput DomTimeline)) -> IO () runApp' app = run $ Main.runApp' app {-# INLINE runApp' #-} mainHydrationWidgetWithHead :: (forall x. HydrationWidget x ()) -> (forall x. HydrationWidget x ()) -> IO () mainHydrationWidgetWithHead h b = run $ Main.mainHydrationWidgetWithHead h b {-# INLINE mainHydrationWidgetWithHead #-} mainHydrationWidgetWithHead' :: HydrationWidget () () -> HydrationWidget () () -> IO () mainHydrationWidgetWithHead' h b = run $ Main.mainHydrationWidgetWithHead' h b {-# INLINE mainHydrationWidgetWithHead' #-}
mightybyte/reflex-dom
reflex-dom/src/Reflex/Dom/Internal.hs
bsd-3-clause
4,272
0
11
637
638
351
287
47
1
module Client.Login where import Client.Facebook import qualified HSH as HSH import HSH ((-|-)) import Control.Monad.Reader import Control.Monad.State import Control.Concurrent import Debug.Trace import Text.JSON import System.Process createLoginUrl :: FacebookConfig -> String createLoginUrl config = "http://www.facebook.com/login.php?api_key=" ++ apiKey config ++ "&v=" ++ show version ++ "&fbconnect=1&connect_display=touch" createExtensionUrl apiKey perm = "http://m.facebook.com/authorize.php?api_key=" ++ apiKey ++ "&v=1.0&ext_perm=" ++ perm ++ "&next=http://fbplatform.mancrushonmcslee.com/textbook/permission.php" waitForUser :: String -> IO () waitForUser url = do HSH.runIO ("firefox \"" ++ url ++ "\"") print url print "Press enter when done..." getLine return () showBrowser :: String -> Maybe String -> IO () showBrowser url useragent = do system $ "lynx -accept-all-cookies " ++ maybe "" ("--useragent="++) useragent ++" -error-file=\"/tmp/fblynx\" \"" ++ url ++ "\"" return () waitForLogin :: String -> IO(String) waitForLogin url = do HSH.runIO "rm /tmp/fblynx;touch /tmp/fblynx;chmod 777 /tmp/fblynx" showBrowser url $ Just "mozilla" auth_token <- HSH.runSL "cat /tmp/fblynx | grep auth_token | sed 's/.*auth_token=\\(\\w*\\) .*/\\1/'" return auth_token -- strip the newline showLoginScreen :: FacebookM (GetSession) showLoginScreen = do config <- ask token <- liftIO $ waitForLogin $ createLoginUrl config session <- auth_getSession token return session askPermission :: String -> FacebookM () askPermission perm = do config <- ask liftIO $ showBrowser (createExtensionUrl (apiKey config) perm) Nothing
srush/TextBook
src/Client/Login.hs
bsd-3-clause
1,732
0
12
310
436
214
222
48
1
{-# LANGUAGE NoImplicitPrelude #-} module PropertyKeys ( keysTests ) where import Prelude.Compat import Control.Applicative (Const) import Data.Time.Compat (Day, LocalTime, TimeOfDay, UTCTime) import Data.Time.Calendar.Compat (DayOfWeek) import Data.Time.Calendar.Month.Compat (Month) import Data.Time.Calendar.Quarter.Compat (Quarter, QuarterOfYear) import Data.Version (Version) import Instances () import Numeric.Natural (Natural) import Test.Tasty (TestTree, testGroup) import Test.Tasty.QuickCheck (testProperty) import Types import qualified Data.Text as T import qualified Data.Text.Lazy as LT import qualified Data.UUID.Types as UUID import PropUtils keysTests :: TestTree keysTests = testGroup "roundTrip Key" [ testProperty "Bool" $ roundTripKey True , testProperty "Text" $ roundTripKey (undefined :: T.Text) , testProperty "String" $ roundTripKey (undefined :: String) , testProperty "Int" $ roundTripKey (undefined :: Int) , testProperty "[Text]" $ roundTripKey (undefined :: LogScaled [T.Text]) , testProperty "(Int,Char)" $ roundTripKey (undefined :: (Int,Char)) , testProperty "Integer" $ roundTripKey (undefined :: Integer) , testProperty "Natural" $ roundTripKey (undefined :: Natural) , testProperty "Float" $ roundTripKey (undefined :: Float) , testProperty "Double" $ roundTripKey (undefined :: Double) , testProperty "Day" $ roundTripKey (undefined :: Day) , testProperty "DayOfWeek" $ roundTripKey (undefined :: DayOfWeek) , testProperty "Month" $ roundTripKey (undefined :: Month) , testProperty "Quarter" $ roundTripKey (undefined :: Quarter) , testProperty "QuarterOfYear" $ roundTripKey (undefined :: QuarterOfYear) , testProperty "LocalTime" $ roundTripKey (undefined :: LocalTime) , testProperty "TimeOfDay" $ roundTripKey (undefined :: TimeOfDay) , testProperty "UTCTime" $ roundTripKey (undefined :: UTCTime) , testProperty "Version" $ roundTripKey (undefined :: Version) , testProperty "Lazy Text" $ roundTripKey (undefined :: LT.Text) , testProperty "UUID" $ roundTripKey UUID.nil , testProperty "Const Text" $ roundTripKey (undefined :: Const T.Text ()) ]
dmjio/aeson
tests/PropertyKeys.hs
bsd-3-clause
2,189
0
12
351
618
347
271
43
1
module TestSuite where import Control.Applicative hiding (empty) import Control.Monad import Control.Monad.ST import Control.Monad.Primitive import Control.Monad.State.Strict import Data.HashMap.Strict (empty) import qualified Data.HashMap.Strict as HashMap import Data.List import Data.Vector.Unboxed (Vector, Unbox) import qualified Data.Vector.Unboxed as V import GHC.Word import Observable.Core import Observable.MCMC import Observable.MCMC.Anneal import Observable.MCMC.Hamiltonian import Observable.MCMC.MetropolisHastings import Observable.MCMC.MALA import Observable.MCMC.NUTS import Observable.MCMC.Slice import Observable.Types import System.IO import System.Random.MWC hiding (Gen) import Test.Hspec import Test.QuickCheck hiding (vector, vectorOf, sample, frequency) prettyPrint :: Handle -> Vector Double -> IO () prettyPrint h = hPutStrLn h . filter (`notElem` "fromList []") . show rosenbrock :: Target Double rosenbrock = createTargetWithGradient lRosenbrock glRosenbrock where lRosenbrock :: Vector Double -> Double lRosenbrock xs = let [x0, x1] = V.toList xs in (-1) * (5 * (x1 - x0 ^ 2) ^ 2 + 0.05 * (1 - x0) ^ 2) glRosenbrock :: Vector Double -> Vector Double glRosenbrock xs = let [x, y] = V.toList xs dx = 20 * x * (y - x ^ 2) + 0.1 * (1 - x) dy = -10 * (y - x ^ 2) in V.fromList [dx, dy] himmelblau :: Target Double himmelblau = createTargetWithGradient lHimmelblau glHimmelblau where lHimmelblau :: Vector Double -> Double lHimmelblau xs = let [x0, x1] = V.toList xs in (-1) * ((x0 * x0 + x1 - 11) ^ 2 + (x0 + x1 * x1 - 7) ^ 2) glHimmelblau :: Vector Double -> Vector Double glHimmelblau xs = let [x, y] = V.toList xs quadFactor0 = x * x + y - 11 quadFactor1 = x + y * y - 7 dx = (-2) * (2 * quadFactor0 * x + quadFactor1) dy = (-2) * (quadFactor0 + 2 * quadFactor1 * y) in V.fromList [dx, dy] bnn :: Target Double bnn = createTargetWithGradient lBnn glBnn where lBnn :: Vector Double -> Double lBnn xs = let [x0, x1] = V.toList xs in -0.5 * (x0 ^ 2 * x1 ^ 2 + x0 ^ 2 + x1 ^ 2 - 8 * x0 - 8 * x1) glBnn :: Vector Double -> Vector Double glBnn xs = let [x, y] = V.toList xs dx = -0.5 * (2 * x * y * y + 2 * x - 8) dy = -0.5 * (2 * x * x * y + 2 * y - 8) in V.fromList [x, y] beale = createTargetWithGradient lBeale glBeale where lBeale :: Vector Double -> Double lBeale xs | and [x0 >= -4.5, x0 <= 4.5, x1 >= -4.5, x1 <= 4.5] = negate $ (1.5 - x0 + x0 * x1) ^ 2 + (2.25 - x0 + x0 * x1 ^ 2) ^ 2 + (2.625 - x0 + x0 * x1 ^ 3) ^ 2 | otherwise = - (1 / 0) where [x0, x1] = V.toList xs glBeale :: Vector Double -> Vector Double glBeale xs = let [x0, x1] = V.toList xs dx = negate $ 2 * (1.5 - x0 + x0 * x1) * ((-1) + x1) + 2.25 * 2 * (2.25 - x0 + x0 * x1 ^ 2) * ((-1) + x1 ^ 2) + 2.625 * 2 * (2.2625 - x0 + x0 * x1 ^ 3) * ((-1) + x1 ^ 3) dy = negate $ 2 * (1.5 - x0 + x0 * x1) * x0 + 2 * (2.25 - x0 + x0 * x1 ^ 2) * 2 * x0 * x1 + 2 * (2.625 - x0 + x0 * x1 ^ 3) * 3 * x0 * x1 ^ 2 in V.fromList [dx, dy] vector :: (Eq a, Unbox a, Arbitrary a) => Gen (Vector a) vector = V.fromList <$> listOf arbitrary target :: Gen (Target Double) target = elements [rosenbrock, himmelblau, bnn] spec_scalarTimesVector :: Spec spec_scalarTimesVector = describe "(.*)" $ do it "returns the zero vector when multiplied by zero" $ property $ do let zeros xs = V.fromList (replicate (V.length xs) 0) ds <- vector :: Gen (Vector Double) return $ 0 .* ds == zeros ds it "scales vectors correctly" $ property $ do vs <- vector `suchThat` (not . V.null) :: Gen (Vector Double) j <- choose (0, V.length vs - 1) :: Gen Int e <- arbitrary :: Gen Double return $ (e .* vs) V.! j == e * (vs V.! j) spec_metropolisHastings :: Spec spec_metropolisHastings = describe "metropolisHastings" $ it "should move around the state space" $ property $ do targetDist <- target mwcSeed <- arbitrary :: Gen Word32 e <- choose (0.00001, 10) position <- V.fromList <$> replicateM 2 (arbitrary :: Gen Double) let store = HashMap.insert MH (ODouble 0) HashMap.empty value = logObjective targetDist position chain = Chain position targetDist value store let tracked = runST $ do g <- initialize (V.singleton mwcSeed) traceChain 100 (metropolisHastings (Just e)) chain g return $ length (nub tracked) > 1 runSpecs :: IO () runSpecs = hspec $ do spec_scalarTimesVector spec_metropolisHastings mhStrategy :: PrimMonad m => Transition m Double mhStrategy = let radials = [0.1, 0.5, 1.0, 2.0, 2.5] in interleave $ map (metropolisHastings . Just) radials hmcStrategy :: PrimMonad m => Transition m Double hmcStrategy = hamiltonian (Just 0.05) (Just 10) malaStrategy :: PrimMonad m => Transition m Double malaStrategy = mala (Just 0.15) sliceStrategy :: PrimMonad m => Transition m Double sliceStrategy = do slice 0.5 slice 1.0 oneOf [slice 4.0, slice 10.0] nutsStrategy :: PrimMonad m => Transition m Double nutsStrategy = do nuts customStrategy :: PrimMonad m => Transition m Double customStrategy = do firstWithProb 0.8 (metropolisHastings (Just 3.0)) (hamiltonian (Just 0.05) (Just 20)) slice 3.0 nuts annealingStrategy :: PrimMonad m => Transition m Double annealingStrategy = do anneal 0.70 $ randomStrategy anneal 0.05 $ randomStrategy anneal 0.05 $ randomStrategy anneal 0.70 $ randomStrategy randomStrategy randomStrategy :: PrimMonad m => Transition m Double randomStrategy = frequency [ (5, metropolisHastings (Just 1.5)) , (4, slice 1.0) , (1, nuts) ] occasionallyJump :: PrimMonad m => Transition m Double occasionallyJump = frequency [ (4, slice 1.0) , (1, nuts) ] rosenbrockChain :: Chain Double rosenbrockChain = Chain position target value empty where position = V.fromList [1.0, 1.0] target = rosenbrock value = logObjective target position himmelblauChain :: Chain Double himmelblauChain = Chain position target value empty where position = V.fromList [1.0, 1.0] target = himmelblau value = logObjective target position bnnChain :: Chain Double bnnChain = Chain position target value empty where position = V.fromList [1.0, 1.0] target = bnn value = logObjective target position bealeChain :: Chain Double bealeChain = Chain position target value empty where position = V.fromList [1.0, 1.0] target = beale value = logObjective target position genericTrace :: Transition IO Double -> Chain Double -> Handle -> IO () genericTrace strategy chain h = create >>= \g -> traceChain 10000 strategy chain g >>= mapM_ (prettyPrint h) annealingTrace :: Chain Double -> Handle -> IO () annealingTrace chain h = create >>= \g -> do let c = annealTransitions $ replicate 5000 (metropolisHastings (Just 1.0) ) traceMarkovChain c chain g >>= mapM_ (prettyPrint h) hmcTrace :: Chain Double -> Handle -> IO () hmcTrace = genericTrace hmcStrategy malaTrace :: Chain Double -> Handle -> IO () malaTrace = genericTrace malaStrategy sliceTrace :: Chain Double -> Handle -> IO () sliceTrace = genericTrace sliceStrategy mhTrace :: Chain Double -> Handle -> IO () mhTrace = genericTrace mhStrategy nutsTrace :: Chain Double -> Handle -> IO () nutsTrace = genericTrace nutsStrategy customTrace :: Chain Double -> Handle -> IO () customTrace = genericTrace customStrategy jumpTrace :: Chain Double -> Handle -> IO () jumpTrace = genericTrace occasionallyJump annealTrace :: Chain Double -> Handle -> IO () annealTrace = genericTrace annealingStrategy main :: IO () main = do let chain = rosenbrockChain -- chains = [rosenbrockChain, himmelblauChain, bnnChain, bealeChain] -- chain <- observe (categorical chains) g h <- openFile "./test/trace.dat" WriteMode malaTrace chain h hClose h
jtobin/deprecated-observable
test/TestSuite.hs
bsd-3-clause
8,121
0
27
1,994
3,164
1,614
1,550
209
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TupleSections #-} -- | -- Module : Network.GitHub -- Copyright : (c) 2012 Vo Minh Thu, -- -- License : BSD-style -- Maintainer : thu@hypered.be -- Stability : experimental -- Portability : GHC -- -- This module provides bindings to the GitHub API v3. module Network.GitHub where import Control.Applicative ((<$>), (<*>)) import Control.Monad (mzero) import Data.Aeson import Data.Attoparsec.Lazy (parse, Result(..)) import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Base64 as B64 import qualified Data.ByteString.Lazy as L import Data.CaseInsensitive import Data.Text (Text) import qualified Data.Text as T import Network.HTTP.Enumerator -- | Construct a request from a `username:password` bytestring (suitable for a -- Basic Auth scheme), a URI (starting with a `/`, e.g. `/user/repos`), and a -- list of parameters. apiGetRequest :: B.ByteString -> String -> [(CI B.ByteString, B.ByteString)] -> IO (Request IO) apiGetRequest usernamePassword uri parameters = do let auth = "Basic " `B.append` B64.encode usernamePassword request <- parseUrl $ "https://api.github.com" ++ uri let request' = request { requestHeaders = ("Authorization", auth) : parameters } return request' -- | Construct a request from a `username:password` bytestring (suitable for a -- Basic Auth scheme), a URI (starting with a `/`, e.g. `/user/repos`), and a -- body. apiPostRequest :: B.ByteString -> String -> L.ByteString -> IO (Request IO) apiPostRequest usernamePassword uri body = do let auth = "Basic " `B.append` B64.encode usernamePassword request <- parseUrl $ "https://api.github.com" ++ uri let request' = request { method = "POST" , requestHeaders = [("Authorization", auth)] , requestBody = RequestBodyLBS body } return request' -- | Execute a GET agains the specified URI (e.g. `/user/repos`) using the -- supplied `username:password` and parameters. apiGet :: FromJSON a => String -> String -> [(CI B.ByteString, B.ByteString)] -> IO (Maybe a) apiGet usernamePassword uri parameters = do request <- apiGetRequest (B.pack usernamePassword) uri parameters Response{..} <- withManager $ httpLbs request case parse json responseBody of Done _ value -> do -- print value case fromJSON value of Success value' -> do return $ Just value' _ -> return Nothing _ -> return Nothing -- | Execute a POST agains the specified URI (e.g. `/user/repos`) using the -- supplied `username:password` and body. apiPost :: FromJSON a => String -> String -> L.ByteString -> IO (Maybe a) apiPost usernamePassword uri body = do request <- apiPostRequest (B.pack usernamePassword) uri body Response{..} <- withManager $ httpLbs request case parse json responseBody of Done _ value -> do print value case fromJSON value of Success value' -> do return $ Just value' _ -> return Nothing _ -> return Nothing -- | Return the list of repositories for a given `username:password` string. repositoryList :: String -> IO (Maybe [Repository]) repositoryList usernamePassword = apiGet usernamePassword "/user/repos" [] -- | Create a new repository from a given name and description. repositoryCreate :: String -> String -> Maybe String -> IO (Maybe Repository) repositoryCreate usernamePassword name description = apiPost usernamePassword "/user/repos" $ encode CreateRepository { createRepositoryName = T.pack name , createRepositoryDescription = T.pack <$> description } -- | Represent a repository. TODO add missing fields. data Repository = Repository { repositoryName :: Text , repositoryDescription :: Text } deriving Show instance FromJSON Repository where parseJSON (Object v) = Repository <$> v .: "name" <*> v .: "description" parseJSON _ = mzero -- | Data needed to create a new repository. data CreateRepository = CreateRepository { createRepositoryName :: Text , createRepositoryDescription :: Maybe Text } deriving Show instance ToJSON CreateRepository where toJSON CreateRepository{..} = object $ [ "name" .= createRepositoryName ] ++ maybe [] ((:[]) . ("description" .=)) createRepositoryDescription
noteed/hgithub
Network/GitHub.hs
bsd-3-clause
4,318
0
18
833
1,006
534
472
80
3
{-# LANGUAGE DeriveDataTypeable, DeriveGeneric, FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses, NoImplicitPrelude, OverloadedStrings #-} {-# LANGUAGE QuasiQuotes, ScopedTypeVariables, StandaloneDeriving, TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module FreeAgent.Core.Action ( toAction , extractAction, extractResult , matchAction, matchResult , decodeResult , decodeEnvelope , resultNow , registerAction, actionType , tryExec, tryExecWith , tryExecET, tryExecWithET , wrap, unWrap ) where import FreeAgent.AgentPrelude import FreeAgent.Core.Internal.Lenses hiding ((.=)) import Control.Monad.Writer (tell) import Data.Binary (Binary) import qualified Data.Binary as Binary import Data.Dynamic (cast) import qualified Data.Map as Map import Control.Error (hoistEither, hush) import Data.SafeCopy import Data.Serialize (Get, runGet) import Data.Aeson (Value (..), fromJSON, (.:), (.=)) import qualified Data.Aeson as Aeson -- Serialization instances for Action are all this module as they require specialized -- and sensitive functions we want to keep encapsulated e.g. (readPluginMaps) deriveSerializers ''Result deriveSerializers ''FailResult -- ActionEnvelope -- | A general type for transit of Actions through an agent network which -- may not have the required plugins available to deserialize the -- wrapped value. data ActionEnvelope = ActionEnvelope { envelopeKey :: Key , envelopeWrapped :: Wrapped , envelopeMeta :: Aeson.Object } deriving (Show, Eq, Typeable, Generic) instance Stashable ActionEnvelope where key = envelopeKey instance Runnable ActionEnvelope where exec env = do edecoded <- decodeEnvelope $ toAction env [qwarn|Executing ActionEnvelope for #{edecoded} |] case edecoded of Right action' -> exec action' Left msg -> return $ Left (DeserializationFailure (convert msg)) instance Binary Action where put (Action action) = Binary.put (seal action) get = fmap Action (Binary.get :: Binary.Get ActionEnvelope) instance SafeCopy Action where version = 1 kind = base errorTypeName _ = "FreeAgent.Type.Action" putCopy (Action action) = contain (safePut $ seal action) getCopy = contain $ fmap Action (safeGet :: Get ActionEnvelope) extractAction :: Typeable a=> Action -> Maybe a extractAction (Action a)= cast a extractResult :: Portable a => Result -> Maybe a extractResult = hush . unWrap . resultWrapped matchAction :: Typeable a => (a -> Bool) -> Action -> Bool matchAction f (Action a) = maybe False f (cast a) matchResult :: Portable a => (a -> Bool) -> Result -> Bool matchResult f = maybe False f . extractResult seal :: Runnable action => action -> ActionEnvelope seal action = fromMaybe ActionEnvelope { envelopeKey = key action , envelopeWrapped = wrap action , envelopeMeta = mempty --TODO:implement meta } (cast action) instance Stashable Action where key (Action a) = key a instance FromJSON Action where parseJSON (Object value') = do key' <- value' .: "key" type' <- value' .: "type" action' <- value' .: "action" return $ toAction $ ActionEnvelope key' (WrappedJson type' action') mempty parseJSON _ = mzero instance ToJSON Action where toJSON (Action action') = Aeson.object ["key" .= key action', "type" .= fqName action', "action" .= toJSON action'] instance Runnable Action where exec (Action action') = exec action' execWith (Action action') = execWith action' -- | Wrap a concrete action in existential unless it is already an Action -- in which case the original is returned. toAction :: (Runnable a) => a -> Action toAction act = fromMaybe (Action act) (cast act) resultNow :: (MonadIO io, Runnable action, Portable result) => result -> Text -> action -> io Result resultNow result text' action = do time <- getCurrentTime return (Result (wrap result) time text' (toAction action)) -- | Use to register your Action types so they can be -- deserialized dynamically at runtime; invoke as: registerAction :: forall a. (Runnable a) => Proxy a -> ActionsWriter registerAction action' = tell [ (ActionUnwrappers(proxyFqName action') (unwrapAction (unWrap :: Unwrapper a)) ,ResultUnwrappers(proxyFqName (Proxy :: Proxy (RunnableResult a))) (unwrapResult (unWrap :: Unwrapper (RunnableResult a))) ) ] unwrapResult :: Portable a => Unwrapper a -> Result -> Result unwrapResult uw result = let wrapped = resultWrapped result in case uw wrapped of Right unwrapped -> result {resultWrapped = wrap unwrapped} Left s -> error . convert $ "unwrapResult failed for: " ++ wrappedTypeName wrapped ++ " : " ++ convert s -- | Used only to fix the type passed to 'register' - this should not -- ever be evaluated and will throw an error if it is actionType :: (Runnable a) => Proxy a actionType = Proxy :: Proxy a -- | Does tryAny on exec and converts SomeException to RunnableFail. tryExec :: (Runnable action, MonadAgent agent) => action -> agent (Either RunnableFail Result) tryExec action' = either (Left . convert) id <$> tryAny (exec action') -- | Does tryAny on execWith and converts SomeException to RunnableFail. tryExecWith :: (Runnable action, MonadAgent agent) => action -> Result -> agent (Either RunnableFail Result) tryExecWith action' result' = either (Left . convert) id <$> tryAny (execWith action' result') -- | Like tryExec but hoists into an ExceptT monad. tryExecET :: (Runnable action, MonadAgent agent) => action -> ExceptT RunnableFail agent Result tryExecET = tryExec >=> hoistEither -- | Like tryExecWith but hoists into an ExceptT monad. tryExecWithET :: (Runnable action, MonadAgent agent) => action -> Result -> ExceptT RunnableFail agent Result tryExecWithET action' = tryExecWith action' >=> hoistEither -- | Unwrap a concrete type into an Action -- unwrapAction :: (Runnable a) => Unwrapper a -> Wrapped -> FetchAction unwrapAction uw wrapped = Action <$> uw wrapped -- Wrap a concrete type for stash or send where it -- will be decoded to an Action or Result wrap :: (Portable a) => a -> Wrapped wrap st = WrappedExists (fqName st) st -- | Unwrap a 'Wrapper' into a (known) concrete type unWrap :: forall a. (Portable a) => Wrapped -> Either String a unWrap (WrappedEncoded _ bytes')= safeDecode bytes' unWrap (WrappedJson _ val')= case fromJSON val' of Aeson.Success val -> Right val Aeson.Error reason -> Left reason unWrap (WrappedExists _ payload) = maybe (Left failcast) Right (cast payload) where failcast = convert $ fqName payload <> " does not match " <> fqName (undefined :: a) safeDecode :: (SafeCopy a) => ByteString -> Either String a safeDecode = runGet safeGet decodeEnvelope :: ContextReader m => Action -> m (Either String Action) decodeEnvelope action' = do pluginMap <- viewContext (plugins.actionUnwrappers) return $ case extractAction action' of Just envelope -> let wrapped = envelopeWrapped envelope in case Map.lookup (wrappedTypeName wrapped) pluginMap of Just uwMap -> let uw = actionUnwrapper uwMap in uw wrapped Nothing -> Left $ "No unwrapper found for: " ++ convert (wrappedTypeName wrapped) Nothing -> Right action' --not an envelope - its already decoded decodeResult :: ContextReader m => Result -> m (Maybe Result) decodeResult wrapped = do pluginMap <- viewContext (plugins.resultUnwrappers) return $ case Map.lookup (wrappedTypeName (resultWrapped wrapped)) pluginMap of Just uwMap -> Just $ let uw = resultUnwrapper uwMap in uw wrapped Nothing -> Nothing deriveSerializers ''ActionEnvelope
jeremyjh/free-agent
core/src/FreeAgent/Core/Action.hs
bsd-3-clause
8,403
0
20
2,162
2,134
1,098
1,036
156
3
{-| Module : IRTS.JavaScript.LangTransforms Description : The JavaScript LDecl Transformations. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE DeriveDataTypeable, OverloadedStrings, StandaloneDeriving #-} module IRTS.JavaScript.LangTransforms( removeDeadCode , globlToCon ) where import Control.DeepSeq import Control.Monad.Trans.State import Data.List import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Maybe import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import Idris.Core.CaseTree import Idris.Core.TT import IRTS.Lang import Data.Data import Data.Generics.Uniplate.Data import GHC.Generics (Generic) deriving instance Typeable FDesc deriving instance Data FDesc deriving instance Typeable LVar deriving instance Data LVar deriving instance Typeable PrimFn deriving instance Data PrimFn deriving instance Typeable CaseType deriving instance Data CaseType deriving instance Typeable LExp deriving instance Data LExp deriving instance Typeable LDecl deriving instance Data LDecl deriving instance Typeable LOpt deriving instance Data LOpt restrictKeys :: Ord k => Map k a -> Set k -> Map k a restrictKeys m s = Map.filterWithKey (\k _ -> k `Set.member` s) m mapMapListKeys :: Ord k => (a->a) -> [k] -> Map k a -> Map k a mapMapListKeys _ [] x = x mapMapListKeys f (t:r) x = mapMapListKeys f r $ Map.adjust f t x extractGlobs :: Map Name LDecl -> LDecl -> [Name] extractGlobs defs (LConstructor _ _ _) = [] extractGlobs defs (LFun _ _ _ e) = let f (LV x) = Just x f (LLazyApp x _) = Just x f _ = Nothing in [x | Just x <- map f $ universe e, Map.member x defs] usedFunctions :: Map Name LDecl -> Set Name -> [Name] -> [Name] usedFunctions _ _ [] = [] usedFunctions alldefs done names = let decls = catMaybes $ map (\x -> Map.lookup x alldefs) names used_names = (nub $ concat $ map (extractGlobs alldefs) decls) \\ names new_names = filter (\x -> not $ Set.member x done) used_names in used_names ++ usedFunctions alldefs (Set.union done $ Set.fromList new_names) new_names usedDecls :: Map Name LDecl -> [Name] -> Map Name LDecl usedDecls dcls start = let used = reverse $ start ++ usedFunctions dcls (Set.fromList start) start in restrictKeys dcls (Set.fromList used) getUsedConstructors :: Map Name LDecl -> Set Name getUsedConstructors x = Set.fromList [ n | LCon _ _ n _ <- universeBi x] removeUnusedBranches :: Set Name -> Map Name LDecl -> Map Name LDecl removeUnusedBranches used x = transformBi f x where f :: [LAlt] -> [LAlt] f ((LConCase x n y z):r) = if Set.member n used then ((LConCase x n y z):r) else r f x = x removeDeadCode :: Map Name LDecl -> [Name] -> Map Name LDecl removeDeadCode dcls start = let used = usedDecls dcls start remCons = removeUnusedBranches (getUsedConstructors used) used in if Map.keys remCons == Map.keys dcls then remCons else removeDeadCode remCons start globlToCon :: Map Name LDecl -> Map Name LDecl globlToCon x = transformBi (f x) x where f :: Map Name LDecl -> LExp -> LExp f y x@(LV n) = case Map.lookup n y of Just (LConstructor _ conId arity) -> LCon Nothing conId n [] _ -> x f y x = x
markuspf/Idris-dev
src/IRTS/JavaScript/LangTransforms.hs
bsd-3-clause
3,389
0
14
748
1,233
630
603
81
3
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Network.Nylas.Client ( -- * Streaming Delta Consumption consumeDeltas -- * Requesting Individual Objects , getMessage , getThread ) where import Control.Lens (view, (&), (.~), (?~), (^.)) import Control.Monad ((=<<)) import qualified Data.ByteString.Char8 as B import Data.Either (Either (Left, Right)) import Data.Eq ((/=)) import Data.Functor ((<$>)) import Data.Maybe (Maybe, maybe) import Data.Monoid ((<>)) import qualified Data.Text as T import qualified Data.Text.Encoding as E import GHC.Base (($)) import qualified Network.Wreq as W import Pipes (Consumer, Producer, runEffect, (>->)) import Pipes.Aeson (DecodingError) import qualified Pipes.Aeson.Unchecked as AU import Pipes.HTTP (Manager, Request, applyBasicAuth, parseRequest, responseBody, withHTTP) import qualified Pipes.Prelude as P import System.IO (IO) import Network.Nylas.Types authenticatedOpts :: AccessToken -> W.Options -> W.Options authenticatedOpts (AccessToken t) = W.auth ?~ W.basicAuth (E.encodeUtf8 t) "" authenticatedReq :: AccessToken -> Request -> Request authenticatedReq (AccessToken t) = applyBasicAuth (E.encodeUtf8 t) (E.encodeUtf8 "") deltaStreamUrl :: Maybe Cursor -> Url deltaStreamUrl mCursor = T.unpack $ "https://api.nylas.com/delta/streaming?cursor=" <> maybe "0" _cursorId mCursor -- | Consume 'Delta's for the inbox associated with the provided 'AccessToken' -- since the optional 'Cursor' from Nylas' transactional -- <https://www.nylas.com/docs/platform#streaming_delta_updates Streaming Delta Updates endpoint>. -- -- Clients should keep track of the 'Cursor' from the latest 'Delta' consumed to -- resume consumption in the future. -- -- Any errors encountered during consumption (e.g. while writing to a database) -- should be surfaced using the 'ConsumerError' value constructor of -- 'StreamingError'. consumeDeltas :: Manager -> AccessToken -> Maybe Cursor -> Consumer Delta IO (Either StreamingError ()) -> IO (Either StreamingError ()) consumeDeltas m t mCursor consumer = do req <- parseRequest $ deltaStreamUrl mCursor withHTTP (authenticatedReq t req) m $ \resp -> do let body = responseBody resp >-> P.takeWhile (/= "\n") deltas = wrapError <$> view AU.decoded body runEffect $ deltas >-> consumer where wrapError :: Either (DecodingError, Producer B.ByteString IO ()) () -> Either StreamingError () wrapError (Left (err, leftovers)) = Left $ ParsingError err leftovers wrapError _ = Right () messageUrl :: NylasId -> Url messageUrl (NylasId i) = T.unpack $ "https://api.nylas.com/messages/" <> i -- | Fetch the 'Message' identified by 'NylasId' from the account associated -- with 'AccessToken'. getMessage :: Manager -> AccessToken -> NylasId -> IO Message getMessage mgr t i = (^. W.responseBody) <$> (W.asJSON =<< W.getWith opts url) where opts = W.defaults & authenticatedOpts t & W.manager .~ Right mgr url = messageUrl i threadUrl :: NylasId -> Url threadUrl (NylasId i) = T.unpack $ "https://api.nylas.com/threads/" <> i -- | Fetch the 'Thread' identified by 'NylasId' from the account associated with -- 'AccessToken'. getThread :: Manager -> AccessToken -> NylasId -> IO Thread getThread mgr t i = (^. W.responseBody) <$> (W.asJSON =<< W.getWith opts url) where opts = W.defaults & authenticatedOpts t & W.manager .~ Right mgr url = threadUrl i
bts/nylas-hs
src/Network/Nylas/Client.hs
bsd-3-clause
3,882
0
16
998
912
511
401
66
2
{-# LINE 1 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 2 "fptools\libraries\network\Network\Socket.hsc" #-} ----------------------------------------------------------------------------- -- | -- Module : Network.Socket -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/core/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : provisional -- Portability : portable -- -- The "Network.Socket" module is for when you want full control over -- sockets. Essentially the entire C socket API is exposed through -- this module; in general the operations follow the behaviour of the C -- functions of the same name (consult your favourite Unix networking book). -- -- A higher level interface to networking operations is provided -- through the module "Network". -- ----------------------------------------------------------------------------- {-# LINE 23 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 25 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 26 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 27 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 31 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 39 "fptools\libraries\network\Network\Socket.hsc" #-} -- In order to process this file, you need to have CALLCONV defined. module Network.Socket ( -- * Types Socket(..), -- instance Eq, Show Family(..), SocketType(..), SockAddr(..), SocketStatus(..), HostAddress, ShutdownCmd(..), ProtocolNumber, PortNumber(..), -- * Socket Operations socket, -- :: Family -> SocketType -> ProtocolNumber -> IO Socket {-# LINE 60 "fptools\libraries\network\Network\Socket.hsc" #-} connect, -- :: Socket -> SockAddr -> IO () bindSocket, -- :: Socket -> SockAddr -> IO () listen, -- :: Socket -> Int -> IO () accept, -- :: Socket -> IO (Socket, SockAddr) getPeerName, -- :: Socket -> IO SockAddr getSocketName, -- :: Socket -> IO SockAddr {-# LINE 71 "fptools\libraries\network\Network\Socket.hsc" #-} socketPort, -- :: Socket -> IO PortNumber socketToHandle, -- :: Socket -> IOMode -> IO Handle sendTo, -- :: Socket -> String -> SockAddr -> IO Int recvFrom, -- :: Socket -> Int -> IO (String, Int, SockAddr) send, -- :: Socket -> String -> IO Int recv, -- :: Socket -> Int -> IO String recvLen, -- :: Socket -> Int -> IO (String, Int) inet_addr, -- :: String -> IO HostAddress inet_ntoa, -- :: HostAddress -> IO String shutdown, -- :: Socket -> ShutdownCmd -> IO () sClose, -- :: Socket -> IO () -- ** Predicates on sockets sIsConnected, -- :: Socket -> IO Bool sIsBound, -- :: Socket -> IO Bool sIsListening, -- :: Socket -> IO Bool sIsReadable, -- :: Socket -> IO Bool sIsWritable, -- :: Socket -> IO Bool -- * Socket options SocketOption(..), getSocketOption, -- :: Socket -> SocketOption -> IO Int setSocketOption, -- :: Socket -> SocketOption -> Int -> IO () -- * File descriptor transmission {-# LINE 111 "fptools\libraries\network\Network\Socket.hsc" #-} -- * Special Constants aNY_PORT, -- :: PortNumber iNADDR_ANY, -- :: HostAddress sOMAXCONN, -- :: Int sOL_SOCKET, -- :: Int {-# LINE 120 "fptools\libraries\network\Network\Socket.hsc" #-} maxListenQueue, -- :: Int -- * Initialisation withSocketsDo, -- :: IO a -> IO a -- * Very low level operations -- in case you ever want to get at the underlying file descriptor.. fdSocket, -- :: Socket -> CInt mkSocket, -- :: CInt -> Family -- -> SocketType -- -> ProtocolNumber -- -> SocketStatus -- -> IO Socket -- * Internal -- | The following are exported ONLY for use in the BSD module and -- should not be used anywhere else. packFamily, unpackFamily, packSocketType, throwSocketErrorIfMinus1_ ) where {-# LINE 146 "fptools\libraries\network\Network\Socket.hsc" #-} import Hugs.Prelude import Hugs.IO ( openFd ) {-# CBITS HsNet.c initWinSock.c ancilData.c winSockErr.c #-} {-# LINE 151 "fptools\libraries\network\Network\Socket.hsc" #-} import Data.Word ( Word8, Word16, Word32 ) import Foreign.Ptr ( Ptr, castPtr, plusPtr ) import Foreign.Storable ( Storable(..) ) import Foreign.C.Error import Foreign.C.String ( withCString, peekCString, peekCStringLen, castCharToCChar ) import Foreign.C.Types ( CInt, CUInt, CChar, CSize ) import Foreign.Marshal.Alloc ( alloca, allocaBytes ) import Foreign.Marshal.Array ( peekArray, pokeArray0 ) import Foreign.Marshal.Utils ( with ) import System.IO import Control.Monad ( liftM, when ) import Data.Ratio ( (%) ) import qualified Control.Exception import Control.Concurrent.MVar {-# LINE 179 "fptools\libraries\network\Network\Socket.hsc" #-} ----------------------------------------------------------------------------- -- Socket types -- There are a few possible ways to do this. The first is convert the -- structs used in the C library into an equivalent Haskell type. An -- other possible implementation is to keep all the internals in the C -- code and use an Int## and a status flag. The second method is used -- here since a lot of the C structures are not required to be -- manipulated. -- Originally the status was non-mutable so we had to return a new -- socket each time we changed the status. This version now uses -- mutable variables to avoid the need to do this. The result is a -- cleaner interface and better security since the application -- programmer now can't circumvent the status information to perform -- invalid operations on sockets. data SocketStatus -- Returned Status Function called = NotConnected -- socket | Bound -- bindSocket | Listening -- listen | Connected -- connect/accept deriving (Eq, Show) data Socket = MkSocket CInt -- File Descriptor Family SocketType ProtocolNumber -- Protocol Number (MVar SocketStatus) -- Status Flag mkSocket :: CInt -> Family -> SocketType -> ProtocolNumber -> SocketStatus -> IO Socket mkSocket fd fam sType pNum stat = do mStat <- newMVar stat return (MkSocket fd fam sType pNum mStat) instance Eq Socket where (MkSocket _ _ _ _ m1) == (MkSocket _ _ _ _ m2) = m1 == m2 instance Show Socket where showsPrec n (MkSocket fd _ _ _ _) = showString "<socket: " . shows fd . showString ">" fdSocket :: Socket -> CInt fdSocket (MkSocket fd _ _ _ _) = fd type ProtocolNumber = CInt -- NOTE: HostAddresses are represented in network byte order. -- Functions that expect the address in machine byte order -- will have to perform the necessary translation. type HostAddress = Word32 ---------------------------------------------------------------------------- -- Port Numbers -- -- newtyped to prevent accidental use of sane-looking -- port numbers that haven't actually been converted to -- network-byte-order first. -- newtype PortNumber = PortNum Word16 deriving ( Eq, Ord ) instance Show PortNumber where showsPrec p pn = showsPrec p (portNumberToInt pn) intToPortNumber :: Int -> PortNumber intToPortNumber v = PortNum (htons (fromIntegral v)) portNumberToInt :: PortNumber -> Int portNumberToInt (PortNum po) = fromIntegral (ntohs po) foreign import stdcall unsafe "HsNet.h ntohs" ntohs :: Word16 -> Word16 foreign import stdcall unsafe "HsNet.h htons" htons :: Word16 -> Word16 --foreign import CALLCONV unsafe "ntohl" ntohl :: Word32 -> Word32 foreign import stdcall unsafe "HsNet.h htonl" htonl :: Word32 -> Word32 instance Enum PortNumber where toEnum = intToPortNumber fromEnum = portNumberToInt instance Num PortNumber where fromInteger i = intToPortNumber (fromInteger i) -- for completeness. (+) x y = intToPortNumber (portNumberToInt x + portNumberToInt y) (-) x y = intToPortNumber (portNumberToInt x - portNumberToInt y) negate x = intToPortNumber (-portNumberToInt x) (*) x y = intToPortNumber (portNumberToInt x * portNumberToInt y) abs n = intToPortNumber (abs (portNumberToInt n)) signum n = intToPortNumber (signum (portNumberToInt n)) instance Real PortNumber where toRational x = toInteger x % 1 instance Integral PortNumber where quotRem a b = let (c,d) = quotRem (portNumberToInt a) (portNumberToInt b) in (intToPortNumber c, intToPortNumber d) toInteger a = toInteger (portNumberToInt a) instance Storable PortNumber where sizeOf _ = sizeOf (undefined :: Word16) alignment _ = alignment (undefined :: Word16) poke p (PortNum po) = poke (castPtr p) po peek p = PortNum `liftM` peek (castPtr p) ----------------------------------------------------------------------------- -- SockAddr -- The scheme used for addressing sockets is somewhat quirky. The -- calls in the BSD socket API that need to know the socket address -- all operate in terms of struct sockaddr, a `virtual' type of -- socket address. -- The Internet family of sockets are addressed as struct sockaddr_in, -- so when calling functions that operate on struct sockaddr, we have -- to type cast the Internet socket address into a struct sockaddr. -- Instances of the structure for different families might *not* be -- the same size. Same casting is required of other families of -- sockets such as Xerox NS. Similarly for Unix domain sockets. -- To represent these socket addresses in Haskell-land, we do what BSD -- didn't do, and use a union/algebraic type for the different -- families. Currently only Unix domain sockets and the Internet family -- are supported. data SockAddr -- C Names = SockAddrInet PortNumber -- sin_port (network byte order) HostAddress -- sin_addr (ditto) {-# LINE 320 "fptools\libraries\network\Network\Socket.hsc" #-} deriving (Eq) {-# LINE 323 "fptools\libraries\network\Network\Socket.hsc" #-} type CSaFamily = (Word16) {-# LINE 324 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 329 "fptools\libraries\network\Network\Socket.hsc" #-} -- we can't write an instance of Storable for SockAddr, because the Storable -- class can't easily handle alternatives. {-# LINE 339 "fptools\libraries\network\Network\Socket.hsc" #-} pokeSockAddr p (SockAddrInet (PortNum port) addr) = do ((\hsc_ptr -> pokeByteOff hsc_ptr 0)) p ((2) :: CSaFamily) {-# LINE 341 "fptools\libraries\network\Network\Socket.hsc" #-} ((\hsc_ptr -> pokeByteOff hsc_ptr 2)) p port {-# LINE 342 "fptools\libraries\network\Network\Socket.hsc" #-} ((\hsc_ptr -> pokeByteOff hsc_ptr 4)) p addr {-# LINE 343 "fptools\libraries\network\Network\Socket.hsc" #-} peekSockAddr p = do family <- ((\hsc_ptr -> peekByteOff hsc_ptr 0)) p {-# LINE 346 "fptools\libraries\network\Network\Socket.hsc" #-} case family :: CSaFamily of {-# LINE 352 "fptools\libraries\network\Network\Socket.hsc" #-} (2) -> do {-# LINE 353 "fptools\libraries\network\Network\Socket.hsc" #-} addr <- ((\hsc_ptr -> peekByteOff hsc_ptr 4)) p {-# LINE 354 "fptools\libraries\network\Network\Socket.hsc" #-} port <- ((\hsc_ptr -> peekByteOff hsc_ptr 2)) p {-# LINE 355 "fptools\libraries\network\Network\Socket.hsc" #-} return (SockAddrInet (PortNum port) addr) -- size of struct sockaddr by family {-# LINE 361 "fptools\libraries\network\Network\Socket.hsc" #-} sizeOfSockAddr_Family AF_INET = 16 {-# LINE 362 "fptools\libraries\network\Network\Socket.hsc" #-} -- size of struct sockaddr by SockAddr {-# LINE 367 "fptools\libraries\network\Network\Socket.hsc" #-} sizeOfSockAddr (SockAddrInet _ _) = 16 {-# LINE 368 "fptools\libraries\network\Network\Socket.hsc" #-} withSockAddr :: SockAddr -> (Ptr SockAddr -> Int -> IO a) -> IO a withSockAddr addr f = do let sz = sizeOfSockAddr addr allocaBytes sz $ \p -> pokeSockAddr p addr >> f (castPtr p) sz withNewSockAddr :: Family -> (Ptr SockAddr -> Int -> IO a) -> IO a withNewSockAddr family f = do let sz = sizeOfSockAddr_Family family allocaBytes sz $ \ptr -> f ptr sz ----------------------------------------------------------------------------- -- Connection Functions -- In the following connection and binding primitives. The names of -- the equivalent C functions have been preserved where possible. It -- should be noted that some of these names used in the C library, -- \tr{bind} in particular, have a different meaning to many Haskell -- programmers and have thus been renamed by appending the prefix -- Socket. -- Create an unconnected socket of the given family, type and -- protocol. The most common invocation of $socket$ is the following: -- ... -- my_socket <- socket AF_INET Stream 6 -- ... socket :: Family -- Family Name (usually AF_INET) -> SocketType -- Socket Type (usually Stream) -> ProtocolNumber -- Protocol Number (getProtocolByName to find value) -> IO Socket -- Unconnected Socket socket family stype protocol = do fd <- throwSocketErrorIfMinus1Retry "socket" $ c_socket (packFamily family) (packSocketType stype) protocol {-# LINE 406 "fptools\libraries\network\Network\Socket.hsc" #-} socket_status <- newMVar NotConnected return (MkSocket fd family stype protocol socket_status) -- Create an unnamed pair of connected sockets, given family, type and -- protocol. Differs from a normal pipe in being a bi-directional channel -- of communication. {-# LINE 439 "fptools\libraries\network\Network\Socket.hsc" #-} ----------------------------------------------------------------------------- -- Binding a socket -- -- Given a port number this {\em binds} the socket to that port. This -- means that the programmer is only interested in data being sent to -- that port number. The $Family$ passed to $bindSocket$ must -- be the same as that passed to $socket$. If the special port -- number $aNY\_PORT$ is passed then the system assigns the next -- available use port. -- -- Port numbers for standard unix services can be found by calling -- $getServiceEntry$. These are traditionally port numbers below -- 1000; although there are afew, namely NFS and IRC, which used higher -- numbered ports. -- -- The port number allocated to a socket bound by using $aNY\_PORT$ can be -- found by calling $port$ bindSocket :: Socket -- Unconnected Socket -> SockAddr -- Address to Bind to -> IO () bindSocket (MkSocket s _family _stype _protocol socketStatus) addr = do modifyMVar_ socketStatus $ \ status -> do if status /= NotConnected then ioError (userError ("bindSocket: can't peform bind on socket in status " ++ show status)) else do withSockAddr addr $ \p_addr sz -> do status <- throwSocketErrorIfMinus1Retry "bind" $ c_bind s p_addr (fromIntegral sz) return Bound ----------------------------------------------------------------------------- -- Connecting a socket -- -- Make a connection to an already opened socket on a given machine -- and port. assumes that we have already called createSocket, -- otherwise it will fail. -- -- This is the dual to $bindSocket$. The {\em server} process will -- usually bind to a port number, the {\em client} will then connect -- to the same port number. Port numbers of user applications are -- normally agreed in advance, otherwise we must rely on some meta -- protocol for telling the other side what port number we have been -- allocated. connect :: Socket -- Unconnected Socket -> SockAddr -- Socket address stuff -> IO () connect sock@(MkSocket s _family _stype _protocol socketStatus) addr = do modifyMVar_ socketStatus $ \currentStatus -> do if currentStatus /= NotConnected then ioError (userError ("connect: can't peform connect on socket in status " ++ show currentStatus)) else do withSockAddr addr $ \p_addr sz -> do let connectLoop = do r <- c_connect s p_addr (fromIntegral sz) if r == -1 then do {-# LINE 512 "fptools\libraries\network\Network\Socket.hsc" #-} rc <- c_getLastError case rc of 10093 -> do -- WSANOTINITIALISED withSocketsDo (return ()) r <- c_connect s p_addr (fromIntegral sz) if r == -1 then (c_getLastError >>= throwSocketError "connect") else return r _ -> throwSocketError "connect" rc {-# LINE 522 "fptools\libraries\network\Network\Socket.hsc" #-} else return r connectBlocked = do {-# LINE 528 "fptools\libraries\network\Network\Socket.hsc" #-} err <- getSocketOption sock SoError if (err == 0) then return 0 else do ioError (errnoToIOError "connect" (Errno (fromIntegral err)) Nothing Nothing) connectLoop return Connected ----------------------------------------------------------------------------- -- Listen -- -- The programmer must call $listen$ to tell the system software that -- they are now interested in receiving data on this port. This must -- be called on the bound socket before any calls to read or write -- data are made. -- The programmer also gives a number which indicates the length of -- the incoming queue of unread messages for this socket. On most -- systems the maximum queue length is around 5. To remove a message -- from the queue for processing a call to $accept$ should be made. listen :: Socket -- Connected & Bound Socket -> Int -- Queue Length -> IO () listen (MkSocket s _family _stype _protocol socketStatus) backlog = do modifyMVar_ socketStatus $ \ status -> do if status /= Bound then ioError (userError ("listen: can't peform listen on socket in status " ++ show status)) else do throwSocketErrorIfMinus1Retry "listen" (c_listen s (fromIntegral backlog)) return Listening ----------------------------------------------------------------------------- -- Accept -- -- A call to `accept' only returns when data is available on the given -- socket, unless the socket has been set to non-blocking. It will -- return a new socket which should be used to read the incoming data and -- should then be closed. Using the socket returned by `accept' allows -- incoming requests to be queued on the original socket. accept :: Socket -- Queue Socket -> IO (Socket, -- Readable Socket SockAddr) -- Peer details accept sock@(MkSocket s family stype protocol status) = do currentStatus <- readMVar status okay <- sIsAcceptable sock if not okay then ioError (userError ("accept: can't perform accept on socket (" ++ (show (family,stype,protocol)) ++") in status " ++ show currentStatus)) else do let sz = sizeOfSockAddr_Family family allocaBytes sz $ \ sockaddr -> do {-# LINE 596 "fptools\libraries\network\Network\Socket.hsc" #-} with (fromIntegral sz) $ \ ptr_len -> do new_sock <- {-# LINE 602 "fptools\libraries\network\Network\Socket.hsc" #-} (c_accept s sockaddr ptr_len) {-# LINE 606 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 607 "fptools\libraries\network\Network\Socket.hsc" #-} addr <- peekSockAddr sockaddr new_status <- newMVar Connected return ((MkSocket new_sock family stype protocol new_status), addr) {-# LINE 621 "fptools\libraries\network\Network\Socket.hsc" #-} ----------------------------------------------------------------------------- -- sendTo & recvFrom sendTo :: Socket -- (possibly) bound/connected Socket -> String -- Data to send -> SockAddr -> IO Int -- Number of Bytes sent sendTo (MkSocket s _family _stype _protocol status) xs addr = do withSockAddr addr $ \p_addr sz -> do withCString xs $ \str -> do liftM fromIntegral $ {-# LINE 638 "fptools\libraries\network\Network\Socket.hsc" #-} c_sendto s str (fromIntegral $ length xs) 0{-flags-} p_addr (fromIntegral sz) recvFrom :: Socket -> Int -> IO (String, Int, SockAddr) recvFrom sock@(MkSocket s _family _stype _protocol status) nbytes | nbytes <= 0 = ioError (mkInvalidRecvArgError "Network.Socket.recvFrom") | otherwise = allocaBytes nbytes $ \ptr -> do withNewSockAddr AF_INET $ \ptr_addr sz -> do alloca $ \ptr_len -> do poke ptr_len (fromIntegral sz) len <- {-# LINE 654 "fptools\libraries\network\Network\Socket.hsc" #-} c_recvfrom s ptr (fromIntegral nbytes) 0{-flags-} ptr_addr ptr_len let len' = fromIntegral len if len' == 0 then ioError (mkEOFError "Network.Socket.recvFrom") else do flg <- sIsConnected sock -- For at least one implementation (WinSock 2), recvfrom() ignores -- filling in the sockaddr for connected TCP sockets. Cope with -- this by using getPeerName instead. sockaddr <- if flg then getPeerName sock else peekSockAddr ptr_addr str <- peekCStringLen (ptr,len') return (str, len', sockaddr) ----------------------------------------------------------------------------- -- send & recv send :: Socket -- Bound/Connected Socket -> String -- Data to send -> IO Int -- Number of Bytes sent send (MkSocket s _family _stype _protocol status) xs = do withCString xs $ \str -> do liftM fromIntegral $ {-# LINE 685 "fptools\libraries\network\Network\Socket.hsc" #-} c_send s str (fromIntegral $ length xs) 0{-flags-} recv :: Socket -> Int -> IO String recv sock l = recvLen sock l >>= \ (s,_) -> return s recvLen :: Socket -> Int -> IO (String, Int) recvLen sock@(MkSocket s _family _stype _protocol status) nbytes | nbytes <= 0 = ioError (mkInvalidRecvArgError "Network.Socket.recv") | otherwise = do allocaBytes nbytes $ \ptr -> do len <- {-# LINE 700 "fptools\libraries\network\Network\Socket.hsc" #-} c_recv s ptr (fromIntegral nbytes) 0{-flags-} let len' = fromIntegral len if len' == 0 then ioError (mkEOFError "Network.Socket.recv") else do s <- peekCStringLen (ptr,len') return (s, len') -- --------------------------------------------------------------------------- -- socketPort -- -- The port number the given socket is currently connected to can be -- determined by calling $port$, is generally only useful when bind -- was given $aNY\_PORT$. socketPort :: Socket -- Connected & Bound Socket -> IO PortNumber -- Port Number of Socket socketPort sock@(MkSocket _ AF_INET _ _ _) = do (SockAddrInet port _) <- getSocketName sock return port socketPort (MkSocket _ family _ _ _) = ioError (userError ("socketPort: not supported for Family " ++ show family)) -- --------------------------------------------------------------------------- -- getPeerName -- Calling $getPeerName$ returns the address details of the machine, -- other than the local one, which is connected to the socket. This is -- used in programs such as FTP to determine where to send the -- returning data. The corresponding call to get the details of the -- local machine is $getSocketName$. getPeerName :: Socket -> IO SockAddr getPeerName (MkSocket s family _ _ _) = do withNewSockAddr family $ \ptr sz -> do with (fromIntegral sz) $ \int_star -> do throwSocketErrorIfMinus1Retry "getPeerName" $ c_getpeername s ptr int_star sz <- peek int_star peekSockAddr ptr getSocketName :: Socket -> IO SockAddr getSocketName (MkSocket s family _ _ _) = do withNewSockAddr family $ \ptr sz -> do with (fromIntegral sz) $ \int_star -> do throwSocketErrorIfMinus1Retry "getSocketName" $ c_getsockname s ptr int_star peekSockAddr ptr ----------------------------------------------------------------------------- -- Socket Properties data SocketOption = DummySocketOption__ {-# LINE 754 "fptools\libraries\network\Network\Socket.hsc" #-} | Debug {- SO_DEBUG -} {-# LINE 756 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 757 "fptools\libraries\network\Network\Socket.hsc" #-} | ReuseAddr {- SO_REUSEADDR -} {-# LINE 759 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 760 "fptools\libraries\network\Network\Socket.hsc" #-} | Type {- SO_TYPE -} {-# LINE 762 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 763 "fptools\libraries\network\Network\Socket.hsc" #-} | SoError {- SO_ERROR -} {-# LINE 765 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 766 "fptools\libraries\network\Network\Socket.hsc" #-} | DontRoute {- SO_DONTROUTE -} {-# LINE 768 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 769 "fptools\libraries\network\Network\Socket.hsc" #-} | Broadcast {- SO_BROADCAST -} {-# LINE 771 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 772 "fptools\libraries\network\Network\Socket.hsc" #-} | SendBuffer {- SO_SNDBUF -} {-# LINE 774 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 775 "fptools\libraries\network\Network\Socket.hsc" #-} | RecvBuffer {- SO_RCVBUF -} {-# LINE 777 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 778 "fptools\libraries\network\Network\Socket.hsc" #-} | KeepAlive {- SO_KEEPALIVE -} {-# LINE 780 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 781 "fptools\libraries\network\Network\Socket.hsc" #-} | OOBInline {- SO_OOBINLINE -} {-# LINE 783 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 786 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 789 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 790 "fptools\libraries\network\Network\Socket.hsc" #-} | NoDelay {- TCP_NODELAY -} {-# LINE 792 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 793 "fptools\libraries\network\Network\Socket.hsc" #-} | Linger {- SO_LINGER -} {-# LINE 795 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 798 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 799 "fptools\libraries\network\Network\Socket.hsc" #-} | RecvLowWater {- SO_RCVLOWAT -} {-# LINE 801 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 802 "fptools\libraries\network\Network\Socket.hsc" #-} | SendLowWater {- SO_SNDLOWAT -} {-# LINE 804 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 805 "fptools\libraries\network\Network\Socket.hsc" #-} | RecvTimeOut {- SO_RCVTIMEO -} {-# LINE 807 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 808 "fptools\libraries\network\Network\Socket.hsc" #-} | SendTimeOut {- SO_SNDTIMEO -} {-# LINE 810 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 811 "fptools\libraries\network\Network\Socket.hsc" #-} | UseLoopBack {- SO_USELOOPBACK -} {-# LINE 813 "fptools\libraries\network\Network\Socket.hsc" #-} socketOptLevel :: SocketOption -> CInt socketOptLevel so = case so of {-# LINE 820 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 823 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 824 "fptools\libraries\network\Network\Socket.hsc" #-} NoDelay -> 6 {-# LINE 825 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 826 "fptools\libraries\network\Network\Socket.hsc" #-} _ -> 65535 {-# LINE 827 "fptools\libraries\network\Network\Socket.hsc" #-} packSocketOption :: SocketOption -> CInt packSocketOption so = case so of {-# LINE 832 "fptools\libraries\network\Network\Socket.hsc" #-} Debug -> 1 {-# LINE 833 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 834 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 835 "fptools\libraries\network\Network\Socket.hsc" #-} ReuseAddr -> 4 {-# LINE 836 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 837 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 838 "fptools\libraries\network\Network\Socket.hsc" #-} Type -> 4104 {-# LINE 839 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 840 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 841 "fptools\libraries\network\Network\Socket.hsc" #-} SoError -> 4103 {-# LINE 842 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 843 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 844 "fptools\libraries\network\Network\Socket.hsc" #-} DontRoute -> 16 {-# LINE 845 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 846 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 847 "fptools\libraries\network\Network\Socket.hsc" #-} Broadcast -> 32 {-# LINE 848 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 849 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 850 "fptools\libraries\network\Network\Socket.hsc" #-} SendBuffer -> 4097 {-# LINE 851 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 852 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 853 "fptools\libraries\network\Network\Socket.hsc" #-} RecvBuffer -> 4098 {-# LINE 854 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 855 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 856 "fptools\libraries\network\Network\Socket.hsc" #-} KeepAlive -> 8 {-# LINE 857 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 858 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 859 "fptools\libraries\network\Network\Socket.hsc" #-} OOBInline -> 256 {-# LINE 860 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 861 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 864 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 867 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 868 "fptools\libraries\network\Network\Socket.hsc" #-} NoDelay -> 1 {-# LINE 869 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 870 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 871 "fptools\libraries\network\Network\Socket.hsc" #-} Linger -> 128 {-# LINE 872 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 873 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 876 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 877 "fptools\libraries\network\Network\Socket.hsc" #-} RecvLowWater -> 4100 {-# LINE 878 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 879 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 880 "fptools\libraries\network\Network\Socket.hsc" #-} SendLowWater -> 4099 {-# LINE 881 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 882 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 883 "fptools\libraries\network\Network\Socket.hsc" #-} RecvTimeOut -> 4102 {-# LINE 884 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 885 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 886 "fptools\libraries\network\Network\Socket.hsc" #-} SendTimeOut -> 4101 {-# LINE 887 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 888 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 889 "fptools\libraries\network\Network\Socket.hsc" #-} UseLoopBack -> 64 {-# LINE 890 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 891 "fptools\libraries\network\Network\Socket.hsc" #-} setSocketOption :: Socket -> SocketOption -- Option Name -> Int -- Option Value -> IO () setSocketOption (MkSocket s _ _ _ _) so v = do with (fromIntegral v) $ \ptr_v -> do throwErrnoIfMinus1_ "setSocketOption" $ c_setsockopt s (socketOptLevel so) (packSocketOption so) ptr_v (fromIntegral (sizeOf v)) return () getSocketOption :: Socket -> SocketOption -- Option Name -> IO Int -- Option Value getSocketOption (MkSocket s _ _ _ _) so = do alloca $ \ptr_v -> with (fromIntegral (sizeOf (undefined :: CInt))) $ \ptr_sz -> do throwErrnoIfMinus1 "getSocketOption" $ c_getsockopt s (socketOptLevel so) (packSocketOption so) ptr_v ptr_sz fromIntegral `liftM` peek ptr_v {-# LINE 933 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1014 "fptools\libraries\network\Network\Socket.hsc" #-} {- A calling sequence table for the main functions is shown in the table below. \begin{figure}[h] \begin{center} \begin{tabular}{|l|c|c|c|c|c|c|c|}d \hline {\bf A Call to} & socket & connect & bindSocket & listen & accept & read & write \\ \hline {\bf Precedes} & & & & & & & \\ \hline socket & & & & & & & \\ \hline connect & + & & & & & & \\ \hline bindSocket & + & & & & & & \\ \hline listen & & & + & & & & \\ \hline accept & & & & + & & & \\ \hline read & & + & & + & + & + & + \\ \hline write & & + & & + & + & + & + \\ \hline \end{tabular} \caption{Sequence Table for Major functions of Socket} \label{tab:api-seq} \end{center} \end{figure} -} -- --------------------------------------------------------------------------- -- OS Dependent Definitions unpackFamily :: CInt -> Family packFamily :: Family -> CInt packSocketType :: SocketType -> CInt -- | Address Families. -- -- This data type might have different constructors depending on what is -- supported by the operating system. data Family = AF_UNSPEC -- unspecified {-# LINE 1063 "fptools\libraries\network\Network\Socket.hsc" #-} | AF_UNIX -- local to host (pipes, portals {-# LINE 1065 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1066 "fptools\libraries\network\Network\Socket.hsc" #-} | AF_INET -- internetwork: UDP, TCP, etc {-# LINE 1068 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1069 "fptools\libraries\network\Network\Socket.hsc" #-} | AF_INET6 -- Internet Protocol version 6 {-# LINE 1071 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1072 "fptools\libraries\network\Network\Socket.hsc" #-} | AF_IMPLINK -- arpanet imp addresses {-# LINE 1074 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1075 "fptools\libraries\network\Network\Socket.hsc" #-} | AF_PUP -- pup protocols: e.g. BSP {-# LINE 1077 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1078 "fptools\libraries\network\Network\Socket.hsc" #-} | AF_CHAOS -- mit CHAOS protocols {-# LINE 1080 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1081 "fptools\libraries\network\Network\Socket.hsc" #-} | AF_NS -- XEROX NS protocols {-# LINE 1083 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1086 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1087 "fptools\libraries\network\Network\Socket.hsc" #-} | AF_ECMA -- european computer manufacturers {-# LINE 1089 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1090 "fptools\libraries\network\Network\Socket.hsc" #-} | AF_DATAKIT -- datakit protocols {-# LINE 1092 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1093 "fptools\libraries\network\Network\Socket.hsc" #-} | AF_CCITT -- CCITT protocols, X.25 etc {-# LINE 1095 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1096 "fptools\libraries\network\Network\Socket.hsc" #-} | AF_SNA -- IBM SNA {-# LINE 1098 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1099 "fptools\libraries\network\Network\Socket.hsc" #-} | AF_DECnet -- DECnet {-# LINE 1101 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1102 "fptools\libraries\network\Network\Socket.hsc" #-} | AF_DLI -- Direct data link interface {-# LINE 1104 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1105 "fptools\libraries\network\Network\Socket.hsc" #-} | AF_LAT -- LAT {-# LINE 1107 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1108 "fptools\libraries\network\Network\Socket.hsc" #-} | AF_HYLINK -- NSC Hyperchannel {-# LINE 1110 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1111 "fptools\libraries\network\Network\Socket.hsc" #-} | AF_APPLETALK -- Apple Talk {-# LINE 1113 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1116 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1117 "fptools\libraries\network\Network\Socket.hsc" #-} | AF_NETBIOS -- NetBios-style addresses {-# LINE 1119 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1122 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1125 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1126 "fptools\libraries\network\Network\Socket.hsc" #-} | AF_ISO -- ISO protocols {-# LINE 1128 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1129 "fptools\libraries\network\Network\Socket.hsc" #-} | AF_OSI -- umbrella of all families used by OSI {-# LINE 1131 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1134 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1137 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1140 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1143 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1146 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1147 "fptools\libraries\network\Network\Socket.hsc" #-} | AF_IPX -- Novell Internet Protocol {-# LINE 1149 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1152 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1155 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1158 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1161 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1164 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1167 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1170 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1173 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1176 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1179 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1182 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1185 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1188 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1191 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1194 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1197 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1200 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1203 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1206 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1209 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1212 "fptools\libraries\network\Network\Socket.hsc" #-} deriving (Eq, Ord, Read, Show) ------ ------ packFamily f = case f of AF_UNSPEC -> 0 {-# LINE 1218 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1219 "fptools\libraries\network\Network\Socket.hsc" #-} AF_UNIX -> 1 {-# LINE 1220 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1221 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1222 "fptools\libraries\network\Network\Socket.hsc" #-} AF_INET -> 2 {-# LINE 1223 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1224 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1225 "fptools\libraries\network\Network\Socket.hsc" #-} AF_INET6 -> 23 {-# LINE 1226 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1227 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1228 "fptools\libraries\network\Network\Socket.hsc" #-} AF_IMPLINK -> 3 {-# LINE 1229 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1230 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1231 "fptools\libraries\network\Network\Socket.hsc" #-} AF_PUP -> 4 {-# LINE 1232 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1233 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1234 "fptools\libraries\network\Network\Socket.hsc" #-} AF_CHAOS -> 5 {-# LINE 1235 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1236 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1237 "fptools\libraries\network\Network\Socket.hsc" #-} AF_NS -> 6 {-# LINE 1238 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1239 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1242 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1243 "fptools\libraries\network\Network\Socket.hsc" #-} AF_ECMA -> 8 {-# LINE 1244 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1245 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1246 "fptools\libraries\network\Network\Socket.hsc" #-} AF_DATAKIT -> 9 {-# LINE 1247 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1248 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1249 "fptools\libraries\network\Network\Socket.hsc" #-} AF_CCITT -> 10 {-# LINE 1250 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1251 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1252 "fptools\libraries\network\Network\Socket.hsc" #-} AF_SNA -> 11 {-# LINE 1253 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1254 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1255 "fptools\libraries\network\Network\Socket.hsc" #-} AF_DECnet -> 12 {-# LINE 1256 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1257 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1258 "fptools\libraries\network\Network\Socket.hsc" #-} AF_DLI -> 13 {-# LINE 1259 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1260 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1261 "fptools\libraries\network\Network\Socket.hsc" #-} AF_LAT -> 14 {-# LINE 1262 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1263 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1264 "fptools\libraries\network\Network\Socket.hsc" #-} AF_HYLINK -> 15 {-# LINE 1265 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1266 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1267 "fptools\libraries\network\Network\Socket.hsc" #-} AF_APPLETALK -> 16 {-# LINE 1268 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1269 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1272 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1273 "fptools\libraries\network\Network\Socket.hsc" #-} AF_NETBIOS -> 17 {-# LINE 1274 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1275 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1278 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1281 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1282 "fptools\libraries\network\Network\Socket.hsc" #-} AF_ISO -> 7 {-# LINE 1283 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1284 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1285 "fptools\libraries\network\Network\Socket.hsc" #-} AF_OSI -> 7 {-# LINE 1286 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1287 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1290 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1293 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1296 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1299 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1302 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1303 "fptools\libraries\network\Network\Socket.hsc" #-} AF_IPX -> 6 {-# LINE 1304 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1305 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1308 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1311 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1314 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1317 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1320 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1323 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1326 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1329 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1332 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1335 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1338 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1341 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1344 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1347 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1350 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1353 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1356 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1359 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1362 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1365 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1368 "fptools\libraries\network\Network\Socket.hsc" #-} --------- ---------- unpackFamily f = case f of (0) -> AF_UNSPEC {-# LINE 1373 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1374 "fptools\libraries\network\Network\Socket.hsc" #-} (1) -> AF_UNIX {-# LINE 1375 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1376 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1377 "fptools\libraries\network\Network\Socket.hsc" #-} (2) -> AF_INET {-# LINE 1378 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1379 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1380 "fptools\libraries\network\Network\Socket.hsc" #-} (23) -> AF_INET6 {-# LINE 1381 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1382 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1383 "fptools\libraries\network\Network\Socket.hsc" #-} (3) -> AF_IMPLINK {-# LINE 1384 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1385 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1386 "fptools\libraries\network\Network\Socket.hsc" #-} (4) -> AF_PUP {-# LINE 1387 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1388 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1389 "fptools\libraries\network\Network\Socket.hsc" #-} (5) -> AF_CHAOS {-# LINE 1390 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1391 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1392 "fptools\libraries\network\Network\Socket.hsc" #-} (6) -> AF_NS {-# LINE 1393 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1394 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1397 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1398 "fptools\libraries\network\Network\Socket.hsc" #-} (8) -> AF_ECMA {-# LINE 1399 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1400 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1401 "fptools\libraries\network\Network\Socket.hsc" #-} (9) -> AF_DATAKIT {-# LINE 1402 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1403 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1404 "fptools\libraries\network\Network\Socket.hsc" #-} (10) -> AF_CCITT {-# LINE 1405 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1406 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1407 "fptools\libraries\network\Network\Socket.hsc" #-} (11) -> AF_SNA {-# LINE 1408 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1409 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1410 "fptools\libraries\network\Network\Socket.hsc" #-} (12) -> AF_DECnet {-# LINE 1411 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1412 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1413 "fptools\libraries\network\Network\Socket.hsc" #-} (13) -> AF_DLI {-# LINE 1414 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1415 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1416 "fptools\libraries\network\Network\Socket.hsc" #-} (14) -> AF_LAT {-# LINE 1417 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1418 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1419 "fptools\libraries\network\Network\Socket.hsc" #-} (15) -> AF_HYLINK {-# LINE 1420 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1421 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1422 "fptools\libraries\network\Network\Socket.hsc" #-} (16) -> AF_APPLETALK {-# LINE 1423 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1424 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1427 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1428 "fptools\libraries\network\Network\Socket.hsc" #-} (17) -> AF_NETBIOS {-# LINE 1429 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1430 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1433 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1436 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1437 "fptools\libraries\network\Network\Socket.hsc" #-} (7) -> AF_ISO {-# LINE 1438 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1439 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1440 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1443 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1444 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1447 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1450 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1453 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1456 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1459 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1460 "fptools\libraries\network\Network\Socket.hsc" #-} (6) -> AF_IPX {-# LINE 1461 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1462 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1465 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1468 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1471 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1474 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1477 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1480 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1483 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1486 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1489 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1492 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1495 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1498 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1501 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1504 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1507 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1510 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1513 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1516 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1519 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1522 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1525 "fptools\libraries\network\Network\Socket.hsc" #-} -- Socket Types. -- | Socket Types. -- -- This data type might have different constructors depending on what is -- supported by the operating system. data SocketType = NoSocketType {-# LINE 1535 "fptools\libraries\network\Network\Socket.hsc" #-} | Stream {-# LINE 1537 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1538 "fptools\libraries\network\Network\Socket.hsc" #-} | Datagram {-# LINE 1540 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1541 "fptools\libraries\network\Network\Socket.hsc" #-} | Raw {-# LINE 1543 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1544 "fptools\libraries\network\Network\Socket.hsc" #-} | RDM {-# LINE 1546 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1547 "fptools\libraries\network\Network\Socket.hsc" #-} | SeqPacket {-# LINE 1549 "fptools\libraries\network\Network\Socket.hsc" #-} deriving (Eq, Ord, Read, Show) packSocketType stype = case stype of NoSocketType -> 0 {-# LINE 1554 "fptools\libraries\network\Network\Socket.hsc" #-} Stream -> 1 {-# LINE 1555 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1556 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1557 "fptools\libraries\network\Network\Socket.hsc" #-} Datagram -> 2 {-# LINE 1558 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1559 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1560 "fptools\libraries\network\Network\Socket.hsc" #-} Raw -> 3 {-# LINE 1561 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1562 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1563 "fptools\libraries\network\Network\Socket.hsc" #-} RDM -> 4 {-# LINE 1564 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1565 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1566 "fptools\libraries\network\Network\Socket.hsc" #-} SeqPacket -> 5 {-# LINE 1567 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1568 "fptools\libraries\network\Network\Socket.hsc" #-} -- --------------------------------------------------------------------------- -- Utility Functions aNY_PORT :: PortNumber aNY_PORT = 0 iNADDR_ANY :: HostAddress iNADDR_ANY = htonl (0) {-# LINE 1577 "fptools\libraries\network\Network\Socket.hsc" #-} sOMAXCONN :: Int sOMAXCONN = 5 {-# LINE 1580 "fptools\libraries\network\Network\Socket.hsc" #-} sOL_SOCKET :: Int sOL_SOCKET = 65535 {-# LINE 1583 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1588 "fptools\libraries\network\Network\Socket.hsc" #-} maxListenQueue :: Int maxListenQueue = sOMAXCONN -- ----------------------------------------------------------------------------- data ShutdownCmd = ShutdownReceive | ShutdownSend | ShutdownBoth sdownCmdToInt :: ShutdownCmd -> CInt sdownCmdToInt ShutdownReceive = 0 sdownCmdToInt ShutdownSend = 1 sdownCmdToInt ShutdownBoth = 2 shutdown :: Socket -> ShutdownCmd -> IO () shutdown (MkSocket s _ _ _ _) stype = do throwSocketErrorIfMinus1Retry "shutdown" (c_shutdown s (sdownCmdToInt stype)) return () -- ----------------------------------------------------------------------------- sClose :: Socket -> IO () sClose (MkSocket s _ _ _ _) = do c_close s; return () -- ----------------------------------------------------------------------------- sIsConnected :: Socket -> IO Bool sIsConnected (MkSocket _ _ _ _ status) = do value <- readMVar status return (value == Connected) -- ----------------------------------------------------------------------------- -- Socket Predicates sIsBound :: Socket -> IO Bool sIsBound (MkSocket _ _ _ _ status) = do value <- readMVar status return (value == Bound) sIsListening :: Socket -> IO Bool sIsListening (MkSocket _ _ _ _ status) = do value <- readMVar status return (value == Listening) sIsReadable :: Socket -> IO Bool sIsReadable (MkSocket _ _ _ _ status) = do value <- readMVar status return (value == Listening || value == Connected) sIsWritable :: Socket -> IO Bool sIsWritable = sIsReadable -- sort of. sIsAcceptable :: Socket -> IO Bool {-# LINE 1649 "fptools\libraries\network\Network\Socket.hsc" #-} sIsAcceptable (MkSocket _ _ _ _ status) = do value <- readMVar status return (value == Connected || value == Listening) -- ----------------------------------------------------------------------------- -- Internet address manipulation routines: inet_addr :: String -> IO HostAddress inet_addr ipstr = do withCString ipstr $ \str -> do had <- c_inet_addr str if had == -1 then ioError (userError ("inet_addr: Malformed address: " ++ ipstr)) else return had -- network byte order inet_ntoa :: HostAddress -> IO String inet_ntoa haddr = do pstr <- c_inet_ntoa haddr peekCString pstr -- socketHandle turns a Socket into a Haskell IO Handle. By default, the new -- handle is unbuffered. Use hSetBuffering to alter this. {-# LINE 1673 "fptools\libraries\network\Network\Socket.hsc" #-} socketToHandle :: Socket -> IOMode -> IO Handle socketToHandle s@(MkSocket fd _ _ _ _) mode = do {-# LINE 1678 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1679 "fptools\libraries\network\Network\Socket.hsc" #-} openFd (fromIntegral fd) True{-is a socket-} mode True{-bin-} {-# LINE 1681 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1685 "fptools\libraries\network\Network\Socket.hsc" #-} mkInvalidRecvArgError :: String -> IOError mkInvalidRecvArgError loc = IOError Nothing {-# LINE 1691 "fptools\libraries\network\Network\Socket.hsc" #-} IllegalOperation {-# LINE 1693 "fptools\libraries\network\Network\Socket.hsc" #-} loc "non-positive length" Nothing mkEOFError :: String -> IOError mkEOFError loc = IOError Nothing EOF loc "end of file" Nothing -- --------------------------------------------------------------------------- -- WinSock support {-| On Windows operating systems, the networking subsystem has to be initialised using 'withSocketsDo' before any networking operations can be used. eg. > main = withSocketsDo $ do {...} Although this is only strictly necessary on Windows platforms, it is harmless on other platforms, so for portability it is good practice to use it all the time. -} withSocketsDo :: IO a -> IO a {-# LINE 1715 "fptools\libraries\network\Network\Socket.hsc" #-} withSocketsDo act = do x <- initWinSock if ( x /= 0 ) then ioError (userError "Failed to initialise WinSock") else do act `Control.Exception.finally` shutdownWinSock foreign import ccall unsafe "HsNet.h initWinSock" initWinSock :: IO Int foreign import ccall unsafe "HsNet.h shutdownWinSock" shutdownWinSock :: IO () {-# LINE 1726 "fptools\libraries\network\Network\Socket.hsc" #-} -- --------------------------------------------------------------------------- -- foreign imports from the C library foreign import ccall unsafe "HsNet.h my_inet_ntoa" c_inet_ntoa :: HostAddress -> IO (Ptr CChar) foreign import stdcall unsafe "HsNet.h inet_addr" c_inet_addr :: Ptr CChar -> IO HostAddress foreign import stdcall unsafe "HsNet.h shutdown" c_shutdown :: CInt -> CInt -> IO CInt {-# LINE 1743 "fptools\libraries\network\Network\Socket.hsc" #-} foreign import stdcall unsafe "HsNet.h closesocket" c_close :: CInt -> IO CInt {-# LINE 1746 "fptools\libraries\network\Network\Socket.hsc" #-} foreign import stdcall unsafe "HsNet.h socket" c_socket :: CInt -> CInt -> CInt -> IO CInt foreign import stdcall unsafe "HsNet.h bind" c_bind :: CInt -> Ptr SockAddr -> CInt{-CSockLen???-} -> IO CInt foreign import stdcall unsafe "HsNet.h connect" c_connect :: CInt -> Ptr SockAddr -> CInt{-CSockLen???-} -> IO CInt foreign import stdcall unsafe "HsNet.h accept" c_accept :: CInt -> Ptr SockAddr -> Ptr CInt{-CSockLen???-} -> IO CInt foreign import stdcall unsafe "HsNet.h listen" c_listen :: CInt -> CInt -> IO CInt foreign import stdcall unsafe "HsNet.h send" c_send :: CInt -> Ptr CChar -> CSize -> CInt -> IO CInt foreign import stdcall unsafe "HsNet.h sendto" c_sendto :: CInt -> Ptr CChar -> CSize -> CInt -> Ptr SockAddr -> CInt -> IO CInt foreign import stdcall unsafe "HsNet.h recv" c_recv :: CInt -> Ptr CChar -> CSize -> CInt -> IO CInt foreign import stdcall unsafe "HsNet.h recvfrom" c_recvfrom :: CInt -> Ptr CChar -> CSize -> CInt -> Ptr SockAddr -> Ptr CInt -> IO CInt foreign import stdcall unsafe "HsNet.h getpeername" c_getpeername :: CInt -> Ptr SockAddr -> Ptr CInt -> IO CInt foreign import stdcall unsafe "HsNet.h getsockname" c_getsockname :: CInt -> Ptr SockAddr -> Ptr CInt -> IO CInt foreign import stdcall unsafe "HsNet.h getsockopt" c_getsockopt :: CInt -> CInt -> CInt -> Ptr CInt -> Ptr CInt -> IO CInt foreign import stdcall unsafe "HsNet.h setsockopt" c_setsockopt :: CInt -> CInt -> CInt -> Ptr CInt -> CInt -> IO CInt ----------------------------------------------------------------------------- -- Support for thread-safe blocking operations in GHC. {-# LINE 1808 "fptools\libraries\network\Network\Socket.hsc" #-} throwErrnoIfMinus1Retry_mayBlock name _ act = throwSocketErrorIfMinus1Retry name act throwErrnoIfMinus1Retry_repeatOnBlock name _ act = throwSocketErrorIfMinus1Retry name act throwSocketErrorIfMinus1_ :: Num a => String -> IO a -> IO () throwSocketErrorIfMinus1_ name act = do throwSocketErrorIfMinus1Retry name act return () {-# LINE 1821 "fptools\libraries\network\Network\Socket.hsc" #-} throwSocketErrorIfMinus1Retry name act = do r <- act if (r == -1) then do rc <- c_getLastError case rc of 10093 -> do -- WSANOTINITIALISED withSocketsDo (return ()) r <- act if (r == -1) then (c_getLastError >>= throwSocketError name) else return r _ -> throwSocketError name rc else return r throwSocketError name rc = do pstr <- c_getWSError rc str <- peekCString pstr {-# LINE 1842 "fptools\libraries\network\Network\Socket.hsc" #-} ioError (userError (name ++ ": socket error - " ++ str)) {-# LINE 1844 "fptools\libraries\network\Network\Socket.hsc" #-} foreign import stdcall unsafe "HsNet.h WSAGetLastError" c_getLastError :: IO CInt foreign import ccall unsafe "HsNet.h getWSErrorDescr" c_getWSError :: CInt -> IO (Ptr CChar) {-# LINE 1854 "fptools\libraries\network\Network\Socket.hsc" #-} {-# LINE 1855 "fptools\libraries\network\Network\Socket.hsc" #-}
OS2World/DEV-UTIL-HUGS
libraries/Network/Socket.hs
bsd-3-clause
61,756
650
36
9,633
7,196
4,108
3,088
-1
-1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.Temperature.HR.Rules ( rules ) where import Data.String import Prelude import Duckling.Dimensions.Types import Duckling.Temperature.Helpers import Duckling.Temperature.Types (TemperatureData (..)) import Duckling.Types import qualified Duckling.Temperature.Types as TTemperature ruleLatentTempStupnjevi :: Rule ruleLatentTempStupnjevi = Rule { name = "<latent temp> stupnjevi" , pattern = [ dimension Temperature , regex "deg\\.?|stupa?nj((ev)?a)?|\x00b0" ] , prod = \tokens -> case tokens of (Token Temperature td:_) -> Just . Token Temperature $ withUnit TTemperature.Degree td _ -> Nothing } ruleTempCelzij :: Rule ruleTempCelzij = Rule { name = "<temp> Celzij" , pattern = [ dimension Temperature , regex "c(elz?(ija?)?)?\\.?" ] , prod = \tokens -> case tokens of (Token Temperature td:_) -> Just . Token Temperature $ withUnit TTemperature.Celsius td _ -> Nothing } ruleTempFahrenheit :: Rule ruleTempFahrenheit = Rule { name = "<temp> Fahrenheit" , pattern = [ dimension Temperature , regex "f(ah?rh?eh?n(h?eit)?)?\\.?" ] , prod = \tokens -> case tokens of (Token Temperature td:_) -> Just . Token Temperature $ withUnit TTemperature.Fahrenheit td _ -> Nothing } rules :: [Rule] rules = [ ruleLatentTempStupnjevi , ruleTempCelzij , ruleTempFahrenheit ]
rfranek/duckling
Duckling/Temperature/HR/Rules.hs
bsd-3-clause
1,772
0
13
372
371
214
157
46
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE Rank2Types #-} -- | -- This is a small example of how to construct a projection for a third-party library like -- @aeson@. -- -- To test this: -- -- > doctest Aeson.hs module Aeson where import Control.Lens import Data.Aeson import Data.ByteString.Lazy -- | -- >>> 5^.by aeson -- "5" -- >>> [1,2,3]^.by aeson -- "[1,2,3]" -- >>> aeson.both +~ 2 $ (2,3)^.by aeson -- "[4,5]" aeson, aeson' :: (FromJSON c, ToJSON d) => Projection ByteString ByteString c d aeson = projection encode decode aeson' = projection encode decode'
np/lens
examples/Aeson.hs
bsd-3-clause
572
0
6
98
87
56
31
9
1
{- | Module : ./GUI/ConsoleUtils.hs Description : simple command line dialogs Copyright : (c) C. Maeder, Uni Bremen 2002-2005 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : portable gui utilities that work via the console instead of using HTk The interface should remain compatible with GUI.HTkUtils so that GUI.Utils can reexport functions of both modules based on the presence of UNI_PACKAGE. -} module GUI.ConsoleUtils where import Data.Char import Data.List import Control.Monad ( unless ) infoDialog :: String -> String -> IO () infoDialog _title msg = putStrLn msg -- | present a list of choices and return the selection listBox :: String -> [String] -> IO (Maybe Int) listBox prompt choices = do putStrLn prompt mapM_ putStrLn $ zipWith (\ n -> (shows n ": " ++)) [0 :: Int ..] choices putStrLn "Please enter a number on the next line" s <- getLine if all isDigit s then let n = foldl ( \ r a -> r * 10 + digitToInt a) 0 s in if n >= length choices then putStrLn "number to large, try again" >> listBox prompt choices else putStrLn ("you have chosen entry \"" ++ choices !! n) >> return (Just n) else putStrLn ("illegal input \"" ++ s ++ "\" try again") >> listBox prompt choices -- | show text and ask to save it createTextSaveDisplay :: String -- ^ title of the window -> String -- ^ default filename for saving the text -> String -- ^ text to be displayed -> IO () createTextSaveDisplay t f txt = do putStrLn t putStrLn $ replicate (length t) '=' putStrLn "" putStrLn txt putStrLn "" askFileNameAndSave f txt -- | ask for a file name askFileNameAndSave :: String -- ^ default filename for saving the text -> String -- ^ text to be saved -> IO () askFileNameAndSave f txt = do putStrLn $ "save text in file \"" ++ f ++ "\"? (y/n)" s <- getLine if "y" `isPrefixOf` map toLower s then writeFile f txt else do putStrLn "enter new file name (or abort with return):" n <- getLine unless (null n) $ askFileNameAndSave n txt
spechub/Hets
GUI/ConsoleUtils.hs
gpl-2.0
2,327
0
16
690
488
239
249
43
3
{-# LANGUAGE OverloadedStrings #-} module HROOT.Data.Core.Class where import FFICXX.Generate.Code.Primitive ( bool , bool_ , charpp , cppclass, cppclass_, cppclasscopy_ , cstar_ , cstring , cstring_ , double , double_ , float , float_ , int , int_ , intp , self_ , short , short_ , uint , uint_ , void_ ) import FFICXX.Generate.Type.Cabal ( BuildType(..), Cabal(..), CabalName(..) ) import FFICXX.Generate.Type.Class ( Arg(..) , Class(..) , CTypes(CTShort,CTDouble,CTUShort) , CPPTypes(CPTClassRef) , Function(..) , IsConst(..) , ProtectedMethod(..) , TopLevel(..) -- , TLOrdinary(..) , Types(..) , Variable(..) ) import FFICXX.Generate.Type.Config ( ModuleUnit(..) , ModuleUnitImports(..) , modImports ) ------------------------ -- import from stdcxx -- ------------------------ stdcxx_cabal :: Cabal stdcxx_cabal = Cabal { cabal_pkgname = CabalName "stdcxx" , cabal_version = "0.6" , cabal_cheaderprefix = "STD" , cabal_moduleprefix = "STD" , cabal_additional_c_incs = [] , cabal_additional_c_srcs = [] , cabal_additional_pkgdeps = [] , cabal_license = Nothing , cabal_licensefile = Nothing , cabal_extraincludedirs = [] , cabal_extralibdirs = [] , cabal_extrafiles = [] , cabal_pkg_config_depends = [] , cabal_buildType = Simple } deletable :: Class deletable = AbstractClass { class_cabal = stdcxx_cabal , class_name = "Deletable" , class_parents = [] , class_protected = Protected [] , class_alias = Nothing , class_funcs = [ Destructor Nothing ] , class_vars = [] , class_tmpl_funcs = [] } ---------------------- -- start HROOT-core -- ---------------------- corecabal :: Cabal corecabal = Cabal { cabal_pkgname = CabalName "HROOT-core" , cabal_version = "0.10.0.1" , cabal_cheaderprefix = "HROOTCore" , cabal_moduleprefix = "HROOT.Core" , cabal_additional_c_incs = [] , cabal_additional_c_srcs = [] , cabal_additional_pkgdeps = [ CabalName "stdcxx" ] , cabal_license = Nothing , cabal_licensefile = Nothing , cabal_extraincludedirs = [] , cabal_extralibdirs = [] , cabal_extrafiles = [] , cabal_pkg_config_depends = [] , cabal_buildType = Custom [CabalName "Cabal", CabalName "base", CabalName "process"] } coreclass :: String -> [Class] -> [Function] -> Class coreclass n ps fs = Class { class_cabal = corecabal , class_name = n , class_parents = ps , class_protected = Protected [] , class_alias = Nothing , class_funcs = fs , class_vars = [] , class_tmpl_funcs = [] , class_has_proxy = False } ---------------- -- pod struct -- ---------------- -- This part should be reimplemented as Haskell Storable as fficxx will support. -- For now, these are implemented as "classes" rectangle_t :: Class rectangle_t = Class { class_cabal = corecabal , class_name = "Rectangle_t" , class_parents = [deletable] , class_protected = Protected [] , class_alias = Nothing , class_funcs = [] , class_vars = [ Variable (Arg (CT CTUShort NoConst) "fHeight") , Variable (Arg (CT CTUShort NoConst) "fWidth") , Variable (Arg (CT CTShort NoConst) "fX") , Variable (Arg (CT CTShort NoConst) "fY") ] , class_tmpl_funcs = [] , class_has_proxy = False } ---------------- -- starting A -- ---------------- tApplication :: Class tApplication = coreclass "TApplication" [tObject, tQObject] [ Constructor [ cstring "appClassName", intp "argc", charpp "argv" ] Nothing , Virtual void_ "Run" [ bool "retrn"] Nothing ] tArray :: Class tArray = coreclass "TArray" [deletable] [ Virtual double_ "GetAt" [ int "i" ] Nothing , NonVirtual int_ "GetSize" [] Nothing , Virtual void_ "Set" [ int "n" ] (Just "SetArray") , Virtual void_ "SetAt" [ double "v", int "i" ] Nothing ] tArrayC :: Class tArrayC = coreclass "TArrayC" [tArray] [] tArrayD :: Class tArrayD = coreclass "TArrayD" [tArray] [ NonVirtual double_ "At" [ int "i" ] Nothing , NonVirtual (cstar_ CTDouble) "GetArray" [] Nothing ] tArrayF :: Class tArrayF = coreclass "TArrayF" [tArray] [] tArrayI :: Class tArrayI = coreclass "TArrayI" [tArray] [] tArrayL :: Class tArrayL = coreclass "TArrayL" [tArray] [] tArrayL64 :: Class tArrayL64 = coreclass "TArrayL64" [tArray] [] tArrayS :: Class tArrayS = coreclass "TArrayS" [tArray] [] tAtt3D :: Class tAtt3D = coreclass "TAtt3D" [deletable] [] tAttAxis :: Class tAttAxis = coreclass "TAttAxis" [deletable] [ Constructor [] Nothing , Virtual int_ "GetNdivisions" [] Nothing , Virtual short_ "GetAxisColor" [] Nothing , Virtual short_ "GetLabelColor" [] Nothing , Virtual short_ "GetLabelFont" [] Nothing , Virtual float_ "GetLabelOffset" [] Nothing , Virtual float_ "GetLabelSize" [] Nothing , Virtual float_ "GetTitleOffset" [] Nothing , Virtual float_ "GetTitleSize" [] Nothing , Virtual float_ "GetTickLength" [] Nothing , Virtual short_ "GetTitleFont" [] Nothing -- omit.. , Virtual void_ "SetNdivisions" [int "n", bool "optim" ] Nothing , Virtual void_ "SetAxisColor" [short "color"] Nothing , Virtual void_ "SetLabelColor" [short "color" ] Nothing , Virtual void_ "SetLabelFont" [short "font"] Nothing , Virtual void_ "SetLabelOffset" [float "offset"] Nothing , Virtual void_ "SetLabelSize" [float "size" ] Nothing , Virtual void_ "SetTickLength" [float "length" ] Nothing , Virtual void_ "SetTitleOffset" [float "offset" ] Nothing , Virtual void_ "SetTitleSize" [float "size"] Nothing , Virtual void_ "SetTitleColor" [short "color"] Nothing , Virtual void_ "SetTitleFont" [short "font"] Nothing ] tAttBBox :: Class tAttBBox = coreclass "TAttBBox" [deletable] [] tAttBBox2D :: Class tAttBBox2D = AbstractClass { class_cabal = corecabal , class_name = "TAttBBox2D" , class_parents = [deletable] , class_protected = Protected [] , class_alias = Nothing , class_funcs = [ Virtual (cppclasscopy_ rectangle_t) "GetBBox" [] Nothing , Virtual void_ "SetBBoxX1" [ int "x" ] Nothing , Virtual void_ "SetBBoxX2" [ int "x" ] Nothing , Virtual void_ "SetBBoxY1" [ int "y" ] Nothing , Virtual void_ "SetBBoxY2" [ int "y" ] Nothing ] , class_vars = [] , class_tmpl_funcs = [] } tAttCanvas :: Class tAttCanvas = coreclass "TAttCanvas" [deletable] [ Constructor [] Nothing ] tAttFill :: Class tAttFill = coreclass "TAttFill" [deletable] [ Constructor [short "fcolor", short "fstyle"] Nothing , Virtual void_ "SetFillColor" [int "color" ] Nothing , Virtual void_ "SetFillStyle" [int "style" ] Nothing ] tAttLine :: Class tAttLine = coreclass "TAttLine" [deletable] [ Constructor [short "lcolor", short "lstyle", short "lwidth"] Nothing , NonVirtual int_ "DistancetoLine" [int "px", int "py", double "xp1", double "yp1", double "xp2", double "yp2"] Nothing , Virtual short_ "GetLineColor" [] Nothing , Virtual short_ "GetLineStyle" [] Nothing , Virtual short_ "GetLineWidth" [] Nothing -- , Virtual void_ "Modify" [] , Virtual void_ "ResetAttLine" [cstring "option"] Nothing -- SaveLineAttributes , Virtual void_ "SetLineAttributes" [] Nothing , Virtual void_ "SetLineColor" [short "lcolor" ] Nothing , Virtual void_ "SetLineStyle" [short "lstyle" ] Nothing , Virtual void_ "SetLineWidth" [short "lwidth" ] Nothing ] tAttMarker :: Class tAttMarker = coreclass "TAttMarker" [deletable] [ Constructor [short "color", short "style", short "msize"] Nothing , Virtual short_ "GetMarkerColor" [] Nothing , Virtual short_ "GetMarkerStyle" [] Nothing , Virtual float_ "GetMarkerSize" [] Nothing -- Modify , Virtual void_ "ResetAttMarker" [cstring "option"] Nothing , Virtual void_ "SetMarkerAttributes" [] Nothing , Virtual void_ "SetMarkerColor" [short "tcolor"] Nothing , Virtual void_ "SetMarkerStyle" [short "mstyle"] Nothing , Virtual void_ "SetMarkerSize" [short "msize"] Nothing ] tAttPad :: Class tAttPad = coreclass "TAttPad" [deletable] [ Constructor [] Nothing , NonVirtual float_ "GetBottomMargin" [] Nothing , NonVirtual float_ "GetLeftMargin" [] Nothing , NonVirtual float_ "GetRightMargin" [] Nothing , NonVirtual float_ "GetTopMargin" [] Nothing , NonVirtual float_ "GetAfile" [] Nothing , NonVirtual float_ "GetXfile" [] Nothing , NonVirtual float_ "GetYfile" [] Nothing , NonVirtual float_ "GetAstat" [] Nothing , NonVirtual float_ "GetXstat" [] Nothing , NonVirtual float_ "GetYstat" [] Nothing , NonVirtual short_ "GetFrameFillColor" [] Nothing , NonVirtual short_ "GetFrameLineColor" [] Nothing , NonVirtual short_ "GetFrameFillStyle" [] Nothing , NonVirtual short_ "GetFrameLineStyle" [] Nothing , NonVirtual short_ "GetFrameLineWidth" [] Nothing , NonVirtual short_ "GetFrameBorderSize" [] Nothing , NonVirtual short_ "GetFrameBorderMode" [] Nothing , Virtual void_ "ResetAttPad" [cstring "option"] Nothing , Virtual void_ "SetBottomMargin" [float "bottommargin"] Nothing , Virtual void_ "SetLeftMargin" [float "leftmargin"] Nothing , Virtual void_ "SetRightMargin" [float "rightmargin"] Nothing , Virtual void_ "SetTopMargin" [float "topmargin"] Nothing , Virtual void_ "SetMargin" [float "left", float "right", float "bottom", float "top"] Nothing , Virtual void_ "SetAfile" [float "afile"] Nothing , Virtual void_ "SetXfile" [float "xfile"] Nothing , Virtual void_ "SetYfile" [float "yfile"] Nothing , Virtual void_ "SetAstat" [float "astat"] Nothing , Virtual void_ "SetXstat" [float "xstat"] Nothing , Virtual void_ "SetYstat" [float "ystat"] Nothing , NonVirtual void_ "SetFrameFillColor" [short "color"] Nothing , NonVirtual void_ "SetFrameLineColor" [short "color"] Nothing , NonVirtual void_ "SetFrameFillStyle" [short "styl"] Nothing , NonVirtual void_ "SetFrameLineStyle" [short "styl"] Nothing , NonVirtual void_ "SetFrameLineWidth" [short "width"] Nothing , NonVirtual void_ "SetFrameBorderSize" [short "size"] Nothing , NonVirtual void_ "SetFrameBorderMode" [int "mode"] Nothing ] {- tAttParticle :: Class tAttParticle = coreclass "TAttParticle" [tNamed] [] -} tAttText :: Class tAttText = coreclass "TAttText" [deletable] [ Constructor [int "align", float "angle", short "color", short "font", float "tsize" ] Nothing , Virtual short_ "GetTextAlign" [] Nothing , Virtual float_ "GetTextAngle" [] Nothing , Virtual short_ "GetTextColor" [] Nothing , Virtual short_ "GetTextFont" [] Nothing , Virtual float_ "GetTextSize" [] Nothing , Virtual void_ "ResetAttText" [cstring "toption"] Nothing -- SaveTextAttributes , Virtual void_ "SetTextAttributes" [] Nothing , Virtual void_ "SetTextAlign" [short "align"] Nothing , Virtual void_ "SetTextAngle" [float "tangle"] Nothing , Virtual void_ "SetTextColor" [int "tcolor"] Nothing , Virtual void_ "SetTextFont" [short "tfont"] Nothing , Virtual void_ "SetTextSize" [float "tsize"] Nothing , Virtual void_ "SetTextSizePixels" [int "npixels"] Nothing ] ---------------- -- starting C -- ---------------- tClass :: Class tClass = coreclass "TClass" [tDictionary] [ ] tCollection :: Class tCollection = coreclass "TCollection" [tObject] [ ] tColor :: Class tColor = coreclass "TColor" [tNamed] [ Constructor [] (Just "newTColor_") , Constructor [float "r", float "g", float "b", float "a"] Nothing , Static (CPT (CPTClassRef tArrayI) Const) "GetPalette" [] Nothing ] ---------------- -- starting D -- ---------------- tDatime :: Class tDatime = coreclass "TDatime" [deletable] [ Constructor [int "year", int "month", int "day", int "hour", int "min", int "sec"] Nothing , Virtual uint_ "Convert" [bool "toGMT"] Nothing , NonVirtual int_ "GetDay" [] Nothing , NonVirtual int_ "GetHour" [] Nothing , NonVirtual int_ "GetMinute" [] Nothing , NonVirtual int_ "GetSecond" [] Nothing , NonVirtual int_ "GetYear" [] Nothing , NonVirtual int_ "GetMonth" [] Nothing , Virtual void_ "Set" [uint "tloc" ] (Just "setTDatime") ] tDictionary :: Class tDictionary = AbstractClass { class_cabal = corecabal , class_name = "TDictionary" , class_parents = [tNamed] , class_protected = Protected [] , class_alias = Nothing , class_funcs = [] , class_vars = [] , class_tmpl_funcs = [] } tDirectory :: Class tDirectory = coreclass "TDirectory" [tNamed] [ Static void_ "AddDirectory" [bool "add"] Nothing , Static bool_ "AddDirectoryStatus" [] Nothing , Virtual void_ "Append" [cppclass tObject "obj", bool "replace"] Nothing , Virtual void_ "Add" [cppclass tObject "obj", bool "replace"] (Just "addD") , Virtual int_ "AppendKey" [cppclass tKey "key" ] Nothing , Virtual void_ "Close" [ cstring "option" ] Nothing , Virtual (cppclass_ tObject) "Get" [ cstring "namecycle" ] Nothing , Virtual bool_ "cd" [ cstring "path" ] (Just "cd_TDirectory") ] ---------------- -- starting G -- ---------------- tGlobal :: Class tGlobal = coreclass "TGlobal" [tDictionary] [ ] ---------------- -- starting K -- ---------------- tKey :: Class tKey = coreclass "TKey" [tNamed] [ Constructor [ cstring "name", cstring "title", cppclass tClass "cl", int "nbytes" , cppclass tDirectory "motherDir"] Nothing ] ---------------- -- starting M -- ---------------- tMutex :: Class tMutex = coreclass "TMutex" [tVirtualMutex] [ Constructor [ bool "recursive" ] Nothing ] ---------------- -- starting N -- ---------------- tNamed :: Class tNamed = coreclass "TNamed" [tObject] [ Constructor [cstring "name", cstring "title"] Nothing , Virtual void_ "SetName" [cstring "name"] Nothing , Virtual void_ "SetNameTitle" [cstring "name", cstring "title"] Nothing , Virtual void_ "SetTitle" [cstring "name"] Nothing ] ---------------- -- starting O -- ---------------- tObjArray :: Class tObjArray = coreclass "TObjArray" [tSeqCollection] [] tObject :: Class tObject = coreclass "TObject" [deletable] [ Constructor [] Nothing , Virtual void_ "Clear" [cstring "option"] Nothing -- , Virtual int_ "DistancetoPrimitive" [int "px", int "py"] , Virtual void_ "Draw" [cstring "option"] Nothing -- , Virtual void_ "ExecuteEvent" [int "event", int "px", int "py"] , Virtual (cppclass_ tObject) "FindObject" [cstring "name"] Nothing , Virtual cstring_ "GetName" [] Nothing , Virtual (cppclass_ tClass) "IsA" [] Nothing , Virtual void_ "Paint" [cstring "option"] Nothing , Virtual void_ "Print" [cstring "option"] (Just "printObj") , Virtual void_ "SaveAs" [cstring "filename", cstring "option"] Nothing , Virtual int_ "Write" [cstring "name", int "option", int "bufsize" ] Nothing , Virtual int_ "Write" [] (Just "Write_") , Static bool_ "GetObjectStat" [] Nothing ] ---------------- -- starting Q -- ---------------- tQObject :: Class tQObject = coreclass "TQObject" [deletable] [] ---------------- -- starting R -- ---------------- tROOT :: Class tROOT = coreclass "TROOT" [tDirectory] [ NonVirtual (cppclass_ tGlobal) "GetGlobal" [ cstring "name", bool "load" ] Nothing , Static bool_ "Initialized" [] Nothing ] ---------------- -- starting S -- ---------------- tSeqCollection :: Class tSeqCollection = coreclass "TSeqCollection" [tCollection] [] tString :: Class tString = coreclass "TString" [] [ Constructor [ cstring "s" ] Nothing ] tStyle :: Class tStyle = coreclass "TStyle" [tNamed, tAttLine, tAttFill, tAttMarker, tAttText] [ NonVirtual void_ "SetCanvasPreferGL" [bool "prefer"] Nothing , NonVirtual void_ "SetOptDate" [int "optdate"] Nothing , NonVirtual void_ "SetOptFile" [int "file"] Nothing , NonVirtual void_ "SetOptFit" [int "mode"] Nothing , NonVirtual void_ "SetOptLogx" [int "logx"] Nothing , NonVirtual void_ "SetOptLogy" [int "logy"] Nothing , NonVirtual void_ "SetOptLogz" [int "logz"] Nothing , NonVirtual void_ "SetOptStat" [int "mode"] Nothing , NonVirtual void_ "SetOptTitle" [int "tit"] Nothing , NonVirtual void_ "SetPalette" [int "ncolors"] Nothing ] tSystem :: Class tSystem = coreclass "TSystem" [tNamed] [ Virtual bool_ "ProcessEvents" [] Nothing ] ---------------- -- starting V -- ---------------- tVirtualMutex :: Class tVirtualMutex = AbstractClass { class_cabal = corecabal , class_name = "TVirtualMutex" , class_parents = [deletable] , class_protected = Protected [] , class_alias = Nothing , class_funcs = [ Virtual int_ "CleanUp" [] Nothing , Virtual self_ "Factory" [bool "recursive" ] Nothing , Virtual int_ "Lock" [] Nothing , Virtual int_ "TryLock" [] Nothing , Virtual int_ "UnLock" [] Nothing ] , class_vars = [] , class_tmpl_funcs = [] } tVirtualPad :: Class tVirtualPad = coreclass "TVirtualPad" [tObject, tAttLine, tAttFill, tAttPad, tQObject] [ Virtual self_ "cd" [int "subpadnumber"] Nothing , Virtual void_ "Divide" [int "nx", int "ny", float "xmargin", float "ymargin", int "color" ] (Just "divide_tvirtualpad") , Virtual void_ "Modified" [bool "flag"] Nothing , Virtual void_ "Range" [double "x1", double "y1", double "x2", double "y2"] Nothing , Virtual void_ "SetLogx" [int "value"] Nothing , Virtual void_ "SetLogy" [int "value"] Nothing , Virtual void_ "SetLogz" [int "value"] Nothing , Virtual void_ "Update" [] Nothing ] core_classes :: [Class] core_classes = [ rectangle_t , tApplication, tArray, tArrayC, tArrayD, tArrayF, tArrayI, tArrayL, tArrayL64, tArrayS , tAtt3D, tAttAxis, tAttBBox, tAttBBox2D, tAttCanvas, tAttFill, tAttLine, tAttMarker, tAttPad, tAttText , tClass, tCollection, tColor , tDatime, tDictionary, tDirectory , tGlobal , tKey , tMutex , tNamed , tObjArray, tObject , tQObject , tROOT , tSeqCollection, tStyle, tSystem , tVirtualMutex, tVirtualPad ] -- TLOrdinary later core_topfunctions :: [TopLevel] core_topfunctions = [ TopLevelFunction (cppclass_ tROOT) "GetROOT" [] Nothing , TopLevelVariable (cppclass_ tROOT) "gROOT" Nothing , TopLevelVariable (cppclass_ tSystem) "gSystem" Nothing , TopLevelVariable (cppclass_ tStyle) "gStyle" Nothing ] core_headers :: [(ModuleUnit,ModuleUnitImports)] core_headers = [ modImports "Rectangle_t" [] ["GuiTypes.h"] , modImports "TApplication" ["ROOT"] ["TApplication.h"] , modImports "TArray" ["ROOT"] ["TArray.h"] , modImports "TArrayC" ["ROOT"] ["TArrayC.h"] , modImports "TArrayD" ["ROOT"] ["TArrayD.h"] , modImports "TArrayF" ["ROOT"] ["TArrayF.h"] , modImports "TArrayI" ["ROOT"] ["TArrayI.h"] , modImports "TArrayL" ["ROOT"] ["TArrayL.h"] , modImports "TArrayL64" ["ROOT"] ["TArrayL64.h"] , modImports "TArrayS" ["ROOT"] ["TArrayS.h"] , modImports "TAtt3D" ["ROOT"] ["TAtt3D.h"] , modImports "TAttAxis" ["ROOT"] ["TAttAxis.h"] , modImports "TAttBBox" ["ROOT"] ["TAttBBox.h"] , modImports "TAttBBox2D" ["ROOT"] ["TAttBBox2D.h"] , modImports "TAttCanvas" ["ROOT"] ["TAttCanvas.h"] , modImports "TAttFill" ["ROOT"] ["TAttFill.h"] , modImports "TAttLine" ["ROOT"] ["TAttLine.h"] , modImports "TAttMarker" ["ROOT"] ["TAttMarker.h"] , modImports "TAttPad" ["ROOT"] ["TAttPad.h"] , modImports "TAttText" ["ROOT"] ["TAttText.h"] , modImports "TClass" ["ROOT"] ["TClass.h"] , modImports "TCollection" ["ROOT"] ["TCollection.h"] , modImports "TColor" ["ROOT"] ["TColor.h"] , modImports "TDatime" ["ROOT"] ["TDatime.h"] , modImports "TDictionary" ["ROOT"] ["TDictionary.h"] , modImports "TDirectory" ["ROOT"] ["TDirectory.h"] , modImports "TGlobal" ["ROOT"] ["TGlobal.h"] , modImports "TKey" ["ROOT"] ["TKey.h"] , modImports "TMutex" ["ROOT"] ["TMutex.h"] , modImports "TNamed" ["ROOT"] ["TNamed.h"] , modImports "TObjArray" ["ROOT"] ["TObjArray.h"] , modImports "TObject" ["ROOT"] ["TObject.h"] , modImports "TQObject" ["ROOT"] ["TQObject.h"] , modImports "TROOT" ["ROOT"] ["TROOT.h"] , modImports "TSeqCollection" ["ROOT"] ["TSeqCollection.h"] , modImports "TStyle" ["ROOT"] ["TStyle.h"] , modImports "TSystem" ["ROOT"] ["TSystem.h"] , modImports "TVirtualMutex" ["ROOT"] ["TVirtualMutex.h"] , modImports "TVirtualPad" ["ROOT"] ["TVirtualPad.h"] ] core_extraLib :: [String] core_extraLib = [] core_extraDep :: [(String,[String])] core_extraDep = []
wavewave/HROOT-generate
HROOT-generate/lib/HROOT/Data/Core/Class.hs
gpl-3.0
22,189
0
12
5,651
5,950
3,240
2,710
493
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Main ( main ) where import Web.Scotty(scotty,get,setHeader,text) import Network.Info(getNetworkInterfaces,NetworkInterface(..)) import Control.Monad.IO.Class(liftIO) import Data.String(fromString) -- import System.Win32.Console.Console import System.IO.Silently import System.IO import Distribution.Version import Distribution.PackageDescription.TH as P myVersion :: Version myVersion = read $(packageVariable (pkgVersion . package)) replace :: String -> String replace [] = [] replace ('.':xs) = ' ':replace xs replace (x:xs) = x:replace xs getIp :: [[String]] -> Maybe String getIp [] = Nothing getIp (x:xs) = if (head.head) x== '2' then Just $ tail $ concatMap ("."++) x else getIp xs main :: IO () main = do --putStrLn myVersion putStrLn "GetIp server begin"{- freeConsole ma ma :: Bool -> IO() ma x = do let xx = show x writeFile "a" xx putStrLn "asd" writeFile "aa" "aa" scotty 7999 $ get "/" $ do setHeader "Content-Type" "application/json; charset=utf-8" netinfo <- liftIO getNetworkInterfaces let rt = getIp $ map (words.replace.show.ipv4) netinfo case rt of Nothing -> do liftIO $ putStrLn "CANNOT GET IPV$4" text "{\"status\":\"failed\",\"reason\":\"CANNOT GET IPV4\"}" Just x -> do liftIO $ putStrLn x text $ fromString $ "{\"status\":\"success\",\"ipv4\":\""++x++"\"}" return () -}
Qinka/GetIp
Main.hs
bsd-3-clause
1,791
0
10
606
292
165
127
25
2
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} ----------------------------------------------------------------------------- -- | -- Module : -- Copyright : -- License : -- -- Maintainer : -- Stability : experimental -- -- Emulate all hadoop operations locally ---------------------------------------------------------------------------- module Hadron.Run.Local where ------------------------------------------------------------------------------- import Control.Applicative import Control.Error import Control.Lens import Control.Monad.Reader import Control.Monad.Trans.Resource import qualified Data.ByteString.Char8 as B import Data.Conduit import Data.Conduit.Binary (sourceFile) import Data.Default import Data.Hashable import Data.List import Data.Monoid import System.Directory import System.Environment import System.Exit import System.FilePath.Glob import System.FilePath.Lens import System.FilePath.Posix import System.IO import System.Process ------------------------------------------------------------------------------- import Hadron.Logger import Hadron.Run.FanOut import qualified Hadron.Run.Hadoop as H import Hadron.Utils ------------------------------------------------------------------------------- #if MIN_VERSION_base(4, 7, 0) #else import System.Posix.Env #endif newtype LocalFile = LocalFile { _unLocalFile :: FilePath } deriving (Eq,Show,Read,Ord) makeLenses ''LocalFile data LocalRunSettings = LocalRunSettings { _lrsTempPath :: FilePath -- ^ Root of the "file system" during a localrun } makeLenses ''LocalRunSettings instance Default LocalRunSettings where def = LocalRunSettings "tmp" type Local = ReaderT LocalRunSettings IO runLocal :: r -> ReaderT r m a -> m a runLocal env f = runReaderT f env ------------------------------------------------------------------------------- path :: (MonadIO m, MonadReader LocalRunSettings m) => LocalFile -> m FilePath path (LocalFile fp) = do root <- view lrsTempPath let p = root </> fp dir = p ^. directory liftIO $ createDirectoryIfMissing True dir return p ------------------------------------------------------------------------------- getRecursiveDirectoryContents :: FilePath -> IO [FilePath] getRecursiveDirectoryContents dir0 = go dir0 where go dir = do fs <- liftM (map (dir </>) . filter (not . flip elem [".", ".."])) $ getDirectoryContents' dir fs' <- filterM (fmap not . doesDirectoryExist) fs fss <- mapM go fs return $ fs' ++ concat fss ------------------------------------------------------------------------------- -- | A version that return [] instead of an error when directory does not exit. getDirectoryContents' :: FilePath -> IO [FilePath] getDirectoryContents' fp = do chk <- doesDirectoryExist fp case chk of False -> return [] True -> getDirectoryContents fp ------------------------------------------------------------------------------- -- | Recursive contents if given a directory, assumed glob pattern if not. getInputFiles :: FilePath -> IO [FilePath] getInputFiles fp = do chk <- doesDirectoryExist fp case chk of True -> glob (fp </> "**") False -> glob fp ------------------------------------------------------------------------------- localMapReduce :: MonadIO m => LocalRunSettings -> String -- ^ MapReduceKey -> String -- ^ RunToken -> H.HadoopRunOpts -> EitherT String m () localMapReduce lrs mrKey token H.HadoopRunOpts{..} = do exPath <- scriptIO getExecutablePath echoInfo $ "Launching Hadoop job for MR key: " <> ls mrKey expandedInput <- liftIO $ liftM concat $ forM _mrsInput $ \ inp -> withLocalFile lrs (LocalFile inp) getInputFiles let enableCompress = case _mrsCompress of Nothing -> False Just x -> isInfixOf "Gzip" x -- Are the input files already compressed? inputCompressed file = isInfixOf ".gz" file outFile <- liftIO $ withLocalFile lrs (LocalFile _mrsOutput) $ \ fp -> case fp ^. extension . to null of False -> return fp True -> do createDirectoryIfMissing True fp return $ fp </> ("0000.out" ++ if enableCompress then ".gz" else "") let pipe = " | " maybeCompress = if enableCompress then pipe <> "gzip" else "" maybeGunzip fp = (if inputCompressed fp then ("gunzip" <> pipe) else "") maybeReducer = case _mrsNumReduce of Just 0 -> "" _ -> pipe <> exPath <> " " <> token <> " " <> "reducer_" <> mrKey -- map over each file individually and write results into a temp file mapFile infile = clearExit . scriptIO . withTmpMapFile infile $ \ fp -> do echoInfo ("Running command: " <> ls (command fp)) #if MIN_VERSION_base(4, 7, 0) setEnv "mapreduce_map_input_file" infile #else setEnv "mapreduce_map_input_file" infile True #endif system (command fp) where command fp = "cat " <> infile <> pipe <> maybeGunzip infile <> exPath <> " " <> token <> " " <> "mapper_" <> mrKey <> " > " <> fp -- a unique temp file for each input file withTmpMapFile infile f = liftIO $ withLocalFile lrs (LocalFile ((show (hash infile)) <> "_mapout")) f getTempMapFiles = mapM (flip withTmpMapFile return) expandedInput -- concat all processed map output, sort and run through the reducer reduceFiles = do fs <- getTempMapFiles echoInfo ("Running command: " <> ls (command fs)) scriptIO $ createDirectoryIfMissing True (outFile ^. directory) clearExit $ scriptIO $ system (command fs) where command fs = "cat " <> intercalate " " fs <> pipe <> ("sort -t$'\t' -k1," <> show (H.numSegs _mrsPart)) <> maybeReducer <> maybeCompress <> " > " <> outFile removeTempFiles = scriptIO $ do fs <- getTempMapFiles mapM_ removeFile fs echoInfo "Mapping over individual local input files." mapM_ mapFile expandedInput echoInfo "Executing reduce stage." reduceFiles removeTempFiles ------------------------------------------------------------------------------- echo :: (Applicative m, MonadIO m) => Severity -> LogStr -> m () echo sev msg = runLog $ logMsg "Local" sev msg ------------------------------------------------------------------------------- echoInfo :: (Applicative m, MonadIO m) => LogStr -> m () echoInfo = echo InfoS ------------------------------------------------------------------------------- -- | Fail if command not successful. clearExit :: MonadIO m => EitherT String m ExitCode -> EitherT [Char] m () clearExit f = do res <- f case res of ExitSuccess -> echoInfo "Command successful." e -> do echo ErrorS $ ls $ "Command failed: " ++ show e hoistEither $ Left $ "Command failed with: " ++ show e ------------------------------------------------------------------------------- -- | Check if the target file is present. hdfsFileExists :: (MonadIO m, MonadReader LocalRunSettings m) => LocalFile -> m Bool hdfsFileExists p = liftIO . chk =<< path p where chk fp = (||) <$> doesFileExist fp <*> doesDirectoryExist fp ------------------------------------------------------------------------------- hdfsDeletePath :: (MonadIO m, MonadReader LocalRunSettings m) => LocalFile -> m () hdfsDeletePath p = do fp <- path p liftIO $ do chk <- doesDirectoryExist fp when chk (removeDirectoryRecursive fp) chk2 <- doesFileExist fp when chk2 (removeFile fp) ------------------------------------------------------------------------------- hdfsLs :: (MonadIO m, MonadReader LocalRunSettings m) => LocalFile -> m [File] hdfsLs p = do fs <- liftIO . getDirectoryContents' =<< path p return $ map (File "" 1 "" "") $ map (_unLocalFile p </>) fs ------------------------------------------------------------------------------- hdfsPut :: (MonadIO m, MonadReader LocalRunSettings m) => LocalFile -> LocalFile -> m () hdfsPut src dest = do src' <- path src dest' <- path dest liftIO $ copyFile src' dest' ------------------------------------------------------------------------------- -- | Create a new multiple output file manager. hdfsFanOut :: (MonadIO m, MonadReader LocalRunSettings m) => FilePath -- ^ Temporary file location. -> m FanOut hdfsFanOut tmp = do env <- ask liftIO $ mkFanOut (mkHandle env) where mkTmp fp = tmp </> fp -- write into a temp file loc until we know the stage is -- complete without failure mkHandle env fp = do fp' <- runLocal env $ path (LocalFile (mkTmp fp)) createDirectoryIfMissing True (fp' ^. directory) h <- openFile fp' AppendMode return (h, fin env fp) -- move temp file to its final destination fin env fp0 = do temp <- runLocal env $ path (LocalFile (mkTmp fp0)) dest <- runLocal env $ path (LocalFile fp0) createDirectoryIfMissing True (dest ^. directory) renameFile temp dest ------------------------------------------------------------------------------- hdfsMkdir :: (MonadIO m, MonadReader LocalRunSettings m) => LocalFile -> m () hdfsMkdir p = liftIO . createDirectoryIfMissing True =<< path p ------------------------------------------------------------------------------- hdfsCat :: LocalFile -> Producer (ResourceT Local) B.ByteString hdfsCat p = sourceFile =<< (lift . lift) (path p) ------------------------------------------------------------------------------- hdfsGet :: (MonadIO m, MonadReader LocalRunSettings m) => LocalFile -> m LocalFile hdfsGet fp = do target <- randomFileName hdfsPut fp target return target hdfsLocalStream :: LocalFile -> Producer (ResourceT Local) B.ByteString hdfsLocalStream = hdfsCat ------------------------------------------------------------------------------- randomFileName :: MonadIO m => m LocalFile randomFileName = LocalFile `liftM` liftIO (randomToken 64) ------------------------------------------------------------------------------- -- | Helper to work with relative paths using Haskell functions like -- 'readFile' and 'writeFile'. withLocalFile :: MonadIO m => LocalRunSettings -> LocalFile -- ^ A relative path in our working folder -> (FilePath -> m b) -- ^ What to do with the absolute path. -> m b withLocalFile settings fp f = f =<< runLocal settings (path fp)
juanpaucar/hadron
src/Hadron/Run/Local.hs
bsd-3-clause
11,452
0
22
2,894
2,525
1,270
1,255
-1
-1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 Monadic type operations This module contains monadic operations over types that contain mutable type variables -} {-# LANGUAGE CPP #-} module TcMType ( TcTyVar, TcKind, TcType, TcTauType, TcThetaType, TcTyVarSet, -------------------------------- -- Creating new mutable type variables newFlexiTyVar, newFlexiTyVarTy, -- Kind -> TcM TcType newFlexiTyVarTys, -- Int -> Kind -> TcM [TcType] newReturnTyVar, newReturnTyVarTy, newMetaKindVar, newMetaKindVars, mkTcTyVarName, cloneMetaTyVar, newMetaTyVar, readMetaTyVar, writeMetaTyVar, writeMetaTyVarRef, newMetaDetails, isFilledMetaTyVar, isUnfilledMetaTyVar, -------------------------------- -- Creating new evidence variables newEvVar, newEvVars, newEq, newDict, newTcEvBinds, addTcEvBind, -------------------------------- -- Instantiation tcInstTyVars, tcInstTyVarX, newSigTyVar, tcInstType, tcInstSkolTyVars, tcInstSuperSkolTyVarsX, tcInstSigTyVarsLoc, tcInstSigTyVars, tcInstSkolType, tcSkolDFunType, tcSuperSkolTyVars, instSkolTyVars, freshenTyVarBndrs, -------------------------------- -- Zonking and tidying zonkTcPredType, zonkTidyTcType, zonkTidyOrigin, tidyEvVar, tidyCt, tidySkolemInfo, skolemiseUnboundMetaTyVar, zonkTcTyVar, zonkTcTyVars, zonkTyVarsAndFV, zonkTcTypeAndFV, zonkQuantifiedTyVar, quantifyTyVars, zonkTcTyVarBndr, zonkTcType, zonkTcTypes, zonkTcThetaType, zonkTcKind, defaultKindVarToStar, zonkEvVar, zonkWC, zonkSimples, zonkId, zonkCt, zonkSkolemInfo, tcGetGlobalTyVars ) where #include "HsVersions.h" -- friends: import TypeRep import TcType import Type import Class import Var import VarEnv -- others: import TcRnMonad -- TcType, amongst others import Id import Name import VarSet import PrelNames import DynFlags import Util import Outputable import FastString import SrcLoc import Bag import Control.Monad import Data.List ( partition, mapAccumL ) {- ************************************************************************ * * Kind variables * * ************************************************************************ -} mkKindName :: Unique -> Name mkKindName unique = mkSystemName unique kind_var_occ kind_var_occ :: OccName -- Just one for all MetaKindVars -- They may be jiggled by tidying kind_var_occ = mkOccName tvName "k" newMetaKindVar :: TcM TcKind newMetaKindVar = do { uniq <- newUnique ; details <- newMetaDetails TauTv ; let kv = mkTcTyVar (mkKindName uniq) superKind details ; return (mkTyVarTy kv) } newMetaKindVars :: Int -> TcM [TcKind] newMetaKindVars n = mapM (\ _ -> newMetaKindVar) (nOfThem n ()) {- ************************************************************************ * * Evidence variables; range over constraints we can abstract over * * ************************************************************************ -} newEvVars :: TcThetaType -> TcM [EvVar] newEvVars theta = mapM newEvVar theta -------------- newEvVar :: TcPredType -> TcM EvVar -- Creates new *rigid* variables for predicates newEvVar ty = do { name <- newSysName (predTypeOccName ty) ; return (mkLocalId name ty) } newEq :: TcType -> TcType -> TcM EvVar newEq ty1 ty2 = do { name <- newSysName (mkVarOccFS (fsLit "cobox")) ; return (mkLocalId name (mkTcEqPred ty1 ty2)) } newDict :: Class -> [TcType] -> TcM DictId newDict cls tys = do { name <- newSysName (mkDictOcc (getOccName cls)) ; return (mkLocalId name (mkClassPred cls tys)) } predTypeOccName :: PredType -> OccName predTypeOccName ty = case classifyPredType ty of ClassPred cls _ -> mkDictOcc (getOccName cls) EqPred _ _ _ -> mkVarOccFS (fsLit "cobox") IrredPred _ -> mkVarOccFS (fsLit "irred") {- ************************************************************************ * * SkolemTvs (immutable) * * ************************************************************************ -} tcInstType :: ([TyVar] -> TcM (TvSubst, [TcTyVar])) -- How to instantiate the type variables -> TcType -- Type to instantiate -> TcM ([TcTyVar], TcThetaType, TcType) -- Result -- (type vars (excl coercion vars), preds (incl equalities), rho) tcInstType inst_tyvars ty = case tcSplitForAllTys ty of ([], rho) -> let -- There may be overloading despite no type variables; -- (?x :: Int) => Int -> Int (theta, tau) = tcSplitPhiTy rho in return ([], theta, tau) (tyvars, rho) -> do { (subst, tyvars') <- inst_tyvars tyvars ; let (theta, tau) = tcSplitPhiTy (substTy subst rho) ; return (tyvars', theta, tau) } tcSkolDFunType :: Type -> TcM ([TcTyVar], TcThetaType, TcType) -- Instantiate a type signature with skolem constants. -- We could give them fresh names, but no need to do so tcSkolDFunType ty = tcInstType tcInstSuperSkolTyVars ty tcSuperSkolTyVars :: [TyVar] -> (TvSubst, [TcTyVar]) -- Make skolem constants, but do *not* give them new names, as above -- Moreover, make them "super skolems"; see comments with superSkolemTv -- see Note [Kind substitution when instantiating] -- Precondition: tyvars should be ordered (kind vars first) tcSuperSkolTyVars = mapAccumL tcSuperSkolTyVar (mkTopTvSubst []) tcSuperSkolTyVar :: TvSubst -> TyVar -> (TvSubst, TcTyVar) tcSuperSkolTyVar subst tv = (extendTvSubst subst tv (mkTyVarTy new_tv), new_tv) where kind = substTy subst (tyVarKind tv) new_tv = mkTcTyVar (tyVarName tv) kind superSkolemTv tcInstSkolTyVars :: [TyVar] -> TcM (TvSubst, [TcTyVar]) tcInstSkolTyVars = tcInstSkolTyVars' False emptyTvSubst tcInstSuperSkolTyVars :: [TyVar] -> TcM (TvSubst, [TcTyVar]) tcInstSuperSkolTyVars = tcInstSuperSkolTyVarsX emptyTvSubst tcInstSuperSkolTyVarsX :: TvSubst -> [TyVar] -> TcM (TvSubst, [TcTyVar]) tcInstSuperSkolTyVarsX subst = tcInstSkolTyVars' True subst tcInstSkolTyVars' :: Bool -> TvSubst -> [TyVar] -> TcM (TvSubst, [TcTyVar]) -- Precondition: tyvars should be ordered (kind vars first) -- see Note [Kind substitution when instantiating] -- Get the location from the monad; this is a complete freshening operation tcInstSkolTyVars' overlappable subst tvs = do { loc <- getSrcSpanM ; instSkolTyVarsX (mkTcSkolTyVar loc overlappable) subst tvs } mkTcSkolTyVar :: SrcSpan -> Bool -> Unique -> Name -> Kind -> TcTyVar mkTcSkolTyVar loc overlappable uniq old_name kind = mkTcTyVar (mkInternalName uniq (getOccName old_name) loc) kind (SkolemTv overlappable) tcInstSigTyVarsLoc :: SrcSpan -> [TyVar] -> TcRnIf gbl lcl (TvSubst, [TcTyVar]) -- We specify the location tcInstSigTyVarsLoc loc = instSkolTyVars (mkTcSkolTyVar loc False) tcInstSigTyVars :: [TyVar] -> TcRnIf gbl lcl (TvSubst, [TcTyVar]) -- Get the location from the TyVar itself, not the monad tcInstSigTyVars = instSkolTyVars mk_tv where mk_tv uniq old_name kind = mkTcTyVar (setNameUnique old_name uniq) kind (SkolemTv False) tcInstSkolType :: TcType -> TcM ([TcTyVar], TcThetaType, TcType) -- Instantiate a type with fresh skolem constants -- Binding location comes from the monad tcInstSkolType ty = tcInstType tcInstSkolTyVars ty ------------------ freshenTyVarBndrs :: [TyVar] -> TcRnIf gbl lcl (TvSubst, [TyVar]) -- ^ Give fresh uniques to a bunch of TyVars, but they stay -- as TyVars, rather than becoming TcTyVars -- Used in FamInst.newFamInst, and Inst.newClsInst freshenTyVarBndrs = instSkolTyVars mk_tv where mk_tv uniq old_name kind = mkTyVar (setNameUnique old_name uniq) kind ------------------ instSkolTyVars :: (Unique -> Name -> Kind -> TyVar) -> [TyVar] -> TcRnIf gbl lcl (TvSubst, [TyVar]) instSkolTyVars mk_tv = instSkolTyVarsX mk_tv emptyTvSubst instSkolTyVarsX :: (Unique -> Name -> Kind -> TyVar) -> TvSubst -> [TyVar] -> TcRnIf gbl lcl (TvSubst, [TyVar]) instSkolTyVarsX mk_tv = mapAccumLM (instSkolTyVarX mk_tv) instSkolTyVarX :: (Unique -> Name -> Kind -> TyVar) -> TvSubst -> TyVar -> TcRnIf gbl lcl (TvSubst, TyVar) instSkolTyVarX mk_tv subst tyvar = do { uniq <- newUnique ; let new_tv = mk_tv uniq old_name kind ; return (extendTvSubst subst tyvar (mkTyVarTy new_tv), new_tv) } where old_name = tyVarName tyvar kind = substTy subst (tyVarKind tyvar) {- Note [Kind substitution when instantiating] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we instantiate a bunch of kind and type variables, first we expect them to be sorted (kind variables first, then type variables). Then we have to instantiate the kind variables, build a substitution from old variables to the new variables, then instantiate the type variables substituting the original kind. Exemple: If we want to instantiate [(k1 :: BOX), (k2 :: BOX), (a :: k1 -> k2), (b :: k1)] we want [(?k1 :: BOX), (?k2 :: BOX), (?a :: ?k1 -> ?k2), (?b :: ?k1)] instead of the buggous [(?k1 :: BOX), (?k2 :: BOX), (?a :: k1 -> k2), (?b :: k1)] ************************************************************************ * * MetaTvs (meta type variables; mutable) * * ************************************************************************ -} newMetaTyVar :: MetaInfo -> Kind -> TcM TcTyVar -- Make a new meta tyvar out of thin air newMetaTyVar meta_info kind = do { uniq <- newUnique ; let name = mkTcTyVarName uniq s s = case meta_info of ReturnTv -> fsLit "r" TauTv -> fsLit "t" FlatMetaTv -> fsLit "fmv" SigTv -> fsLit "a" ; details <- newMetaDetails meta_info ; return (mkTcTyVar name kind details) } newSigTyVar :: Name -> Kind -> TcM TcTyVar newSigTyVar name kind = do { uniq <- newUnique ; let name' = setNameUnique name uniq -- Use the same OccName so that the tidy-er -- doesn't gratuitously rename 'a' to 'a0' etc ; details <- newMetaDetails SigTv ; return (mkTcTyVar name' kind details) } newMetaDetails :: MetaInfo -> TcM TcTyVarDetails newMetaDetails info = do { ref <- newMutVar Flexi ; tclvl <- getTcLevel ; return (MetaTv { mtv_info = info, mtv_ref = ref, mtv_tclvl = tclvl }) } cloneMetaTyVar :: TcTyVar -> TcM TcTyVar cloneMetaTyVar tv = ASSERT( isTcTyVar tv ) do { uniq <- newUnique ; ref <- newMutVar Flexi ; let name' = setNameUnique (tyVarName tv) uniq details' = case tcTyVarDetails tv of details@(MetaTv {}) -> details { mtv_ref = ref } _ -> pprPanic "cloneMetaTyVar" (ppr tv) ; return (mkTcTyVar name' (tyVarKind tv) details') } mkTcTyVarName :: Unique -> FastString -> Name mkTcTyVarName uniq str = mkSysTvName uniq str -- Works for both type and kind variables readMetaTyVar :: TyVar -> TcM MetaDetails readMetaTyVar tyvar = ASSERT2( isMetaTyVar tyvar, ppr tyvar ) readMutVar (metaTvRef tyvar) isFilledMetaTyVar :: TyVar -> TcM Bool -- True of a filled-in (Indirect) meta type variable isFilledMetaTyVar tv | not (isTcTyVar tv) = return False | MetaTv { mtv_ref = ref } <- tcTyVarDetails tv = do { details <- readMutVar ref ; return (isIndirect details) } | otherwise = return False isUnfilledMetaTyVar :: TyVar -> TcM Bool -- True of a un-filled-in (Flexi) meta type variable isUnfilledMetaTyVar tv | not (isTcTyVar tv) = return False | MetaTv { mtv_ref = ref } <- tcTyVarDetails tv = do { details <- readMutVar ref ; return (isFlexi details) } | otherwise = return False -------------------- -- Works with both type and kind variables writeMetaTyVar :: TcTyVar -> TcType -> TcM () -- Write into a currently-empty MetaTyVar writeMetaTyVar tyvar ty | not debugIsOn = writeMetaTyVarRef tyvar (metaTvRef tyvar) ty -- Everything from here on only happens if DEBUG is on | not (isTcTyVar tyvar) = WARN( True, text "Writing to non-tc tyvar" <+> ppr tyvar ) return () | MetaTv { mtv_ref = ref } <- tcTyVarDetails tyvar = writeMetaTyVarRef tyvar ref ty | otherwise = WARN( True, text "Writing to non-meta tyvar" <+> ppr tyvar ) return () -------------------- writeMetaTyVarRef :: TcTyVar -> TcRef MetaDetails -> TcType -> TcM () -- Here the tyvar is for error checking only; -- the ref cell must be for the same tyvar writeMetaTyVarRef tyvar ref ty | not debugIsOn = do { traceTc "writeMetaTyVar" (ppr tyvar <+> text ":=" <+> ppr ty) ; writeMutVar ref (Indirect ty) } -- Everything from here on only happens if DEBUG is on | otherwise = do { meta_details <- readMutVar ref; -- Zonk kinds to allow the error check to work ; zonked_tv_kind <- zonkTcKind tv_kind ; zonked_ty_kind <- zonkTcKind ty_kind -- Check for double updates ; ASSERT2( isFlexi meta_details, hang (text "Double update of meta tyvar") 2 (ppr tyvar $$ ppr meta_details) ) traceTc "writeMetaTyVar" (ppr tyvar <+> text ":=" <+> ppr ty) ; writeMutVar ref (Indirect ty) ; when ( not (isPredTy tv_kind) -- Don't check kinds for updates to coercion variables && not (zonked_ty_kind `tcIsSubKind` zonked_tv_kind)) $ WARN( True, hang (text "Ill-kinded update to meta tyvar") 2 ( ppr tyvar <+> text "::" <+> (ppr tv_kind $$ ppr zonked_tv_kind) <+> text ":=" <+> ppr ty <+> text "::" <+> (ppr ty_kind $$ ppr zonked_ty_kind) ) ) (return ()) } where tv_kind = tyVarKind tyvar ty_kind = typeKind ty {- ************************************************************************ * * MetaTvs: TauTvs * * ************************************************************************ -} newFlexiTyVar :: Kind -> TcM TcTyVar newFlexiTyVar kind = newMetaTyVar TauTv kind newFlexiTyVarTy :: Kind -> TcM TcType newFlexiTyVarTy kind = do tc_tyvar <- newFlexiTyVar kind return (TyVarTy tc_tyvar) newFlexiTyVarTys :: Int -> Kind -> TcM [TcType] newFlexiTyVarTys n kind = mapM newFlexiTyVarTy (nOfThem n kind) newReturnTyVar :: Kind -> TcM TcTyVar newReturnTyVar kind = newMetaTyVar ReturnTv kind newReturnTyVarTy :: Kind -> TcM TcType newReturnTyVarTy kind = TyVarTy <$> newReturnTyVar kind tcInstTyVars :: [TKVar] -> TcM (TvSubst, [TcTyVar]) -- Instantiate with META type variables -- Note that this works for a sequence of kind and type -- variables. Eg [ (k:BOX), (a:k->k) ] -- Gives [ (k7:BOX), (a8:k7->k7) ] tcInstTyVars tyvars = mapAccumLM tcInstTyVarX emptyTvSubst tyvars -- emptyTvSubst has an empty in-scope set, but that's fine here -- Since the tyvars are freshly made, they cannot possibly be -- captured by any existing for-alls. tcInstTyVarX :: TvSubst -> TKVar -> TcM (TvSubst, TcTyVar) -- Make a new unification variable tyvar whose Name and Kind come from -- an existing TyVar. We substitute kind variables in the kind. tcInstTyVarX subst tyvar = do { uniq <- newUnique ; details <- newMetaDetails TauTv ; let name = mkSystemName uniq (getOccName tyvar) -- See Note [Name of an instantiated type variable] kind = substTy subst (tyVarKind tyvar) new_tv = mkTcTyVar name kind details ; return (extendTvSubst subst tyvar (mkTyVarTy new_tv), new_tv) } {- Note [Name of an instantiated type variable] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ At the moment we give a unification variable a System Name, which influences the way it is tidied; see TypeRep.tidyTyVarBndr. ************************************************************************ * * Quantification * * ************************************************************************ Note [quantifyTyVars] ~~~~~~~~~~~~~~~~~~~~~ quantifyTyVars is give the free vars of a type that we are about to wrap in a forall. It takes these free type/kind variables and 1. Zonks them and remove globals 2. Partitions into type and kind variables (kvs1, tvs) 3. Extends kvs1 with free kind vars in the kinds of tvs (removing globals) 4. Calls zonkQuantifiedTyVar on each Step (3) is often unimportant, because the kind variable is often also free in the type. Eg Typeable k (a::k) has free vars {k,a}. But the type (see Trac #7916) (f::k->*) (a::k) has free vars {f,a}, but we must add 'k' as well! Hence step (3). -} quantifyTyVars :: TcTyVarSet -> TcTyVarSet -> TcM [TcTyVar] -- See Note [quantifyTyVars] -- The input is a mixture of type and kind variables; a kind variable k -- may occur *after* a tyvar mentioning k in its kind -- Can be given a mixture of TcTyVars and TyVars, in the case of -- associated type declarations quantifyTyVars gbl_tvs tkvs = do { tkvs <- zonkTyVarsAndFV tkvs ; gbl_tvs <- zonkTyVarsAndFV gbl_tvs ; let (kvs, tvs) = partitionVarSet isKindVar (closeOverKinds tkvs `minusVarSet` gbl_tvs) -- NB kinds of tvs are zonked by zonkTyVarsAndFV kvs2 = varSetElems kvs qtvs = varSetElems tvs -- In the non-PolyKinds case, default the kind variables -- to *, and zonk the tyvars as usual. Notice that this -- may make quantifyTyVars return a shorter list -- than it was passed, but that's ok ; poly_kinds <- xoptM Opt_PolyKinds ; qkvs <- if poly_kinds then return kvs2 else do { let (meta_kvs, skolem_kvs) = partition is_meta kvs2 is_meta kv = isTcTyVar kv && isMetaTyVar kv ; mapM_ defaultKindVarToStar meta_kvs ; return skolem_kvs } -- should be empty ; mapM zonk_quant (qkvs ++ qtvs) } -- Because of the order, any kind variables -- mentioned in the kinds of the type variables refer to -- the now-quantified versions where zonk_quant tkv | isTcTyVar tkv = zonkQuantifiedTyVar tkv | otherwise = return tkv -- For associated types, we have the class variables -- in scope, and they are TyVars not TcTyVars zonkQuantifiedTyVar :: TcTyVar -> TcM TcTyVar -- The quantified type variables often include meta type variables -- we want to freeze them into ordinary type variables, and -- default their kind (e.g. from OpenTypeKind to TypeKind) -- -- see notes with Kind.defaultKind -- The meta tyvar is updated to point to the new skolem TyVar. Now any -- bound occurrences of the original type variable will get zonked to -- the immutable version. -- -- We leave skolem TyVars alone; they are immutable. -- -- This function is called on both kind and type variables, -- but kind variables *only* if PolyKinds is on. zonkQuantifiedTyVar tv = ASSERT2( isTcTyVar tv, ppr tv ) case tcTyVarDetails tv of SkolemTv {} -> do { kind <- zonkTcKind (tyVarKind tv) ; return $ setTyVarKind tv kind } -- It might be a skolem type variable, -- for example from a user type signature MetaTv { mtv_ref = ref } -> do when debugIsOn $ do -- [Sept 04] Check for non-empty. -- See note [Silly Type Synonym] cts <- readMutVar ref case cts of Flexi -> return () Indirect ty -> WARN( True, ppr tv $$ ppr ty ) return () skolemiseUnboundMetaTyVar tv vanillaSkolemTv _other -> pprPanic "zonkQuantifiedTyVar" (ppr tv) -- FlatSkol, RuntimeUnk defaultKindVarToStar :: TcTyVar -> TcM Kind -- We have a meta-kind: unify it with '*' defaultKindVarToStar kv = do { ASSERT( isKindVar kv && isMetaTyVar kv ) writeMetaTyVar kv liftedTypeKind ; return liftedTypeKind } skolemiseUnboundMetaTyVar :: TcTyVar -> TcTyVarDetails -> TcM TyVar -- We have a Meta tyvar with a ref-cell inside it -- Skolemise it, including giving it a new Name, so that -- we are totally out of Meta-tyvar-land -- We create a skolem TyVar, not a regular TyVar -- See Note [Zonking to Skolem] skolemiseUnboundMetaTyVar tv details = ASSERT2( isMetaTyVar tv, ppr tv ) do { span <- getSrcSpanM -- Get the location from "here" -- ie where we are generalising ; uniq <- newUnique -- Remove it from TcMetaTyVar unique land ; kind <- zonkTcKind (tyVarKind tv) ; let tv_name = getOccName tv final_name = mkInternalName uniq tv_name span final_kind = defaultKind kind final_tv = mkTcTyVar final_name final_kind details ; traceTc "Skolemising" (ppr tv <+> ptext (sLit ":=") <+> ppr final_tv) ; writeMetaTyVar tv (mkTyVarTy final_tv) ; return final_tv } {- Note [Zonking to Skolem] ~~~~~~~~~~~~~~~~~~~~~~~~ We used to zonk quantified type variables to regular TyVars. However, this leads to problems. Consider this program from the regression test suite: eval :: Int -> String -> String -> String eval 0 root actual = evalRHS 0 root actual evalRHS :: Int -> a evalRHS 0 root actual = eval 0 root actual It leads to the deferral of an equality (wrapped in an implication constraint) forall a. () => ((String -> String -> String) ~ a) which is propagated up to the toplevel (see TcSimplify.tcSimplifyInferCheck). In the meantime `a' is zonked and quantified to form `evalRHS's signature. This has the *side effect* of also zonking the `a' in the deferred equality (which at this point is being handed around wrapped in an implication constraint). Finally, the equality (with the zonked `a') will be handed back to the simplifier by TcRnDriver.tcRnSrcDecls calling TcSimplify.tcSimplifyTop. If we zonk `a' with a regular type variable, we will have this regular type variable now floating around in the simplifier, which in many places assumes to only see proper TcTyVars. We can avoid this problem by zonking with a skolem. The skolem is rigid (which we require for a quantified variable), but is still a TcTyVar that the simplifier knows how to deal with. Note [Silly Type Synonyms] ~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this: type C u a = u -- Note 'a' unused foo :: (forall a. C u a -> C u a) -> u foo x = ... bar :: Num u => u bar = foo (\t -> t + t) * From the (\t -> t+t) we get type {Num d} => d -> d where d is fresh. * Now unify with type of foo's arg, and we get: {Num (C d a)} => C d a -> C d a where a is fresh. * Now abstract over the 'a', but float out the Num (C d a) constraint because it does not 'really' mention a. (see exactTyVarsOfType) The arg to foo becomes \/\a -> \t -> t+t * So we get a dict binding for Num (C d a), which is zonked to give a = () [Note Sept 04: now that we are zonking quantified type variables on construction, the 'a' will be frozen as a regular tyvar on quantification, so the floated dict will still have type (C d a). Which renders this whole note moot; happily!] * Then the \/\a abstraction has a zonked 'a' in it. All very silly. I think its harmless to ignore the problem. We'll end up with a \/\a in the final result but all the occurrences of a will be zonked to () ************************************************************************ * * Zonking types * * ************************************************************************ @tcGetGlobalTyVars@ returns a fully-zonked set of tyvars free in the environment. To improve subsequent calls to the same function it writes the zonked set back into the environment. -} tcGetGlobalTyVars :: TcM TcTyVarSet tcGetGlobalTyVars = do { (TcLclEnv {tcl_tyvars = gtv_var}) <- getLclEnv ; gbl_tvs <- readMutVar gtv_var ; gbl_tvs' <- zonkTyVarsAndFV gbl_tvs ; writeMutVar gtv_var gbl_tvs' ; return gbl_tvs' } where zonkTcTypeAndFV :: TcType -> TcM TyVarSet -- Zonk a type and take its free variables -- With kind polymorphism it can be essential to zonk *first* -- so that we find the right set of free variables. Eg -- forall k1. forall (a:k2). a -- where k2:=k1 is in the substitution. We don't want -- k2 to look free in this type! zonkTcTypeAndFV ty = do { ty <- zonkTcType ty; return (tyVarsOfType ty) } zonkTyVar :: TyVar -> TcM TcType -- Works on TyVars and TcTyVars zonkTyVar tv | isTcTyVar tv = zonkTcTyVar tv | otherwise = return (mkTyVarTy tv) -- Hackily, when typechecking type and class decls -- we have TyVars in scopeadded (only) in -- TcHsType.tcTyClTyVars, but it seems -- painful to make them into TcTyVars there zonkTyVarsAndFV :: TyVarSet -> TcM TyVarSet zonkTyVarsAndFV tyvars = tyVarsOfTypes <$> mapM zonkTyVar (varSetElems tyvars) zonkTcTyVars :: [TcTyVar] -> TcM [TcType] zonkTcTyVars tyvars = mapM zonkTcTyVar tyvars ----------------- Types zonkTyVarKind :: TyVar -> TcM TyVar zonkTyVarKind tv = do { kind' <- zonkTcKind (tyVarKind tv) ; return (setTyVarKind tv kind') } zonkTcTypes :: [TcType] -> TcM [TcType] zonkTcTypes tys = mapM zonkTcType tys zonkTcThetaType :: TcThetaType -> TcM TcThetaType zonkTcThetaType theta = mapM zonkTcPredType theta zonkTcPredType :: TcPredType -> TcM TcPredType zonkTcPredType = zonkTcType {- ************************************************************************ * * Zonking constraints * * ************************************************************************ -} zonkImplication :: Implication -> TcM Implication zonkImplication implic@(Implic { ic_skols = skols , ic_given = given , ic_wanted = wanted , ic_info = info }) = do { skols' <- mapM zonkTcTyVarBndr skols -- Need to zonk their kinds! -- as Trac #7230 showed ; given' <- mapM zonkEvVar given ; info' <- zonkSkolemInfo info ; wanted' <- zonkWCRec wanted ; return (implic { ic_skols = skols' , ic_given = given' , ic_wanted = wanted' , ic_info = info' }) } zonkEvVar :: EvVar -> TcM EvVar zonkEvVar var = do { ty' <- zonkTcType (varType var) ; return (setVarType var ty') } zonkWC :: WantedConstraints -> TcM WantedConstraints zonkWC wc = zonkWCRec wc zonkWCRec :: WantedConstraints -> TcM WantedConstraints zonkWCRec (WC { wc_simple = simple, wc_impl = implic, wc_insol = insol }) = do { simple' <- zonkSimples simple ; implic' <- mapBagM zonkImplication implic ; insol' <- zonkSimples insol ; return (WC { wc_simple = simple', wc_impl = implic', wc_insol = insol' }) } zonkSimples :: Cts -> TcM Cts zonkSimples cts = do { cts' <- mapBagM zonkCt' cts ; traceTc "zonkSimples done:" (ppr cts') ; return cts' } zonkCt' :: Ct -> TcM Ct zonkCt' ct = zonkCt ct zonkCt :: Ct -> TcM Ct zonkCt ct@(CHoleCan { cc_ev = ev }) = do { ev' <- zonkCtEvidence ev ; return $ ct { cc_ev = ev' } } zonkCt ct = do { fl' <- zonkCtEvidence (cc_ev ct) ; return (mkNonCanonical fl') } zonkCtEvidence :: CtEvidence -> TcM CtEvidence zonkCtEvidence ctev@(CtGiven { ctev_pred = pred }) = do { pred' <- zonkTcType pred ; return (ctev { ctev_pred = pred'}) } zonkCtEvidence ctev@(CtWanted { ctev_pred = pred }) = do { pred' <- zonkTcType pred ; return (ctev { ctev_pred = pred' }) } zonkCtEvidence ctev@(CtDerived { ctev_pred = pred }) = do { pred' <- zonkTcType pred ; return (ctev { ctev_pred = pred' }) } zonkSkolemInfo :: SkolemInfo -> TcM SkolemInfo zonkSkolemInfo (SigSkol cx ty) = do { ty' <- zonkTcType ty ; return (SigSkol cx ty') } zonkSkolemInfo (InferSkol ntys) = do { ntys' <- mapM do_one ntys ; return (InferSkol ntys') } where do_one (n, ty) = do { ty' <- zonkTcType ty; return (n, ty') } zonkSkolemInfo skol_info = return skol_info {- ************************************************************************ * * \subsection{Zonking -- the main work-horses: zonkTcType, zonkTcTyVar} * * * For internal use only! * * * ************************************************************************ -} -- zonkId is used *during* typechecking just to zonk the Id's type zonkId :: TcId -> TcM TcId zonkId id = do { ty' <- zonkTcType (idType id) ; return (Id.setIdType id ty') } -- For unbound, mutable tyvars, zonkType uses the function given to it -- For tyvars bound at a for-all, zonkType zonks them to an immutable -- type variable and zonks the kind too zonkTcType :: TcType -> TcM TcType zonkTcType ty = go ty where go (TyConApp tc tys) = do tys' <- mapM go tys return (TyConApp tc tys') -- Do NOT establish Type invariants, because -- doing so is strict in the TyCOn. -- See Note [Zonking inside the knot] in TcHsType go (LitTy n) = return (LitTy n) go (FunTy arg res) = do arg' <- go arg res' <- go res return (FunTy arg' res') go (AppTy fun arg) = do fun' <- go fun arg' <- go arg return (mkAppTy fun' arg') -- NB the mkAppTy; we might have instantiated a -- type variable to a type constructor, so we need -- to pull the TyConApp to the top. -- OK to do this because only strict in the structure -- not in the TyCon. -- See Note [Zonking inside the knot] in TcHsType -- The two interesting cases! go (TyVarTy tyvar) | isTcTyVar tyvar = zonkTcTyVar tyvar | otherwise = TyVarTy <$> updateTyVarKindM go tyvar -- Ordinary (non Tc) tyvars occur inside quantified types go (ForAllTy tv ty) = do { tv' <- zonkTcTyVarBndr tv ; ty' <- go ty ; return (ForAllTy tv' ty') } zonkTcTyVarBndr :: TcTyVar -> TcM TcTyVar -- A tyvar binder is never a unification variable (MetaTv), -- rather it is always a skolems. BUT it may have a kind -- that has not yet been zonked, and may include kind -- unification variables. zonkTcTyVarBndr tyvar = ASSERT2( isImmutableTyVar tyvar, ppr tyvar ) do updateTyVarKindM zonkTcType tyvar zonkTcTyVar :: TcTyVar -> TcM TcType -- Simply look through all Flexis zonkTcTyVar tv = ASSERT2( isTcTyVar tv, ppr tv ) do case tcTyVarDetails tv of SkolemTv {} -> zonk_kind_and_return RuntimeUnk {} -> zonk_kind_and_return FlatSkol ty -> zonkTcType ty MetaTv { mtv_ref = ref } -> do { cts <- readMutVar ref ; case cts of Flexi -> zonk_kind_and_return Indirect ty -> zonkTcType ty } where zonk_kind_and_return = do { z_tv <- zonkTyVarKind tv ; return (TyVarTy z_tv) } {- ************************************************************************ * * Zonking kinds * * ************************************************************************ -} zonkTcKind :: TcKind -> TcM TcKind zonkTcKind k = zonkTcType k {- ************************************************************************ * * Tidying * * ************************************************************************ -} zonkTidyTcType :: TidyEnv -> TcType -> TcM (TidyEnv, TcType) zonkTidyTcType env ty = do { ty' <- zonkTcType ty ; return (tidyOpenType env ty') } zonkTidyOrigin :: TidyEnv -> CtOrigin -> TcM (TidyEnv, CtOrigin) zonkTidyOrigin env (GivenOrigin skol_info) = do { skol_info1 <- zonkSkolemInfo skol_info ; let (env1, skol_info2) = tidySkolemInfo env skol_info1 ; return (env1, GivenOrigin skol_info2) } zonkTidyOrigin env (TypeEqOrigin { uo_actual = act, uo_expected = exp }) = do { (env1, act') <- zonkTidyTcType env act ; (env2, exp') <- zonkTidyTcType env1 exp ; return ( env2, TypeEqOrigin { uo_actual = act', uo_expected = exp' }) } zonkTidyOrigin env (KindEqOrigin ty1 ty2 orig) = do { (env1, ty1') <- zonkTidyTcType env ty1 ; (env2, ty2') <- zonkTidyTcType env1 ty2 ; (env3, orig') <- zonkTidyOrigin env2 orig ; return (env3, KindEqOrigin ty1' ty2' orig') } zonkTidyOrigin env (FunDepOrigin1 p1 l1 p2 l2) = do { (env1, p1') <- zonkTidyTcType env p1 ; (env2, p2') <- zonkTidyTcType env1 p2 ; return (env2, FunDepOrigin1 p1' l1 p2' l2) } zonkTidyOrigin env (FunDepOrigin2 p1 o1 p2 l2) = do { (env1, p1') <- zonkTidyTcType env p1 ; (env2, p2') <- zonkTidyTcType env1 p2 ; (env3, o1') <- zonkTidyOrigin env2 o1 ; return (env3, FunDepOrigin2 p1' o1' p2' l2) } zonkTidyOrigin env orig = return (env, orig) ---------------- tidyCt :: TidyEnv -> Ct -> Ct -- Used only in error reporting -- Also converts it to non-canonical tidyCt env ct = case ct of CHoleCan { cc_ev = ev } -> ct { cc_ev = tidy_ev env ev } _ -> mkNonCanonical (tidy_ev env (ctEvidence ct)) where tidy_ev :: TidyEnv -> CtEvidence -> CtEvidence -- NB: we do not tidy the ctev_evar field because we don't -- show it in error messages tidy_ev env ctev@(CtGiven { ctev_pred = pred }) = ctev { ctev_pred = tidyType env pred } tidy_ev env ctev@(CtWanted { ctev_pred = pred }) = ctev { ctev_pred = tidyType env pred } tidy_ev env ctev@(CtDerived { ctev_pred = pred }) = ctev { ctev_pred = tidyType env pred } ---------------- tidyEvVar :: TidyEnv -> EvVar -> EvVar tidyEvVar env var = setVarType var (tidyType env (varType var)) ---------------- tidySkolemInfo :: TidyEnv -> SkolemInfo -> (TidyEnv, SkolemInfo) tidySkolemInfo env (SigSkol cx ty) = (env', SigSkol cx ty') where (env', ty') = tidyOpenType env ty tidySkolemInfo env (InferSkol ids) = (env', InferSkol ids') where (env', ids') = mapAccumL do_one env ids do_one env (name, ty) = (env', (name, ty')) where (env', ty') = tidyOpenType env ty tidySkolemInfo env (UnifyForAllSkol skol_tvs ty) = (env1, UnifyForAllSkol skol_tvs' ty') where env1 = tidyFreeTyVars env (tyVarsOfType ty `delVarSetList` skol_tvs) (env2, skol_tvs') = tidyTyVarBndrs env1 skol_tvs ty' = tidyType env2 ty tidySkolemInfo env info = (env, info)
TomMD/ghc
compiler/typecheck/TcMType.hs
bsd-3-clause
36,748
10
21
10,531
7,013
3,654
3,359
-1
-1
{-# LANGUAGE OverloadedStrings #-} -- | Example program that continously computes the mean of a list of -- numbers. module Main where import Control.Concurrent import Control.Exception import Data.List import Data.Time.Clock.POSIX (getPOSIXTime) import qualified System.Metrics.Distribution as Distribution import qualified System.Metrics.Counter as Counter import qualified System.Metrics.Label as Label import System.Remote.Monitoring -- 'sum' is using a non-strict lazy fold and will blow the stack. sum' :: Num a => [a] -> a sum' = foldl' (+) 0 mean :: Fractional a => [a] -> a mean xs = sum' xs / fromIntegral (length xs) main :: IO () main = do handle <- forkServer "localhost" 8000 counter <- getCounter "iterations" handle label <- getLabel "args" handle event <- getDistribution "runtime" handle Label.set label "some text string" let loop n = do t <- timed $ evaluate $ mean [1..n] Distribution.add event t threadDelay 2000 Counter.inc counter loop n loop 1000000 timed :: IO a -> IO Double timed m = do start <- getTime m end <- getTime return $! end - start getTime :: IO Double getTime = realToFrac `fmap` getPOSIXTime
seanparsons/ekg
examples/Basic.hs
bsd-3-clause
1,243
0
15
290
356
182
174
36
1
----------------------------------------------------------------------------- -- Lazy State Thread module -- -- This library provides support for both lazy and strict state threads, -- as described in the PLDI '94 paper by John Launchbury and Simon Peyton -- Jones. In addition to the monad ST, it also provides mutable variables -- STRef and mutable arrays STArray. It is identical to the ST module -- except that the ST instance is lazy. -- -- Suitable for use with Hugs 98. ----------------------------------------------------------------------------- module Hugs.LazyST ( ST , runST , unsafeInterleaveST , fixST , lazyToStrictST , strictToLazyST ) where import qualified Hugs.ST as ST import Control.Monad ----------------------------------------------------------------------------- newtype ST s a = ST (State s -> (a, State s)) unST :: ST s a -> State s -> (a, State s) unST (ST f) = f runST :: (forall s. ST s a) -> a runST m = fst (unST m S) unsafeInterleaveST :: ST s a -> ST s a unsafeInterleaveST (ST m) = return (fst (m S)) fixST :: (a -> ST s a) -> ST s a fixST f = ST (\s -> let (x,s') = unST (f x) s in (x,s')) instance Functor (ST s) where fmap = liftM instance Monad (ST s) where return a = ST (\s -> (a, s)) ST m >>= f = ST (\S -> let (a,s') = m S in unST (f a) s') -- ST m >>= f = ST (\s -> let (a,s') = m s in unST (f a) s') ----------------------------------------------------------------------------- data State s = S ----------------------------------------------------------------------------- lazyToStrictST :: ST s a -> ST.ST s a lazyToStrictST (ST m) = ST.ST (\k -> case m S of (a,S) -> k a) strictToLazyST :: ST.ST s a -> ST s a strictToLazyST (ST.ST m) = ST (\S -> m delay) -- \s -> let (a',s') = case s of S -> m (\a -> (a,S)) in (a',s')) delay :: a -> (a, State s) delay a = (a,S) -----------------------------------------------------------------------------
kaoskorobase/mescaline
resources/hugs/packages/hugsbase/Hugs/LazyST.hs
gpl-3.0
1,939
4
14
373
578
310
268
-1
-1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Bench -- Copyright : Johan Tibell 2011 -- License : BSD3 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- This is the entry point into running the benchmarks in a built -- package. It performs the \"@.\/setup bench@\" action. It runs -- benchmarks designated in the package description. module Distribution.Simple.Bench ( bench ) where import Prelude () import Distribution.Compat.Prelude import Distribution.Types.UnqualComponentName import qualified Distribution.PackageDescription as PD import Distribution.Simple.BuildPaths import Distribution.Simple.Compiler import Distribution.Simple.InstallDirs import qualified Distribution.Simple.LocalBuildInfo as LBI import Distribution.Simple.Setup import Distribution.Simple.UserHooks import Distribution.Simple.Utils import Distribution.Text import System.Exit ( ExitCode(..), exitFailure, exitSuccess ) import System.Directory ( doesFileExist ) import System.FilePath ( (</>), (<.>) ) -- | Perform the \"@.\/setup bench@\" action. bench :: Args -- ^positional command-line arguments -> PD.PackageDescription -- ^information from the .cabal file -> LBI.LocalBuildInfo -- ^information from the configure step -> BenchmarkFlags -- ^flags sent to benchmark -> IO () bench args pkg_descr lbi flags = do let verbosity = fromFlag $ benchmarkVerbosity flags benchmarkNames = args pkgBenchmarks = PD.benchmarks pkg_descr enabledBenchmarks = map fst (LBI.enabledBenchLBIs pkg_descr lbi) -- Run the benchmark doBench :: PD.Benchmark -> IO ExitCode doBench bm = case PD.benchmarkInterface bm of PD.BenchmarkExeV10 _ _ -> do let cmd = LBI.buildDir lbi </> name </> name <.> exeExtension options = map (benchOption pkg_descr lbi bm) $ benchmarkOptions flags -- Check that the benchmark executable exists. exists <- doesFileExist cmd unless exists $ die' verbosity $ "Error: Could not find benchmark program \"" ++ cmd ++ "\". Did you build the package first?" notice verbosity $ startMessage name -- This will redirect the child process -- stdout/stderr to the parent process. exitcode <- rawSystemExitCode verbosity cmd options notice verbosity $ finishMessage name exitcode return exitcode _ -> do notice verbosity $ "No support for running " ++ "benchmark " ++ name ++ " of type: " ++ display (PD.benchmarkType bm) exitFailure where name = unUnqualComponentName $ PD.benchmarkName bm unless (PD.hasBenchmarks pkg_descr) $ do notice verbosity "Package has no benchmarks." exitSuccess when (PD.hasBenchmarks pkg_descr && null enabledBenchmarks) $ die' verbosity $ "No benchmarks enabled. Did you remember to configure with " ++ "\'--enable-benchmarks\'?" bmsToRun <- case benchmarkNames of [] -> return enabledBenchmarks names -> for names $ \bmName -> let benchmarkMap = zip enabledNames enabledBenchmarks enabledNames = map PD.benchmarkName enabledBenchmarks allNames = map PD.benchmarkName pkgBenchmarks in case lookup (mkUnqualComponentName bmName) benchmarkMap of Just t -> return t _ | mkUnqualComponentName bmName `elem` allNames -> die' verbosity $ "Package configured with benchmark " ++ bmName ++ " disabled." | otherwise -> die' verbosity $ "no such benchmark: " ++ bmName let totalBenchmarks = length bmsToRun notice verbosity $ "Running " ++ show totalBenchmarks ++ " benchmarks..." exitcodes <- traverse doBench bmsToRun let allOk = totalBenchmarks == length (filter (== ExitSuccess) exitcodes) unless allOk exitFailure where startMessage name = "Benchmark " ++ name ++ ": RUNNING...\n" finishMessage name exitcode = "Benchmark " ++ name ++ ": " ++ (case exitcode of ExitSuccess -> "FINISH" ExitFailure _ -> "ERROR") -- TODO: This is abusing the notion of a 'PathTemplate'. The result isn't -- necessarily a path. benchOption :: PD.PackageDescription -> LBI.LocalBuildInfo -> PD.Benchmark -> PathTemplate -> String benchOption pkg_descr lbi bm template = fromPathTemplate $ substPathTemplate env template where env = initialPathTemplateEnv (PD.package pkg_descr) (LBI.localUnitId lbi) (compilerInfo $ LBI.compiler lbi) (LBI.hostPlatform lbi) ++ [(BenchmarkNameVar, toPathTemplate $ unUnqualComponentName $ PD.benchmarkName bm)]
mydaum/cabal
Cabal/Distribution/Simple/Bench.hs
bsd-3-clause
5,351
0
22
1,638
994
507
487
89
5
module ListToMaybeIn2 where f :: [a] -> Maybe a f x@[] = (case x of [] -> Nothing (a : _) -> Just a) f x@((b_1 : b_2)) = (case x of [] -> Nothing (a : _) -> Just a) f x = listToMaybe x f_1 x@((b_1 : b_2)) = (case x of [] -> return 0 (a : _) -> return 1) listToMaybe :: [a] -> Maybe a listToMaybe [] = Nothing listToMaybe ((a : _)) = Just a g :: [Int] -> Int g ((x : xs)) = x + (head (tail xs))
kmate/HaRe
old/testing/simplifyExpr/ListToMaybeIn2AST.hs
bsd-3-clause
503
0
10
205
273
145
128
20
3
{-# LANGUAGE DeriveFunctor #-} module Lamdu.Data.Ops ( newHole, wrap, setToWrapper , replace, replaceWithHole, setToHole, lambdaWrap, redexWrap , addListItem , newPublicDefinition , newDefinition, presentationModeOfName , savePreJumpPosition, jumpBack , newPane , newClipboard , makeNewTag, makeNewPublicTag , isInfix ) where import Control.Applicative ((<$>), (<*>), (<$)) import Control.Lens.Operators import Control.Monad (when) import Control.MonadA (MonadA) import Data.Store.Guid (Guid) import Data.Store.IRef (Tag) import Data.Store.Transaction (Transaction, getP, setP, modP) import Lamdu.CharClassification (operatorChars) import Lamdu.Data.Anchors (PresentationMode(..)) import Lamdu.Data.Expression.IRef (DefIM) import qualified Data.Store.IRef as IRef import qualified Data.Store.Property as Property import qualified Data.Store.Transaction as Transaction import qualified Graphics.UI.Bottle.WidgetId as WidgetId import qualified Lamdu.Data.Anchors as Anchors import qualified Lamdu.Data.Definition as Definition import qualified Lamdu.Data.Expression as Expr import qualified Lamdu.Data.Expression.IRef as ExprIRef import qualified Lamdu.Data.Expression.Lens as ExprLens import qualified Lamdu.Data.Expression.Utils as ExprUtil type T = Transaction setToWrapper :: MonadA m => ExprIRef.ExpressionI (Tag m) -> ExprIRef.ExpressionProperty m -> T m (ExprIRef.ExpressionI (Tag m)) setToWrapper wrappedI destP = do newFuncI <- newHole destI <$ ExprIRef.writeExprBody destI (ExprUtil.makeApply newFuncI wrappedI) where destI = Property.value destP wrap :: MonadA m => ExprIRef.ExpressionProperty m -> T m (ExprIRef.ExpressionI (Tag m)) wrap exprP = do newFuncI <- newHole applyI <- ExprIRef.newExprBody . ExprUtil.makeApply newFuncI $ Property.value exprP Property.set exprP applyI return applyI newHole :: MonadA m => T m (ExprIRef.ExpressionI (Tag m)) newHole = ExprIRef.newExprBody $ Expr.BodyLeaf Expr.Hole replace :: MonadA m => ExprIRef.ExpressionProperty m -> ExprIRef.ExpressionI (Tag m) -> T m (ExprIRef.ExpressionI (Tag m)) replace exprP newExprI = do Property.set exprP newExprI return newExprI replaceWithHole :: MonadA m => ExprIRef.ExpressionProperty m -> T m (ExprIRef.ExpressionI (Tag m)) replaceWithHole exprP = replace exprP =<< newHole setToHole :: MonadA m => ExprIRef.ExpressionProperty m -> T m (ExprIRef.ExpressionI (Tag m)) setToHole exprP = exprI <$ ExprIRef.writeExprBody exprI hole where hole = Expr.BodyLeaf Expr.Hole exprI = Property.value exprP lambdaWrap :: MonadA m => ExprIRef.ExpressionProperty m -> T m (Guid, ExprIRef.ExpressionI (Tag m)) lambdaWrap exprP = do newParamTypeI <- newHole (newParam, newExprI) <- ExprIRef.newLambda newParamTypeI $ Property.value exprP Property.set exprP newExprI return (newParam, newExprI) redexWrap :: MonadA m => ExprIRef.ExpressionProperty m -> T m (Guid, ExprIRef.ExpressionI (Tag m)) redexWrap exprP = do newParamTypeI <- newHole (newParam, newLambdaI) <- ExprIRef.newLambda newParamTypeI $ Property.value exprP newValueI <- newHole newApplyI <- ExprIRef.newExprBody $ ExprUtil.makeApply newLambdaI newValueI Property.set exprP newApplyI return (newParam, newLambdaI) addListItem :: MonadA m => Anchors.SpecialFunctions (Tag m) -> ExprIRef.ExpressionProperty m -> T m (ExprIRef.ExpressionI (Tag m), ExprIRef.ExpressionI (Tag m)) addListItem specialFunctions exprP = do consTempI <- ExprIRef.newExprBody $ ExprLens.bodyDefinitionRef # Anchors.sfCons specialFunctions consI <- ExprIRef.newExprBody . ExprUtil.makeApply consTempI =<< newHole newItemI <- newHole headTag <- ExprIRef.newExprBody $ ExprLens.bodyTag # Anchors.sfHeadTag specialFunctions tailTag <- ExprIRef.newExprBody $ ExprLens.bodyTag # Anchors.sfTailTag specialFunctions argsI <- ExprIRef.newExprBody $ ExprLens.bodyKindedRecordFields Expr.KVal # [ (headTag, newItemI) , (tailTag, Property.value exprP) ] newListI <- ExprIRef.newExprBody $ ExprUtil.makeApply consI argsI Property.set exprP newListI return (newListI, newItemI) newPane :: MonadA m => Anchors.CodeProps m -> DefIM m -> T m () newPane codeProps defI = do let panesProp = Anchors.panes codeProps panes <- getP panesProp when (defI `notElem` panes) $ setP panesProp $ Anchors.makePane defI : panes savePreJumpPosition :: MonadA m => Anchors.CodeProps m -> WidgetId.Id -> T m () savePreJumpPosition codeProps pos = modP (Anchors.preJumps codeProps) $ (pos :) . take 19 jumpBack :: MonadA m => Anchors.CodeProps m -> T m (Maybe (T m WidgetId.Id)) jumpBack codeProps = do preJumps <- getP (Anchors.preJumps codeProps) return $ case preJumps of [] -> Nothing (j:js) -> Just $ do setP (Anchors.preJumps codeProps) js return j isInfix :: String -> Bool isInfix x = not (null x) && all (`elem` operatorChars) x presentationModeOfName :: String -> PresentationMode presentationModeOfName x | isInfix x = Infix | otherwise = OO newDefinition :: MonadA m => String -> PresentationMode -> Definition.Body (ExprIRef.ExpressionIM m) -> T m (DefIM m) newDefinition name presentationMode defBody = do res <- Transaction.newIRef defBody let guid = IRef.guid res setP (Anchors.assocNameRef guid) name setP (Anchors.assocPresentationMode guid) presentationMode return res newPublicDefinition :: MonadA m => Anchors.CodeProps m -> String -> T m (DefIM m) newPublicDefinition codeProps name = do defI <- newDefinition name (presentationModeOfName name) =<< (Definition.Body . Definition.ContentExpression <$> newHole <*> newHole) modP (Anchors.globals codeProps) (defI :) return defI newClipboard :: MonadA m => Anchors.CodeProps m -> ExprIRef.ExpressionI (Tag m) -> T m (DefIM m) newClipboard codeProps expr = do len <- length <$> getP (Anchors.clipboards codeProps) def <- Definition.Body (Definition.ContentExpression expr) <$> newHole defI <- newDefinition ("clipboard" ++ show len) OO def modP (Anchors.clipboards codeProps) (defI:) return defI makeNewTag :: MonadA m => String -> T m Guid makeNewTag name = do tag <- Transaction.newKey tag <$ setP (Anchors.assocNameRef tag) name makeNewPublicTag :: MonadA m => Anchors.CodeProps m -> String -> T m Guid makeNewPublicTag codeProps name = do tag <- makeNewTag name modP (Anchors.tags codeProps) (tag :) return tag
sinelaw/lamdu
Lamdu/Data/Ops.hs
gpl-3.0
6,460
0
17
1,086
2,178
1,092
1,086
172
2
{-# LANGUAGE PatternGuards #-} {- Copyright (C) 2015 Martin Linnemann <theCodingMarlin@googlemail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.Reader.Odt Copyright : Copyright (C) 2015 Martin Linnemann License : GNU GPL, version 2 or above Maintainer : Martin Linnemann <theCodingMarlin@googlemail.com> Stability : alpha Portability : portable Entry point to the odt reader. -} module Text.Pandoc.Readers.Odt ( readOdt ) where import Codec.Archive.Zip import qualified Text.XML.Light as XML import qualified Data.ByteString.Lazy as B import Data.Monoid ( mempty ) import Text.Pandoc.Definition import Text.Pandoc.Error import Text.Pandoc.Options import Text.Pandoc.MediaBag import qualified Text.Pandoc.UTF8 as UTF8 import Text.Pandoc.Readers.Odt.ContentReader import Text.Pandoc.Readers.Odt.StyleReader import Text.Pandoc.Readers.Odt.Generic.XMLConverter import Text.Pandoc.Readers.Odt.Generic.Fallible -- readOdt :: ReaderOptions -> B.ByteString -> Either PandocError (Pandoc, MediaBag) readOdt _ bytes = case bytesToOdt bytes of Right pandoc -> Right (pandoc , mempty) Left err -> Left err -- bytesToOdt :: B.ByteString -> Either PandocError Pandoc bytesToOdt bytes = archiveToOdt $ toArchive bytes -- archiveToOdt :: Archive -> Either PandocError Pandoc archiveToOdt archive | Just contentEntry <- findEntryByPath "content.xml" archive , Just stylesEntry <- findEntryByPath "styles.xml" archive , Just contentElem <- entryToXmlElem contentEntry , Just stylesElem <- entryToXmlElem stylesEntry , Right styles <- chooseMax (readStylesAt stylesElem ) (readStylesAt contentElem) , startState <- readerState styles , Right pandoc <- runConverter' read_body startState contentElem = Right pandoc | otherwise -- Not very detailed, but I don't think more information would be helpful = Left $ ParseFailure "Couldn't parse odt file." -- entryToXmlElem :: Entry -> Maybe XML.Element entryToXmlElem = XML.parseXMLDoc . UTF8.toStringLazy . fromEntry
gbataille/pandoc
src/Text/Pandoc/Readers/Odt.hs
gpl-2.0
3,069
0
11
819
417
228
189
40
2
import Text.ParserCombinators.Parsec import Numeric (readOct,readHex) import System.Environment import Control.Monad.Except import Data.List (minimumBy) import Data.Maybe (mapMaybe) type Node = Int type Graph = [(Node,[(Node,Int)])] cmpBy :: Ord b => (a -> b) -> a -> a -> Ordering cmpBy foo a b = foo a `compare` foo b shortestNeighbour :: [(Node,Int)] -> Node -> Maybe (Node,Int) shortestNeighbour [(node,cost)] dest = if node == dest then Just (node,cost) else Nothing shortestNeighbour [] _ = Nothing shortestNeighbour list dest = case mapMaybe (\x -> shortestNeighbour [x] dest) list of [] -> Nothing list -> Just $ minimumBy (\a b -> cmpBy (\(_,cost) -> cost) a b) list shortestPath :: Node -> Node -> Graph -> Maybe Int shortestPath start dest nodeMap = if start == dest then Just 0 else do neighbours <- lookup start nodeMap case shortestNeighbour neighbours dest of Just (_,cost) -> Just cost Nothing -> case mapMaybe (\(node,cost) -> case shortestPath node dest $ filter (\(i,_) -> i /= start) nodeMap of Just i -> Just (cost + i) Nothing -> Nothing ) neighbours of [] -> Nothing list -> Just $ minimum list parseArgs :: [String] -> IO (Int,Int) parseArgs [startstr,deststr] = return (read startstr,read deststr) parseGraph :: Parser Graph parseGraph = between (char '[') (char ']') (sepBy parseNode $ char ',') parseNode :: Parser (Node,[(Node,Int)]) parseNode = do char '(' node <- parseNumber char ',' neighbours <- parseNeighbours char ')' return (node,neighbours) parseNeighbours :: Parser [(Node,Int)] parseNeighbours = between (char '[') (char ']') (sepBy parseNeighbour $ char ',') parseNeighbour :: Parser (Node,Int) parseNeighbour = do char '(' node <- parseNumber char ',' cost <- parseNumber char ')' return (node,cost) parseNumber :: Parser Int parseNumber = do str <- many digit return $ read str main :: IO () main = do args <- getArgs pos <- parseArgs args input <- getContents case parse parseGraph "graph" input of Left err -> print err Right graph -> maybe (print "no path") (print) $ let (start,dest) = pos in shortestPath start dest graph
benaryorg/haskell-inefficient-graph-traversal
src/Main.hs
isc
2,144
11
20
406
971
489
482
64
5
{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeOperators #-} -- | This module tests whether streaming works from client to server -- with a server implemented with servant-server. module Servant.Server.StreamingSpec where import Control.Concurrent import Control.Exception hiding (Handler) import Control.Monad.IO.Class import qualified Data.ByteString as Strict import qualified Data.ByteString.Lazy as Lazy import Network.HTTP.Types import Network.Wai import Network.Wai.Internal import Prelude () import Prelude.Compat import Servant import qualified System.Timeout import Test.Hspec type TestAPI = ReqBody '[OctetStream] Lazy.ByteString :> Get '[JSON] NoContent testAPI :: Proxy TestAPI testAPI = Proxy spec :: Spec spec = do -- The idea of this test is this: -- -- - The mock client will -- - send some data in the request body, but not all, -- - wait for the server to acknowledge (outside of http, through an MVar) -- that the server received some data, -- - send the rest of the request body. -- - The mock server will -- - receive some data, -- - notify the client that it received some data, -- - receive the rest of the data, -- - respond with an empty result. it "client to server can stream lazy ByteStrings" $ timeout $ do serverReceivedFirstChunk <- newWaiter -- - streams some test data -- - waits for serverReceivedFirstChunk -- - streams some more test data streamTestData <- do mvar :: MVar [IO Strict.ByteString] <- newMVar $ map return (replicate 1000 "foo") ++ (waitFor serverReceivedFirstChunk >> return "foo") : map return (replicate 1000 "foo") return $ modifyMVar mvar $ \ actions -> case actions of (a : r) -> (r, ) <$> a [] -> return ([], "") let request = defaultRequest { requestBody = streamTestData, requestBodyLength = ChunkedBody } -- - receives the first chunk -- - notifies serverReceivedFirstChunk -- - receives the rest of the request let handler :: Lazy.ByteString -> Handler NoContent handler input = liftIO $ do let prefix = Lazy.take 3 input prefix `shouldBe` "foo" notify serverReceivedFirstChunk () input `shouldBe` mconcat (replicate 2001 "foo") return NoContent app = serve testAPI handler response <- executeRequest app request statusCode (responseStatus response) `shouldBe` 200 executeRequest :: Application -> Request -> IO Response executeRequest app request = do responseMVar <- newEmptyMVar let respond response = do putMVar responseMVar response return ResponseReceived ResponseReceived <- app request respond takeMVar responseMVar timeout :: IO a -> IO a timeout action = do result <- System.Timeout.timeout 1000000 action maybe (throwIO $ ErrorCall "timeout") return result -- * waiter data Waiter a = Waiter { notify :: a -> IO (), waitFor :: IO a } newWaiter :: IO (Waiter a) newWaiter = do mvar <- newEmptyMVar return $ Waiter { notify = putMVar mvar, waitFor = readMVar mvar }
zoomhub/zoomhub
vendor/servant/servant-server/test/Servant/Server/StreamingSpec.hs
mit
3,400
0
20
920
710
375
335
71
2
{-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, DeriveDataTypeable, OverloadedStrings, StandaloneDeriving #-} module ConvertImage( ImageString , Blueprint , Position , Phase(..) , header , phrases , convertpngs ) where import Data.Typeable(Typeable) import Data.Data(Data) import Codec.Picture.Types import Data.List(unzip,intercalate,intersperse) import Data.Maybe(isNothing,fromJust) import Data.Either(partitionEithers) import qualified Data.ByteString.Lazy.Char8 as L import qualified Data.ByteString as B import qualified Data.Map.Strict as M import qualified Data.Vector.Storable as V import Config type ImageString = String type Blueprint = L.ByteString type Position = Maybe (Int,Int) -- string to put in empty cells, quickfort accepts an empty string or "#" here emptyCell = "#" -- This header goes at the top of each Blueprint and tells -- quickfort where to start and in what mode to run header :: Position -> Int -> Phase -> String header pos w p = '#':mode p ++ start ++ replicate w ',' where start = maybe "" (\x-> " start" ++ show x) pos mode Dig = "dig" mode Build = "build" mode Place = "place" mode _ = "query" convertpngs :: Int -> Position -> [DynamicImage] -> String -> CommandDictionary -> [Either String Blueprint] convertpngs r pos imgs phases dict | null err = convertImage | otherwise = map Left err where convertImage = map (\phase -> pngconvert r pos imgs phase dict) p (err,images) = partitionEithers convertImage p = parsePhases phases -- convert a list of images into a blueprint pngconvert :: Int -> Position -> [DynamicImage] -> Phase -> CommandDictionary -> Either String Blueprint pngconvert r pos imgs phase dict | null errs == False = Left (intercalate "\n" errs) | any (w/=) width || any (h/=) height = Left "Error: not all images have the same dimensions" | otherwise = Right $ toCSV r pos w phase images where (errs,images) = partitionEithers csvList w = head width h = head height (width,height) = unzip $ map extractDims imgs extractDims i = (dynamicMap imageWidth i,dynamicMap imageHeight i) csvList = map (imageToList (translate dict phase)) imgs -- concat a list of ImageStrings into a single csv Blueprint toCSV :: Int -> Position -> Int -> Phase -> [ImageString] -> Blueprint toCSV r s w p imgs = L.pack $ header s w p ++ intercalate uplevel repeatedImgs where uplevel = "\n#>" ++ replicate w ',' repeatedImgs = take (r * (length imgs)) (cycle imgs) -- convert a RGBA8 image to a list of lists of strings imageToList :: (PixelRGBA8 -> String) -> DynamicImage -> Either String ImageString imageToList dict (ImageRGBA8 img) = Right $ convertVector (imageData img) where convertVector = csvify (width) . (map ((++ ",") . dict)) . (toPixelList . V.toList) width = imageWidth img -- convert list of Word8 values into a list of RGBA8 Pixels toPixelList [] = [] toPixelList (a:b:c:d:pixels) = (PixelRGBA8 a b c d) : toPixelList pixels --catch non RGBA8 images and give an error message imageToList _ _ = Left "Error: one or more images are not encoded in RGBA8 color, \ \did you remember to add an alpha channel?" -- take a list of comma delimited strings and return a string with newlines added csvify :: (Int) -> [String] -> String csvify _ [] = "" -- we add a header to the csv later, and the last line of the file doesn't -- need a newline, so we can prepend it for a small savings csvify i ls = '\n' : (concat row) ++ csvify i rest where (row,rest) = splitAt i ls parsePhases :: String -> [Phase] parsePhases "" = [] parsePhases "All" = [Dig,Build,Place,Query] parsePhases s = map read (phrases s) -- same as words, but cuts on commas instead of spaces phrases :: String -> [String] phrases s = case dropWhile {-partain:Char.-}isComma s of "" -> [] s' -> w : phrases s'' where (w,s'') = break {-partain:Char.-} isComma s' isComma :: Char -> Bool isComma ',' = True isComma _ = False data Phase = Dig | Build | Place | Query deriving (Typeable, Data, Eq, Read, Show) translate :: CommandDictionary -> Phase -> PixelRGBA8 -> String translate dict Dig key = M.findWithDefault emptyCell key (des dict) translate dict Build key = M.findWithDefault emptyCell key (bld dict) translate dict Place key = M.findWithDefault emptyCell key (plc dict) translate dict Query key = M.findWithDefault emptyCell key (qry dict)
Hrothen/scripts
src/convertPNG/ConvertImage.hs
mit
4,765
0
13
1,193
1,345
714
631
-1
-1
isPrime :: Int -> Bool isPrime n = isDividable n (n-1) where isDividable 1 _ = False isDividable 2 _ = True isDividable x 2 = (x `mod` 2) > 0 isDividable x y = (x `mod` y) > 0 && isDividable x (y - 1)
mojtabatmj/Hacktoberfest2017
Prime-Number/isPrime.hs
mit
236
0
8
81
120
61
59
6
4
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DeriveGeneric #-} module Text.Greek.Script.Unicode where import Control.Lens import GHC.Generics (Generic) import Data.Aeson (ToJSON, FromJSON) import Data.Text (Text) import Data.Unicode.DecomposeChar import Text.Greek.Source.FileReference import Text.Greek.Parse.Utility import Text.Greek.Utility import Text.Parsec.Combinator import Text.Parsec.Error (ParseError) import Text.Parsec.Prim import qualified Data.Char as Char import qualified Data.Text as Text import qualified Text.Greek.Script.Marked as Marked newtype Composed = Composed { composed :: Char } deriving (Eq, Ord, Show, Generic) instance ToJSON Composed instance FromJSON Composed newtype Decomposed = Decomposed { decomposed :: Char } deriving (Eq, Ord, Show, Generic) instance ToJSON Decomposed instance FromJSON Decomposed newtype Letter = Letter { getLetter :: Char } deriving (Eq, Ord, Show, Generic) instance ToJSON Letter instance FromJSON Letter newtype Mark = Mark { getMark :: Char } deriving (Eq, Ord, Show, Generic) instance ToJSON Mark instance FromJSON Mark data Error = ErrorMultipleLines FileReference Text | ErrorMismatchLength FileReference Text | ErrorParse ParseError deriving Show decompose :: [(Composed, FileCharReference)] -> [(Decomposed, FileCharReference)] decompose cs = over (traverse . _1) Decomposed . concatMap (_1 id) . over (traverse . _1) (decomposeChar . composed) $ cs decompose' :: Composed -> [Decomposed] decompose' = fmap Decomposed . decomposeChar . composed toComposed :: Text -> [Composed] toComposed = fmap Composed . Text.unpack splitText :: Text -> FileReference -> Either Error [(Composed, FileCharReference)] splitText t r = ensureConsistent t r & _Right . each . _1 %~ Composed ensureConsistent :: Text -> FileReference -> Either Error [(Char, FileCharReference)] ensureConsistent t r = do (p, l, c1, c2) <- onErr ErrorMultipleLines $ ensureSingleLine r cs <- onErr ErrorMismatchLength $ ensureLengthMatches t c1 c2 return $ fmap (_2 %~ FileCharReference p . LineReference l) cs where onErr e = maybeToEither (e r t) ensureSingleLine :: FileReference -> Maybe (Path, Line, Column, Column) ensureSingleLine (FileReference p (LineReference l1 c1) (LineReference l2 c2)) | l1 == l2 = Just (p, l1, c1, c2) ensureSingleLine _ = Nothing ensureLengthMatches :: Text -> Column -> Column -> Maybe [(Char, Column)] ensureLengthMatches t (Column c1) (Column c2) | Text.length t == c2 - c1 = Just (zipWith (,) (Text.unpack t) (fmap (Column . (+c1)) [0..])) ensureLengthMatches _ _ _ = Nothing parseMarkedLetters :: [Decomposed] -> Either Error [([Decomposed], Marked.Unit Letter [Mark])] parseMarkedLetters = over _Left ErrorParse . parse markedLettersParser "" type DecomposedParser = ParsecT [Decomposed] () Identity satisfy :: String -> (Char -> Bool) -> DecomposedParser Decomposed satisfy p f = primBool' p (f . decomposed) markParser :: DecomposedParser (Decomposed, Mark) markParser = (\x@(Decomposed c) -> (x, Mark c)) <$> satisfy "Mark" Char.isMark letterParser :: DecomposedParser (Decomposed, Letter) letterParser = (\x@(Decomposed c) -> (x, Letter c)) <$> satisfy "Letter" Char.isLetter markedLetterParser :: DecomposedParser ([Decomposed], Marked.Unit Letter [Mark]) markedLetterParser = do (decomposedLetter, simpleLetter) <- letterParser compositeMarks <- many markParser let decomposedMarks = fmap fst compositeMarks let simpleMarks = fmap snd compositeMarks return (decomposedLetter : decomposedMarks, Marked.Unit simpleLetter simpleMarks) markedLettersParser :: DecomposedParser [([Decomposed], Marked.Unit Letter [Mark])] markedLettersParser = many1 markedLetterParser <* eof
scott-fleischman/greek-grammar
haskell/greek-grammar/src/Text/Greek/Script/Unicode.hs
mit
3,697
0
13
532
1,271
688
583
-1
-1
{-# LANGUAGE GeneralizedNewtypeDeriving, TemplateHaskell #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleInstances #-} module IRC.Types where import Control.Lens import Data.Set (Set) import Data.Map (Map) import qualified IRC.Raw.Types as Raw import IRC.Raw.Monad import Data.Monoid import Data.ByteString (ByteString) import Data.Text (Text) import Data.Aeson import Control.Applicative import Control.Monad data Cmd = N Int | S ByteString deriving (Show,Eq,Ord) -- used by IRC.Commands data User = User Nick Ident Host deriving (Show,Eq) userNick :: User -> Nick userNick (User n _ _) = n newtype Channel = Channel Text deriving (Show,Eq,FromJSON) newtype Nick = Nick Text deriving (Show,Eq,Ord,FromJSON) newtype Message = Message Text deriving (Show,Eq,Monoid) newtype Target = Target Text deriving (Show,Eq) newtype Account = Account Text deriving (Show,Eq,Ord) type Ident = Text type Host = Text data Mode = Plus Char | Minus Char deriving (Show,Eq) data CMode = CMode Nick Mode deriving (Show,Eq) data SASLCfg = SASLCfg { sasl_username :: String ,sasl_password :: String } deriving (Show,Eq) data ChannelCfg = ChannelCfg { channel_name :: Channel ,channel_password :: Maybe String } deriving (Show,Eq) data IRCConfig = IRCConfig { config_network :: String ,config_port :: Int ,config_nick :: Nick ,config_sasl :: Maybe SASLCfg ,config_channels :: [ChannelCfg] } deriving (Show,Eq) instance FromJSON SASLCfg where parseJSON (Object v) = SASLCfg <$> v .: "username" <*> v .: "password" parseJSON _ = fail "sasl_cfg" instance FromJSON ChannelCfg where parseJSON (Object v) = ChannelCfg <$> v .: "name" <*> v .:? "password" parseJSON _ = fail "channel_cfg" instance FromJSON IRCConfig where parseJSON (Object v) = IRCConfig <$> v .: "network" <*> v .:? "port" .!= 6667 <*> v .: "nick" <*> v .:? "sasl" <*> v .: "channels" parseJSON _ = fail "irc_config"
EXio4/netza
src/IRC/Types.hs
mit
2,448
0
16
857
642
359
283
72
1
module ProjectEuler.Problem71 ( problem ) where import Data.Ratio import ProjectEuler.Types problem :: Problem problem = pureProblem 71 Solved result {- see: http://en.wikipedia.org/wiki/Farey_sequence if two fractions are Farey neighbors, a/b < c/d, then we have: b*c - a*d = 1 the converse is true: if b*c - a*d = 1, then a/b and c/d must be neighbors in Farey sequence of order max(b,d) therefore we can search all possible d <= 1,000,000 to find those pairs the closest neighbor must have the maximum value. in our problem, we know that: n/d < 3/7, so the target is: 3d - 7n = 1, therefore: n = (3*d-1) / 7, n is an integer -} solutions :: [Ratio Int] solutions = do d <- [1..1000000] let n = 3*d-1 (q,0) <- [n `quotRem` 7] pure (q % d) result :: Int result = numerator $ maximum solutions
Javran/Project-Euler
src/ProjectEuler/Problem71.hs
mit
844
0
11
194
136
74
62
14
1
module SFML.Window.Types ( Context(..) , Window(..) ) where import Foreign.Ptr newtype Context = Context (Ptr Context) newtype Window = Window (Ptr Window)
SFML-haskell/SFML
src/SFML/Window/Types.hs
mit
169
0
7
35
56
35
21
7
0
import qualified Data.Map as M main :: IO () main = interact atbash atbash :: String -> String atbash = map $ \c -> M.findWithDefault c c atbashDict atbashDict :: M.Map Char Char atbashDict = M.fromList $ zip ['a'..'z'] ['z','y'..'a'] ++ zip ['A'..'Z'] ['Z','Y'..'A']
devonhollowood/dailyprog
2016-02-15/atbash.hs
mit
275
1
8
51
136
68
68
8
1
-- -*- mode: haskell; -*- {-# LANGUAGE BangPatterns #-} module Poker ( HoleCards (..), pocketPair, suited, connected, handShape, PokerRank (..), pokerRank, PokerHand (..), pokerHandCards, pokerHandRank, generateBoards, generateBoard, generateHands, groupRanks, countRanks, countSuits, bestPokerHand, readHoleCards, ShowdownTally (..), pokerEquity, blankTally, addTally, percentTally, newWin, newTie, newLoss ) where import Cards import Wiggly import Data.List import Data.Maybe (fromJust, isJust, catMaybes) import Data.Ratio import Data.Monoid import Data.Char (isSpace) import GHC.Exts (groupWith) import Control.DeepSeq import Data.Choose as DC import Debug.Trace (trace) -- hole cards dealt to a player in Hold Em data HoleCards = HoleCards Card Card instance Read HoleCards where readsPrec _ value = do let stripped = dropWhile isSpace value rest = drop 4 stripped in maybe [] (\x -> [(x,rest)]) $ readHoleCards $ take 4 stripped instance Show HoleCards where show (HoleCards x y ) = (show x) ++ (show y) -- identical rank pocketPair :: HoleCards -> Bool pocketPair (HoleCards x y) = rank x == rank y -- identical suit suited :: HoleCards -> Bool suited (HoleCards x y) = suit x == suit y -- strongly connected, adjacent -- FIXME: Aces connected :: HoleCards -> Bool connected (HoleCards x y) = 1 == abs ((fromEnum (rank x)) - (fromEnum (rank y))) mergeHoleCards :: [Card] -> HoleCards -> [Card] mergeHoleCards cards (HoleCards x y) = cards ++ holeArray where holeArray = [x, y] data PokerRank = StraightFlush | FourOfAKind | FullHouse | Flush | Straight | ThreeOfAKind | TwoPair | Pair | HighCard deriving (Eq, Bounded, Enum, Ord, Show) -- a complete Hold Em hand along with its rank. Hands may be compared and ordered data PokerHand = PokerHand PokerRank Card Card Card Card Card deriving (Show) instance Eq PokerHand where (==) a b = and $ (ra == rb) : (map (\x -> (fst x) == (snd x)) $ zip cra crb) where ra = pokerHandRank a rb = pokerHandRank b cra = map rank (pokerHandCards a) crb = map rank (pokerHandCards b) instance Ord PokerHand where compare a b = (compare ra rb) `mappend` (mconcat $ map (\x -> compare (fst x) (snd x)) $ zip cra crb) where ra = pokerHandRank a rb = pokerHandRank b cra = map rank (pokerHandCards a) crb = map rank (pokerHandCards b) instance NFData PokerHand where rnf (PokerHand r a b c d e) = r `seq` a `seq` b `seq` c `seq` d `seq` e `seq` () pokerHandRank :: PokerHand -> PokerRank pokerHandRank (PokerHand r _ _ _ _ _) = r pokerHandCards :: PokerHand -> [Card] pokerHandCards (PokerHand _ a b c d e) = [a,b,c,d,e] bestPokerHand :: [Card] -> PokerHand bestPokerHand = fromJust . constructPokerHand -- take a board to choose from, a hand and return the best rank made by that hand on the board pokerRank :: [Card] -> HoleCards -> PokerRank pokerRank board (HoleCards x y) = let cards = x : y : board in pokerHandRank $ bestPokerHand cards -- TODO: possibly broken -- this is a bit interesting. due to the fact that Ace enum value is zero we can't check that -- the interval between the first and last rank is exactly 4 so we instead have a check to see that -- an Ace is present and that the sum of the enum values is exactly what is required by the other -- broadway cards - this could be broken as well...TODO!!! -- isStraight :: [Card] -> Bool isStraight xs = or $ map isLegalInterval possibleHands where uniqueOrderedRanks = nub . sort $ map (fromEnum . rank) xs possibleHands = nChooseK uniqueOrderedRanks 5 isLegalInterval ranks | 0 == (head ranks) = (((last ranks) - (head ranks)) == 4) || (42 == (sum ranks)) | otherwise = ((last ranks) - (head ranks)) == 4 -- generate some hands, return them and the remainder of the deck generateHands :: Deck -> Int -> ([HoleCards],Deck) generateHands deck count = (hands, remainder) where hands = map createHand (take count $ chunkList 2 deck) remainder = drop (count * 2) deck createHand (x:y:[]) = (HoleCards x y) countMultipleRanks :: Int -> [Card] -> Int countMultipleRanks n hand = length multiples where groupedRanks = countRanks . groupRanks $ hand multiples = filter (== n) groupedRanks countPairs :: [Card] -> Int countPairs = countMultipleRanks 2 countTrips :: [Card] -> Int countTrips = countMultipleRanks 3 countQuads :: [Card] -> Int countQuads = countMultipleRanks 4 countRanks :: [[Rank]] -> [Int] countRanks xs = map length xs groupRanks :: [Card] -> [[Rank]] groupRanks xs = group . sort $ (map rank xs) -- TODO: we could make a better version that requires the cards to be sorted groupCardsByRank :: [Card] -> [[Card]] groupCardsByRank xs = groupWith rank xs countSuits :: [Card] -> Int countSuits xs = length (groupSuits xs) groupSuits :: [Card] -> [[Suit]] groupSuits xs = group . sort $ (map suit xs) groupBySuits :: [Card] -> [[Card]] groupBySuits xs = groupWith (\x -> suit x) xs readHoleCards :: String -> Maybe HoleCards readHoleCards str | length str /= 4 = Nothing | isJust c1 && isJust c2 = Just (HoleCards (fromJust c1) (fromJust c2)) | otherwise = Nothing where c1 = readCard $ take 2 str c2 = readCard $ drop 2 str data ShowdownTally = ShowdownTally { win :: Int, tie :: Int, loss :: Int } deriving (Eq, Show) instance Ord ShowdownTally where compare a b = compare ((win a) + (tie a) - (loss a)) ((win b) + (tie b) - (loss b)) instance NFData ShowdownTally where rnf ShowdownTally {win=a, tie=b, loss=c} = a `seq` b `seq` c `seq` () addTally :: ShowdownTally -> ShowdownTally -> ShowdownTally addTally x y = ShowdownTally { win = (win x) + (win y), loss = (loss x) + (loss y), tie = (tie x) + (tie y) } blankTally :: ShowdownTally blankTally = ShowdownTally { win = 0, tie = 0, loss = 0 } newWin :: ShowdownTally newWin = ShowdownTally { win = 1, tie = 0, loss = 0 } newTie :: ShowdownTally newTie = ShowdownTally { win = 0, tie = 1, loss = 0 } newLoss :: ShowdownTally newLoss = ShowdownTally { win = 0, tie = 0, loss = 1 } totalTally :: ShowdownTally -> Int totalTally t = (win t) + (tie t) + (loss t) percentTally :: (Fractional a) => ShowdownTally -> (a,a) percentTally t = (we,te) where pct x = 100.0 * fromRational (x % total) we = pct wint wint = toInteger $ win t te = pct tint tint = toInteger $ tie t total = toInteger $ totalTally t pokerEquity :: [Card] -> [HoleCards] -> [ShowdownTally] pokerEquity deck hs = let hands = pokerHands deck hs in pokerHandsToTally hands pokerHandsToTally :: [PokerHand] -> [ShowdownTally] pokerHandsToTally hs = let best = head $ group $ sort hs bob = head best good = if length best > 1 then newTie else newWin in map (\x -> tallyForHand x bob good newLoss) hs where tallyForHand h c g b = if h == c then g else b pokerHands :: [Card] -> [HoleCards] -> [PokerHand] pokerHands deck hs = hands where cards = map (mergeHoleCards deck) hs hands = map bestPokerHand cards -- so, this is a bit of a lie, it actually doesn't give you ALL poker straight combos. -- It cuts them down by removing repeated ranks that are available. -- Therefore if As and Ah are both in the list the Ah will be discarded. This means -- this cannot be directly used to find straight flushes allPokerStraights :: [Card] -> [[Card]] allPokerStraights xs = straights where cs = nubBy (\a b -> rank a == rank b) $ sort xs combos = nChooseK cs 5 straights = filter isStraight combos allPokerFlushes :: [Card] -> [[Card]] allPokerFlushes xs = minLengthSuits where gs = groupBySuits xs ss = fmap sort gs minLengthSuits = map (\x -> take 5 x ) $ filter (\x -> length x > 4) ss bestPokerFlush :: [Card] -> [Card] bestPokerFlush xs = head ordered where ordered = sortBy comp $ allPokerFlushes xs comp a b = (mconcat $ map (\x -> compare (snd x) (fst x)) $ zip a b) constructPokerHand :: [Card] -> Maybe PokerHand constructPokerHand unsortedCards = let result h = firstThat isJust h hands = [ (constructStraightFlushHand suitedCards), (constructFourOfAKindHand quads cards), (constructFullHouseHand trips pairs), (constructFlushHand suitedCards), (constructStraightHand runningCards), (constructThreeOfAKindHand trips cards), (constructTwoPairHand pairs cards), (constructPairHand pairs cards), (constructHighCardHand cards) ] cards = sort unsortedCards rankedCards = groupCardsByRank cards suitedCards = groupBySuits cards runningCards = groupByRuns $ cards ++ lowAces cards pairs = filter (\x -> 2 == length x) rankedCards trips = filter (\x -> 3 == length x) rankedCards quads = filter (\x -> 4 == length x) rankedCards lowAces xs = map (\x -> (Card LowAce (suit x)) ) $ filter (\x -> (rank x) == Ace) xs in result hands groupByRuns :: [Card] -> [[Card]] groupByRuns cards = groupByBreak 0 breaks uniqueRanks where uniqueRanks = nubBy (\a b -> rank a == rank b) cards breaks = runBreaks uniqueRanks -- convert cards to ranks and find out where discontinuities exist -- this shows us where to split the cards at runBreaks :: [Card] -> [Int] runBreaks [] = [] runBreaks cards = indices where xs = map (fromEnum . rank) cards diffs = map (\(x,y) -> y-x ) $ zip xs (drop 1 xs) diffIndices = zip diffs [1..] breakPoints = filter (\x -> fst x /= 1) diffIndices indices = map snd breakPoints -- group cards by break points groupByBreak :: Int -> [Int] -> [Card] -> [[Card]] groupByBreak start breaks [] = [] groupByBreak start [] xs = [xs] groupByBreak start breaks xs = (fst taken):(groupByBreak break (tail breaks) (snd taken)) where break = head breaks takeCount = break - start taken = splitAt takeCount xs -- Find the best 5-card poker hand based on high card. -- -- PRE: cards is sorted constructHighCardHand :: [Card] -> Maybe PokerHand constructHighCardHand cards = do fiveCards <- takeMay 5 cards let (a:b:c:d:e:_) = fiveCards return (PokerHand HighCard a b c d e) -- Find the best 5-card poker hand based on a pair -- -- PRE: pairs is an array of pairs found in the full set of cards -- PRE: cards is sorted constructPairHand :: [[Card]] -> [Card] -> Maybe PokerHand constructPairHand pairs cards = do pair <- headMay pairs nonPairCards <- return $ cards \\ pair let (a:b:_) = pair (c:d:e:_) = nonPairCards return (PokerHand Pair a b c d e) -- Find the best 5-card poker hand based on two pair -- -- PRE: pairs is an array of pairs found in the full set of cards -- PRE: cards is sorted constructTwoPairHand :: [[Card]] -> [Card] -> Maybe PokerHand constructTwoPairHand pairs cards = do twoPair <- fmap concat $ takeMay 2 pairs nonPairCards <- return $ cards \\ twoPair let (a:b:c:d:_) = twoPair (e:_) = nonPairCards return (PokerHand TwoPair a b c d e) -- Find the best 5-card poker hand based on three of a kind -- -- PRE: trips is an array of trips found in the full set of cards -- PRE: cards is sorted constructThreeOfAKindHand :: [[Card]] -> [Card] -> Maybe PokerHand constructThreeOfAKindHand trips cards = do set <- headMay trips nonSetCards <- return $ cards \\ set let (a:b:c:_) = set (d:e:_) = nonSetCards return (PokerHand ThreeOfAKind a b c d e) -- Find the best 5-card poker hand based on straight -- -- PRE: runs is an array of arrays of cards that form contiguous sequences constructStraightHand :: [[Card]] -> Maybe PokerHand constructStraightHand runs = do highestRun <- headMay $ filter (\x -> length x > 4 ) runs let (a:b:c:d:e:_) = highestRun return (PokerHand Straight a b c d e) -- Find the best 5-card poker hand based on flush -- -- PRE: suited is an array of arrays of cards that are grouped by suit -- TODO: this currently will only work for hands where only one flush is possible constructFlushHand :: [[Card]] -> Maybe PokerHand constructFlushHand suited = do flush <- headMay $ filter (\x -> length x > 4 ) suited let (a:b:c:d:e:_) = flush return (PokerHand Flush a b c d e) -- Find the best 5-card poker hand based on full house -- -- PRE: trips is an array of trips found in the full set of cards -- PRE: pairs is an array of pairs found in the full set of cards constructFullHouseHand :: [[Card]] -> [[Card]] -> Maybe PokerHand constructFullHouseHand trips pairs = do set <- headMay trips pair <- headMay pairs let (a:b:c:_) = set (d:e:_) = pair return (PokerHand FullHouse a b c d e) -- Find the best 5-card poker hand based on four of a kind -- -- PRE: quads is an array of trips found in the full set of cards -- PRE: cards is sorted constructFourOfAKindHand :: [[Card]] -> [Card] -> Maybe PokerHand constructFourOfAKindHand quads cards = do quad <- headMay quads nonQuadCards <- return $ cards \\ quad let (a:b:c:d:_) = quad e = head nonQuadCards return (PokerHand FourOfAKind a b c d e) -- Find the best 5-card poker hand based on straight flush -- -- PRE: suited is an array of arrays of cards that are grouped by suit -- TODO: this currently will only work for hands where only one flush is possible constructStraightFlushHand :: [[Card]] -> Maybe PokerHand constructStraightFlushHand suited = do flush <- headMay $ filter (\x -> length x > 4 ) suited let cards = flush ++ lowAces flush lowAces xs = map (\x -> (Card LowAce (suit x)) ) $ filter (\x -> (rank x) == Ace) xs runningCards = groupByRuns cards highestRun <- headMay $ filter (\x -> length x > 4 ) runningCards let (a:b:c:d:e:_) = highestRun return (PokerHand StraightFlush a b c d e) -- Generate all possible unique HoldEm community boards from a deck provided generateBoards :: Int -> [Card] -> [[Card]] generateBoards boardLength deck = let initial = Just $ DC.choose (length deck) boardLength in unfoldr go initial where go nck | isJust nck = Just (board deck (DC.elems (fromJust nck)), DC.next (fromJust nck)) | otherwise = Nothing board c i = map (\x -> c !! x) i -- TODO: create a data type for this handShape :: HoleCards -> String handShape hand = concat [s, " ", c] where s = case (suited hand) of True -> "suited" False -> "off-suit" c = case (connected hand) of True -> "connected" False -> "" -- generate board number N out of the deck available -- N is zero-indexed and should not be larger that the -- number of possible combinations generateBoard :: [Card] -> Int -> [Card] generateBoard deck n = map (\i -> deck !! i) $ nckValues n 5
wiggly/functional-pokering
src/Poker.hs
mit
15,558
0
17
4,138
5,032
2,663
2,369
297
3
{-# LANGUAGE PackageImports #-} module Prelude( module CorePrelude ) where import CorePrelude
zsedem/haskell-playground
human-prelude/src/Prelude.hs
mit
98
0
4
16
14
10
4
4
0
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ForeignFunctionInterface #-} #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) {-# LANGUAGE JavaScriptFFI #-} #endif ----------------------------------------------------------------------------- -- -- Module : Language.Javascript.JSaddle.Object -- Copyright : (c) Hamish Mackenzie -- License : MIT -- -- Maintainer : Hamish Mackenzie <Hamish.K.Mackenzie@googlemail.com> -- -- | Interface to JavaScript object -- ----------------------------------------------------------------------------- module Language.Javascript.JSaddle.Object ( JSObjectRef , MakeObjectRef(..) -- * Property lookup , (!) , (!!) , js , JSF(..) , jsf , js0 , js1 , js2 , js3 , js4 , js5 , jsg -- * Setting the value of a property , (<#) -- * Calling JavaSctipt , (#) , new , call , obj -- * Calling Haskell From JavaScript , function , fun , JSCallAsFunction(..) -- ** Object Constructors -- | There is no good way to support calling haskell code as a JavaScript -- constructor for the same reason that the return type of -- 'JSCallAsFunction' is 'JSUndefined'. -- -- Instead of writing a constructor in Haskell write a function -- that takes a continuation. Create the JavaScript object -- and pass it to the continuation. -- * Arrays , array -- * Global Object , global -- * Enumerating Properties , propertyNames -- * Low level , objCallAsFunction , objCallAsConstructor ) where import Prelude hiding ((!!)) import Language.Javascript.JSaddle.Types (JSPropertyNameArrayRef, JSStringRef, JSObjectRef, JSValueRefRef, JSValueRef, JSContextRef, Index) import Foreign.C.Types (CSize(..), CULong(..), CUInt(..), CULLong(..)) #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.Types (nullRef, castRef, JSArray, JSFun) import GHCJS.Foreign (newObj, toArray, fromArray, syncCallback2, ForeignRetention(..)) import Control.Monad (liftM) import Control.Applicative ((<$>)) #else import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSObjectRef (jsobjectmake, jspropertynamearraygetnameatindex, jspropertynamearraygetcount, jsobjectcopypropertynames, jsobjectsetpropertyatindex, jsobjectgetpropertyatindex, jsobjectcallasconstructor, jsobjectmakearray, jsobjectcallasfunction, jsobjectgetproperty, jsobjectsetproperty, JSPropertyAttributes, JSObjectCallAsFunctionCallback, jsobjectmakefunctionwithcallback, JSObjectCallAsFunctionCallback') import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSValueRef (jsvaluemakeundefined) import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSContextRef (jscontextgetglobalobject) import Foreign (peekArray, nullPtr, withArrayLen) #endif import Language.Javascript.JSaddle.Exception (rethrow) import Language.Javascript.JSaddle.Value (JSUndefined, valMakeUndefined, valToObject) import Language.Javascript.JSaddle.PropRef (JSPropRef(..)) import Language.Javascript.JSaddle.Classes (MakeValueRef(..), MakeStringRef(..), MakeArgRefs(..), MakePropRef(..), MakeObjectRef(..)) import Language.Javascript.JSaddle.Monad (JSM) import Control.Monad.Trans.Reader (runReaderT, ask) import Control.Monad.IO.Class (MonadIO(..)) import qualified Control.Exception as E (catch) import Control.Exception (SomeException) import qualified Data.Text as T (pack) import Foreign.Storable (Storable(..)) import Language.Javascript.JSaddle.Properties import Control.Lens (IndexPreservingGetter, to, (^.)) import Language.Javascript.JSaddle.String (textToStr) -- | If we already have a JSObjectRef we are fine instance MakeObjectRef JSObjectRef where makeObjectRef = return -- | JSObjectRef can be made by evaluating a function in 'JSM' as long -- as it returns something we can make into a JSObjectRef. instance MakeObjectRef v => MakeObjectRef (JSM v) where makeObjectRef v = v >>= makeObjectRef -- | Lookup a property based on its name. This function just constructs a JSPropRef -- the lookup is delayed until we use the JSPropRef. This makes it a bit lazy compared -- to JavaScript's @.@ operator. -- -- >>> testJSaddle $ eval "'Hello World'.length" -- >>> testJSaddle $ val "Hello World" ! "length" -- 11 (!) :: (MakeObjectRef this, MakeStringRef name) => this -- ^ Object to look on -> name -- ^ Name of the property to find -> JSM JSPropRef -- ^ Property reference this ! name = do rthis <- makeObjectRef this return (JSPropRef rthis rname) where rname = makeStringRef name -- | Lookup a property based on its index. This function just constructs a JSPropRef -- the lookup is delayed until we use the JSPropRef. This makes it a bit lazy compared -- to JavaScript's @[]@ operator. -- -- >>> testJSaddle $ eval "'Hello World'[6]" -- >>> testJSaddle $ val "Hello World" !! 6 -- W (!!) :: (MakeObjectRef this) => this -- ^ Object to look on -> Index -- ^ Index of the property to lookup -> JSM JSPropRef -- ^ Property reference this !! index = do rthis <- makeObjectRef this return (JSPropIndexRef rthis index) -- | Makes a getter for a particular property name. -- -- > js name = to (!name) -- -- >>> testJSaddle $ eval "'Hello World'.length" -- >>> testJSaddle $ val "Hello World" ^. js "length" -- 11 js :: (MakeObjectRef s, MakeStringRef name) => name -- ^ Name of the property to find -> IndexPreservingGetter s (JSM JSPropRef) js name = to (!name) -- | Java script function applications have this type type JSF = MakeObjectRef o => IndexPreservingGetter o (JSM JSValueRef) -- | Handy way to call a function -- -- > jsf name = js name . to (# args) -- -- >>> testJSaddle $ val "Hello World" ^. jsf "indexOf" ["World"] -- 6 jsf :: (MakeStringRef name, MakeArgRefs args) => name -> args -> JSF jsf name args = function . to (# args) where function = js name -- | Handy way to call a function that expects no arguments -- -- > js0 name = jsf name () -- -- >>> testJSaddle $ val "Hello World" ^. js0 "toLowerCase" -- hello world js0 :: (MakeStringRef name) => name -> JSF js0 name = jsf name () -- | Handy way to call a function that expects one argument -- -- > js1 name a0 = jsf name [a0] -- -- >>> testJSaddle $ val "Hello World" ^. js1 "indexOf" "World" -- 6 js1 :: (MakeStringRef name, MakeValueRef a0) => name -> a0 -> JSF js1 name a0 = jsf name [a0] -- | Handy way to call a function that expects two arguments js2 :: (MakeStringRef name, MakeValueRef a0, MakeValueRef a1) => name -> a0 -> a1 -> JSF js2 name a0 a1 = jsf name (a0, a1) -- | Handy way to call a function that expects three arguments js3 :: (MakeStringRef name, MakeValueRef a0, MakeValueRef a1, MakeValueRef a2) => name -> a0 -> a1 -> a2 -> JSF js3 name a0 a1 a2 = jsf name (a0, a1, a2) -- | Handy way to call a function that expects four arguments js4 :: (MakeStringRef name, MakeValueRef a0, MakeValueRef a1, MakeValueRef a2, MakeValueRef a3) => name -> a0 -> a1 -> a2 -> a3 -> JSF js4 name a0 a1 a2 a3 = jsf name (a0, a1, a2, a3) -- | Handy way to call a function that expects five arguments js5 :: (MakeStringRef name, MakeValueRef a0, MakeValueRef a1, MakeValueRef a2, MakeValueRef a3, MakeValueRef a4) => name -> a0 -> a1 -> a2 -> a3 -> a4 -> JSF js5 name a0 a1 a2 a3 a4 = jsf name (a0, a1, a2, a3, a4) -- | Handy way to get and hold onto a reference top level javascript -- -- >>> testJSaddle $ eval "w = console; w.log('Hello World')" -- >>> testJSaddle $ do w <- jsg "console"; w ^. js "log" # ["Hello World"] -- 11 jsg :: MakeStringRef a => a -> JSM JSPropRef jsg name = global ! name -- | Call a JavaScript function -- -- >>> testJSaddle $ eval "'Hello World'.indexOf('World')" -- >>> testJSaddle $ val "Hello World" ! "indexOf" # ["World"] -- 6 infixr 2 # (#) :: (MakePropRef prop, MakeArgRefs args) => prop -> args -> JSM JSValueRef prop # args = do rprop <- makePropRef prop (this, f) <- objGetProperty' rprop rethrow $ objCallAsFunction f this args -- | Call a JavaScript function -- -- >>> testJSaddle $ eval "var j = {}; j.x = 1; j.x" -- >>> testJSaddle $ do {j <- eval "({})"; j!"x" <# 1; j!"x"} -- 1 infixr 0 <# (<#) :: (MakePropRef prop, MakeValueRef val) => prop -- ^ Property to set -> val -- ^ Value to set it to -> JSM JSPropRef -- ^ Reference to the property set prop <# val = do p <- makePropRef prop objSetProperty p val return p -- | Use this to create a new JavaScript object -- -- If you pass more than 7 arguments to a constructor for a built in -- JavaScript type (like Date) then this function will fail. -- -- >>> testJSaddle $ new "Date" (2013, 1, 1) -- Fri Feb 01 2013 00:00:00 GMT+1300 (NZDT) new :: (MakeObjectRef constructor, MakeArgRefs args) => constructor -> args -> JSM JSValueRef new constructor args = do f <- makeObjectRef constructor rethrow $ objCallAsConstructor f args -- | Call function with a given @this@. In most cases you should use '#'. -- -- >>> testJSaddle $ eval "(function(){return this;}).apply('Hello', [])" -- >>> testJSaddle $ do { test <- eval "(function(){return this;})"; call test (val "Hello") () } -- Hello call :: (MakeObjectRef function, MakeObjectRef this, MakeArgRefs args) => function -> this -> args -> JSM JSValueRef call function this args = do rfunction <- makeObjectRef function rthis <- makeObjectRef this rethrow $ objCallAsFunction rfunction rthis args -- | Make an empty object using the default constuctor -- -- >>> testJSaddle $ eval "var a = {}; a.x = 'Hello'; a.x" -- >>> testJSaddle $ do { a <- obj; a ^. js "x" <# "Hello"; a ^. js "x" } -- Hello obj :: JSM JSObjectRef #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) obj = liftIO $ newObj #else obj = do gctxt <- ask liftIO $ jsobjectmake gctxt nullPtr nullPtr #endif -- | Type used for Haskell functions called from JavaScript. type JSCallAsFunction = JSValueRef -- ^ Function object -> JSValueRef -- ^ this -> [JSValueRef] -- ^ Function arguments -> JSM JSUndefined -- ^ Only 'JSUndefined' can be returned because -- the function may need to be executed in a -- different thread. If you need to get a -- value out pass in a continuation function -- as an argument and invoke it from haskell. -- | Short hand @::JSCallAsFunction@ so a haskell function can be passed to -- a to a JavaScipt one. -- -- >>> testJSaddle $ eval "(function(f) {f('Hello');})(function (a) {console.log(a)})" -- >>> testJSaddle $ call (eval "(function(f) {f('Hello');})") global [fun $ \ _ _ args -> valToText (head args) >>= (liftIO . putStrLn . T.unpack) ] -- Hello -- undefined fun :: JSCallAsFunction -> JSCallAsFunction fun = id #if (!defined(ghcjs_HOST_OS) || !defined(USE_JAVASCRIPTFFI)) && defined(USE_WEBKIT) foreign import ccall "wrapper" mkJSObjectCallAsFunctionCallback :: JSObjectCallAsFunctionCallback' -> IO JSObjectCallAsFunctionCallback #endif -- ^ Make a JavaScript function object that wraps a Haskell function. function :: MakeStringRef name => name -- ^ Name of the function -> JSCallAsFunction -- ^ Haskell function to call -> JSM JSObjectRef -- ^ Returns a JavaScript function object that will -- call the Haskell one when it is called #if defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI) function name f = liftIO $ do callback <- syncCallback2 AlwaysRetain True $ \this args -> do rargs <- fromArray args runReaderT (f this this rargs) () -- TODO pass function object through makeFunctionWithCallback (makeStringRef name) callback foreign import javascript unsafe "$r = function () { $2(this, arguments); }" makeFunctionWithCallback :: JSStringRef -> JSFun (JSValueRef -> JSValueRefRef -> IO ()) -> IO JSObjectRef #elif defined(USE_WEBKIT) function name f = do gctxt <- ask callback <- liftIO $ mkJSObjectCallAsFunctionCallback wrap liftIO $ jsobjectmakefunctionwithcallback gctxt (makeStringRef name) callback where wrap ctx fobj this argc argv exception = do args <- peekArray (fromIntegral argc) argv (`runReaderT` ctx) $ f fobj this args >>= makeValueRef `E.catch` \(e :: SomeException) -> do str <- runReaderT (makeValueRef . T.pack $ show e) ctx poke exception str jsvaluemakeundefined ctx #else function = undefined #endif -- | A callback to Haskell can be used as a JavaScript value. This will create -- an anonymous JavaScript function object. Use 'function' to create one with -- a name. instance MakeValueRef JSCallAsFunction where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) makeValueRef = function (nullRef:: JSStringRef) #else makeValueRef = function (nullPtr:: JSStringRef) #endif instance MakeArgRefs JSCallAsFunction where makeArgRefs f = do #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) rarg <- function (nullRef:: JSStringRef) f #else rarg <- function (nullPtr:: JSStringRef) f #endif return [rarg] makeArray :: MakeArgRefs args => args -> JSValueRefRef -> JSM JSObjectRef #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) makeArray args exceptions = makeArgRefs args >>= liftM castRef . liftIO . toArray #else makeArray args exceptions = do gctxt <- ask rargs <- makeArgRefs args liftIO $ withArrayLen rargs $ \ len ptr -> jsobjectmakearray gctxt (fromIntegral len) ptr exceptions #endif -- | Make an JavaScript array from a list of values -- -- >>> testJSaddle $ eval "['Hello', 'World'][1]" -- >>> testJSaddle $ array ["Hello", "World"] !! 1 -- World -- >>> testJSaddle $ eval "['Hello', null, undefined, true, 1]" -- >>> testJSaddle $ array ("Hello", JSNull, (), True, 1.0::Double) -- Hello,,,true,1 array :: MakeArgRefs args => args -> JSM JSObjectRef array = rethrow . makeArray -- | JavaScript's global object global :: JSM JSObjectRef #if defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI) global = liftIO js_window foreign import javascript unsafe "$r = window" js_window :: IO JSObjectRef #elif defined(USE_WEBKIT) global = ask >>= (liftIO . jscontextgetglobalobject) #else global = undefined #endif -- | Get an array containing the property names present on a given object #if (!defined(ghcjs_HOST_OS) || !defined(USE_JAVASCRIPTFFI)) && defined(USE_WEBKIT) copyPropertyNames :: MakeObjectRef this => this -> JSM JSPropertyNameArrayRef copyPropertyNames this = do gctxt <- ask rthis <- makeObjectRef this liftIO $ jsobjectcopypropertynames gctxt rthis -- | Get the number of names in a property name array propertyNamesCount :: MonadIO m => JSPropertyNameArrayRef -> m CSize propertyNamesCount names = liftIO $ jspropertynamearraygetcount names -- | Get a name out of a property name array propertyNamesAt :: MonadIO m => JSPropertyNameArrayRef -> CSize -> m JSStringRef propertyNamesAt names index = liftIO $ jspropertynamearraygetnameatindex names index -- | Convert property array to a list propertyNamesList :: MonadIO m => JSPropertyNameArrayRef -> m [JSStringRef] propertyNamesList names = do count <- propertyNamesCount names mapM (propertyNamesAt names) $ enumFromTo 0 (count - 1) #endif -- | Get a list containing the property names present on a given object propertyNames :: MakeObjectRef this => this -> JSM [JSStringRef] #if defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI) propertyNames this = makeObjectRef this >>= liftIO . js_propertyNames >>= liftIO . fromArray foreign import javascript unsafe "$r = []; h$forIn($1, function(n){$r.push(n);})" js_propertyNames :: JSObjectRef -> IO (JSArray a) #elif defined(USE_WEBKIT) propertyNames this = copyPropertyNames this >>= propertyNamesList #else propertyNames = undefined #endif -- | Get a list containing references to all the properties present on a given object properties :: MakeObjectRef this => this -> JSM [JSPropRef] properties this = propertyNames this >>= mapM (this !) -- | Call a JavaScript object as function. Consider using '#'. objCallAsFunction :: MakeArgRefs args => JSObjectRef -> JSObjectRef -> args -> JSValueRefRef -> JSM JSValueRef #if defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI) objCallAsFunction function this args exceptions = do rargs <- makeArgRefs args >>= liftIO . toArray liftIO $ js_apply function this rargs exceptions foreign import javascript unsafe "try { $r = $1.apply($2, $3) } catch(e) { $4[0] = e }" js_apply :: JSObjectRef -> JSObjectRef -> JSValueRefRef -> JSValueRefRef -> IO JSValueRef #elif defined(USE_WEBKIT) objCallAsFunction function this args exceptions = do gctxt <- ask rargs <- makeArgRefs args liftIO $ withArrayLen rargs $ \ largs pargs -> jsobjectcallasfunction gctxt function this (fromIntegral largs) pargs exceptions #else objCallAsFunction = undefined #endif -- | Call a JavaScript object as a constructor. Consider using 'new'. -- -- If you pass more than 7 arguments to a constructor for a built in -- JavaScript type (like Date) then this function will fail. objCallAsConstructor :: MakeArgRefs args => JSObjectRef -> args -> JSValueRefRef -> JSM JSValueRef #if defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI) objCallAsConstructor function args exceptions = do rargs <- makeArgRefs args >>= liftIO . toArray liftIO $ js_new function rargs exceptions foreign import javascript unsafe "\ try {\ switch($2.length) {\ case 0 : $r = new $1(); break;\ case 1 : $r = new $1($2[0]); break;\ case 2 : $r = new $1($2[0],$2[1]); break;\ case 3 : $r = new $1($2[0],$2[1],$2[2]); break;\ case 4 : $r = new $1($2[0],$2[1],$2[2],$2[3]); break;\ case 5 : $r = new $1($2[0],$2[1],$2[2],$2[3],$2[4]); break;\ case 6 : $r = new $1($2[0],$2[1],$2[2],$2[3],$2[4],$2[5]); break;\ case 7 : $r = new $1($2[0],$2[1],$2[2],$2[3],$2[4],$2[5],$2[6]); break;\ default:\ var ret;\ var temp = function() {\ ret = $1.apply(this, $2);\ };\ temp.prototype = $1.prototype;\ var i = new temp();\ if(ret instanceof Object)\ return ret;\ i.constructor = $1;\ return i;\ }\ }\ catch(e) {\ $3[0] = e;\ }" js_new :: JSObjectRef -> JSValueRefRef -> JSValueRefRef -> IO JSValueRef #elif defined(USE_WEBKIT) objCallAsConstructor function args exceptions = do gctxt <- ask rargs <- makeArgRefs args liftIO $ withArrayLen rargs $ \ largs pargs -> jsobjectcallasconstructor gctxt function (fromIntegral largs) pargs exceptions #else objCallAsConstructor = undefined #endif
jmillikan/jsaddle
src/Language/Javascript/JSaddle/Object.hs
mit
19,621
195
10
4,340
2,851
1,771
1,080
180
1
module Player.Human (playerHuman) where import Types import Misc playerHuman :: Player playerHuman = Player humanMove "Human" where humanMove _ _ = read <$> prompt "Write your move! (i,j) with 1<=i,j<=3 "
8Gitbrix/gomoku
src/Player/Human.hs
mit
217
0
8
43
51
28
23
6
1
{- -} pe5 :: Integer -> Integer pe5 n | n < 2 = 1 | otherwise = foldr1 lcm [2..n] main :: IO() main = do print $ pe5 20
kittttttan/pe
haskell/pe5.hs
mit
139
0
8
50
73
35
38
7
1
{-# LANGUAGE OverloadedStrings #-} module Day12 (day12, day12', run) where import Data.Aeson ( Value ( Array , Number , Object , String ) , decode' ) import Data.ByteString.Lazy.Char8 (pack) import Data.Foldable (foldl) import Data.Maybe (fromMaybe) import Data.Scientific import Data.Text (Text) sumJson :: Value -> Scientific sumJson (Object o) = foldl addNumbers 0 o sumJson (Array a) = foldl addNumbers 0 a sumJson (Number n) = n sumJson _ = 0 addNumbers :: Scientific -> Value -> Scientific addNumbers x o@(Object _) = x + sumJson o addNumbers x a@(Array _) = x + sumJson a addNumbers x (Number n) = x + n addNumbers x _ = x sumJson' :: Value -> Scientific sumJson' (Object o) = fromMaybe 0 $ foldl addNumbers' (Just 0) o sumJson' (Array a) = foldl addNumbers'' 0 a sumJson' (Number n) = n sumJson' _ = 0 addNumbers' :: Maybe Scientific -> Value -> Maybe Scientific addNumbers' Nothing _ = Nothing addNumbers' x (String s) = if s == "red" then Nothing else x addNumbers' x v = fmap (`addNumbers''` v) x addNumbers'' :: Scientific -> Value -> Scientific addNumbers'' x o@(Object _) = x + sumJson' o addNumbers'' x a@(Array _) = x + sumJson' a addNumbers'' x (Number n) = x + n addNumbers'' x _ = x day12 :: String -> Scientific day12 input = maybe (-1) sumJson (decode' . pack $ input) day12' :: String -> Scientific day12' input = maybe (-1) sumJson' (decode' . pack $ input) -- Input run :: IO () run = do putStrLn "Day 12 results: " input <- readFile "inputs/day12.txt" putStrLn $ " " ++ show (day12 input) putStrLn $ " " ++ show (day12' input)
brianshourd/adventOfCode2015
src/Day12.hs
mit
1,710
0
10
439
665
347
318
48
2
{-# LANGUAGE Arrows #-} module Game.Client.Components.Projectiles where import FRP.Yampa as Yampa import FRP.Yampa.Geometry import Graphics.UI.SDL as SDL import Graphics.UI.SDL.Events as SDL.Events import Graphics.UI.SDL.Keysym as SDL.Keysym import Data.Maybe import Numeric.IEEE import Game.Shared.Types import Game.Shared.Networking import Game.Shared.Object import Game.Shared.Arrows import Game.Client.Object import Game.Client.Resources import Game.Client.Input import Game.Client.Graphics import Game.Client.Networking ------------------------- -- Tracking projectile -- ------------------------- -- |Input structure for the tracking projectile component data TrackingProjectileInput = TrackingProjectileInput { tpiAllCollisions :: [GameObject] -- ^List of objects colliding with the projectile ,tpiAllObjects :: [GameObject] -- ^All game objects in the scene ,tpiSpeed :: Double -- ^The speed the projectile should travel at ,tpiCurrPos :: Vector2D -- ^The current position of the projectile } -- |Output structure for the tracking projectile component data TrackingProjectileOutput = TrackingProjectileOutput { tpoHitTargetEvent :: Yampa.Event () -- ^Event fired when the projectile has hit its target ,tpoMoveDelta :: Vector2D -- ^Amount to move by } -- |Component for a projectile that should track and chase a specific object trackingProjectile :: GameObject -- ^The projectile object -> Time -- ^The maximum lifetime of the projectile -> SF TrackingProjectileInput TrackingProjectileOutput trackingProjectile obj maxLifeTime = proc input -> do -- Move let isColliding = isJust (findObjById (goTarget obj) (tpiAllCollisions input)) objToTrack = findObjById (goTarget obj) (tpiAllObjects input) hasTarget = isJust objToTrack targetObj = maybe basicGameObject (id) objToTrack targetPos = middleOfObject targetObj moveDelta = (tpiSpeed input) *^ (normalize (targetPos ^-^ (tpiCurrPos input))) -- Handle collisions collisionEvent <- edge -< isColliding targetLostEvent <- edge -< not hasTarget maxLifeTimeReachedEvent <- delayEvent maxLifeTime <<< now () -< () let hitTargetEvent = foldl (lMerge) collisionEvent [targetLostEvent, maxLifeTimeReachedEvent] -- Return object state returnA -< TrackingProjectileOutput { tpoHitTargetEvent = hitTargetEvent, tpoMoveDelta = moveDelta } ------------------------- -- Directional projectile -- ------------------------- -- |Input structure for the directional projectile data DirectionalProjectileInput = DirectionalProjectileInput { dpiAllCollisions :: [GameObject] -- ^A list of objects colliding with the projectile ,dpiAllObjects :: [GameObject] -- ^List of all objects within the scene ,dpiSpeed :: Double -- ^The speed the projectile should travel at ,dpiCurrPos :: Vector2D -- ^Current position of the projectile } -- |Output structure for the directional projectile data DirectionalProjectileOutput = DirectionalProjectileOutput { dpoHitTargetEvent :: Yampa.Event () -- ^Event fired when the projectile hits an object ,dpoMoveDelta :: Vector2D -- ^Amount to move by } -- |A projectile that moves in a fixed direction directionalProjectile :: GameTeam -- ^The enemy team -> GameObject -- ^The projectile object -> Time -- ^Maximum lifetime of the projectile -> SF DirectionalProjectileInput DirectionalProjectileOutput directionalProjectile enemyTeam obj maxLifeTime = proc input -> do -- Move let isColliding = isJust (findObjByTeam enemyTeam (filter (\obj -> not (goIsDead obj)) (dpiAllCollisions input))) moveDelta = (dpiSpeed input) *^ (normalize (goTargetDirection obj)) -- Handle collisions collisionEvent <- edge -< isColliding maxLifeTimeReachedEvent <- delayEvent maxLifeTime <<< now () -< () let hitTargetEvent = lMerge collisionEvent maxLifeTimeReachedEvent -- Return object state returnA -< DirectionalProjectileOutput { dpoHitTargetEvent = hitTargetEvent, dpoMoveDelta = moveDelta }
Mattiemus/LaneWars
Game/Client/Components/Projectiles.hs
mit
4,289
2
20
914
725
414
311
64
1
-- Copyright © 2012 Julian Blake Kongslie <jblake@omgwallhack.org> -- Licensed under the MIT license. {-# LANGUAGE Arrows #-} module Source.HPFanficArchiveCom ( fetchHPFanficArchiveCom , infoHPFanficArchiveCom ) where import Data.DateTime import Data.Char import Data.List import Data.List.Split import Text.Regex.Posix import Text.XML.HXT.Cache import Text.XML.HXT.Core import Text.XML.HXT.HTTP import qualified Text.XML.HXT.DOM.XmlNode as XN fetchHPFanficArchiveCom :: String -> IOStateArrow s b XmlTree fetchHPFanficArchiveCom storyID = proc _ -> do (title, author, date) <- fetchAuxilliary storyID -< () sections <- listA $ fetchChapter storyID 1 -< () root [] [ mkelem "FictionBook" [sattr "xmlns" "http://www.gribuser.ru/xml/fictionbook/2.0"] [ selem "description" [ selem "title-info" [ selem "author" [ selem "nickname" [ txt author ] ] , selem "book-title" [ txt title ] ] , selem "document-info" [ selem "author" [ selem "nickname" [ txt "jblake" ] ] , selem "date" [ txt $ formatDateTime "%F" date ] , selem "program-used" [ txt "ff" ] ] ] , eelem "body" >>> setChildren sections ] ] -<< () infoHPFanficArchiveCom :: String -> IOStateArrow s b (String, String, DateTime) infoHPFanficArchiveCom = fetchAuxilliary downloadXML :: String -> Int -> IOStateArrow s b XmlTree downloadXML storyID chapter = proc _ -> do readDocument -- We use a cache because the auxilliary would otherwise require a separate fetch. [ withCache "cache" 3600 False , withHTTP [] , withInputEncoding isoLatin1 , withParseHTML True , withStrictInput True , withWarnings False ] $ uri -< () where uri = "http://www.hpfanficarchive.com/stories/viewstory.php?action=printable&sid=" ++ storyID ++ "&chapter=" ++ show chapter fetchAuxilliary :: String -> IOStateArrow s b (String, String, DateTime) fetchAuxilliary storyID = proc _ -> do xml <- downloadXML storyID 1 -< () title <- storyTitle -< xml author <- storyAuthor -< xml date <- updateDate -< xml returnA -< (title, author, date) fetchChapter :: String -> Int -> IOStateArrow s b XmlTree fetchChapter storyID chapter = proc _ -> do xml <- downloadXML storyID chapter -< () title <- single $ chapterTitle <+> constA ("Chapter " ++ show chapter) -< xml titleE <- selem "title" [ selem "p" [ mkText ] ] -< title body <- bodyHTML -< xml bodyEs <- listA $ processBottomUp formatBody -< body case bodyEs of [] -> zeroArrow -< () _ -> do section <- eelem "section" >>> setChildren (titleE : bodyEs) -<< () remainder <- listA $ fetchChapter storyID $ chapter + 1 -< xml unlistA -< section : remainder storyTitle :: IOStateArrow s XmlTree String storyTitle = single $ deepest $ hasName "div" >>> hasAttrValue "id" (== "pagetitle") /> hasName "a" >>> hasAttrValue "href" (isPrefixOf "viewstory.php") /> getText storyAuthor :: IOStateArrow s XmlTree String storyAuthor = single $ deepest $ hasName "div" >>> hasAttrValue "id" (== "pagetitle") /> hasName "a" >>> hasAttrValue "href" (isPrefixOf "viewuser.php") /> getText updateDate :: IOStateArrow s XmlTree DateTime updateDate = single $ deepest $ hasName "div" >>> hasAttrValue "class" (== "infobox") /> (listA $ deep getText) >>> arr concat >>> (matchUpdated <+> matchPublished) matchUpdated :: IOStateArrow s String DateTime matchUpdated = proc text -> do res <- arr (\t -> getAllTextSubmatches $ t =~ "Updated: (January|February|March|April|May|June|July|August|September|October|November|December) ([0-9]{1,2}), ([0-9]{4})") -< text case res of [_,month,day,year] -> do returnA -< fromGregorian' (read year) (parseMonth month) (read day) _ -> do none -< () matchPublished :: IOStateArrow s String DateTime matchPublished = proc text -> do res <- arr (\t -> getAllTextSubmatches $ t =~ "Published: (January|February|March|April|May|June|July|August|September|October|November|December) ([0-9]{1,2}), ([0-9]{4})") -< text case res of [_,month,day,year] -> returnA -< fromGregorian' (read year) (parseMonth month) (read day) _ -> none -< () parseMonth :: String -> Int parseMonth "January" = 1 parseMonth "February" = 2 parseMonth "March" = 3 parseMonth "April" = 4 parseMonth "May" = 5 parseMonth "June" = 6 parseMonth "July" = 7 parseMonth "August" = 8 parseMonth "September" = 9 parseMonth "October" = 10 parseMonth "November" = 11 parseMonth "December" = 12 parseMonth m = error $ "parseMonth called with invalid month: " ++ show m chapterTitle :: IOStateArrow s XmlTree String chapterTitle = deepest $ hasName "div" >>> hasAttrValue "class" (== "chaptertitle") /> getText >>> arr (head . splitOn " by ") bodyHTML :: IOStateArrow s XmlTree XmlTree bodyHTML = deepest $ hasName "div" >>> hasAttrValue "class" (== "chapter") formatBody :: IOStateArrow s XmlTree XmlTree formatBody = proc n -> do res <- listA $ catA -- Primitive nodes that we copy directly. [ isBlob , isCdata , isCharRef , isEntityRef , isText -- Horizontal rules are replaced. , hasName "hr" >>> proc _ -> eelem "empty-line" -< () -- Markup nodes that we rewrite as a different type. , hasName "strong" >>> listA getChildren >>> proc cs -> eelem "strong" >>> setChildren cs -<< () , hasName "em" >>> listA getChildren >>> proc cs -> eelem "emphasis" >>> setChildren cs -<< () -- We have to do some special handling to break paragraphs up on <br/> nodes. , hasName "p" >>> listA getChildren >>> proc cs -> catA [ eelem "p" >>> setChildren cs' | cs' <- splitWhen (\n -> XN.getLocalPart n == Just "br") cs, not $ null cs' ] -<< () -- Because we are processing bottom-up, in order for the above to work we need to pass <br/> nodes through. , hasName "br" >>> proc _ -> eelem "br" -< () -- Markup nodes that we just ditch and use the children from. , hasName "div" >>> getChildren ] -< n -- If we didn't get any acceptable result from processing this node, then ditch it and try to process its children. case res of --[] -> (getName >>> arr ("unrecognized node: " ++) >>> mkCmt) <+> getChildren -< n [] -> getChildren -< n _ -> unlistA -< res
jblake/fanfiction
src/Source/HPFanficArchiveCom.hs
mit
6,523
12
23
1,559
1,799
904
895
134
2
module Demo3 where import Probability model = do i <- bernoulli 0.5 y <- normal 0.0 1.0 z <- exponential 0.1 let x = if i == 1 then y else z return ["x" %=% x] main = do mcmc model
bredelings/BAli-Phy
tests/prob_prog/if-then-else/1/Demo3.hs
gpl-2.0
216
0
11
76
89
43
46
10
2
{-# LANGUAGE PatternSynonyms, NoMonomorphismRestriction, OverloadedStrings, LambdaCase, EmptyCase #-} {-# LANGUAGE TemplateHaskell, QuasiQuotes, ScopedTypeVariables, PolyKinds, UndecidableInstances, DataKinds, DefaultSignatures #-} {-# OPTIONS -fno-warn-unticked-promoted-constructors #-} module Database.Design.Ampersand.ECA2SQL.TSQLCombinators ( module Database.Design.Ampersand.ECA2SQL.TSQLCombinators ) where import Database.Design.Ampersand.ECA2SQL.TypedSQL hiding (In) import Database.Design.Ampersand.ECA2SQL.Utils hiding (Not) import Database.Design.Ampersand.ECA2SQL.Singletons import Database.Design.Ampersand.Basics.Assertion import qualified Language.SQL.SimpleSQL.Syntax as Sm import Prelude (Maybe(..), (.), id, seq, undefined, ($), Bool(..), String, (++)) -- This module is intended to be imported qualified import Control.Applicative (Applicative(..), (<$>)) import qualified GHC.TypeLits as TL true :: SQLVal 'SQLBool true = sql PTrue false :: SQLVal 'SQLBool false = sql PFalse not :: SQLVal 'SQLBool -> SQLVal 'SQLBool not = sql Not in_, notIn :: forall a . SQLVal a -> SQLVal ('SQLRel a) -> SQLVal 'SQLBool in_ = sql In; notIn = sql NotIn -- Indexing. Overloaded operator with typeclasses. class IndexInto (t :: SQLType) (indexk :: KProxy index) | t -> indexk where type GetAtIndex t (i :: index) :: SQLType (!) :: forall (i :: index) . SQLVal t -> SingT i -> SQLVal (GetAtIndex t i) instance IndexInto ('SQLRow xs) ('KProxy :: KProxy Symbol) where type GetAtIndex ('SQLRow xs) (nm :: Symbol) = LookupRec xs nm (!) v@(SQLQueryVal x) i@(SSymbol pri) = let strNm = Sm.Name Nothing $ TL.symbolVal pri in case typeOf v of { t -> case lookupRec (colsOf t) i of { r -> withSingT r $ \_ -> case isScalarType r of STrue -> SQLScalarVal $ case x of Sm.Table ns -> Sm.Iden (ns++[strNm]) _ -> Sm.SubQueryExpr Sm.SqSq $ Sm.makeSelect { qeSetQuantifier = Sm.All , qeSelectList = [ (Sm.Iden [strNm], Nothing) ] , qeFrom = [ Sm.TRQueryExpr x ] } SFalse -> SQLQueryVal $ Sm.makeSelect { qeSetQuantifier = Sm.All , qeSelectList = [ (Sm.Iden [strNm], Nothing) ] , qeFrom = [ Sm.TRQueryExpr x ] } }} (!) x y = impossible "" (WHNFIsNF (x, y)) instance IndexInto ('SQLRel ('SQLRow xs)) ('KProxy :: KProxy Symbol) where type GetAtIndex ('SQLRel ('SQLRow xs)) (nm :: Symbol) = 'SQLRel (LookupRec xs nm) instance IndexInto ('SQLVec x) ('KProxy :: KProxy TL.Nat) where type GetAtIndex ('SQLVec ts) (i :: TL.Nat) = LookupIx ts i -- Primitive functions go here. This allows an implementation of SQL to be -- as simple as a function of type the same as `primSQL'. data PrimSQLFunction (args :: [SQLType]) (out :: SQLType) where PTrue, PFalse :: PrimSQLFunction '[] 'SQLBool Not :: PrimSQLFunction '[ 'SQLBool ] 'SQLBool Or, And :: PrimSQLFunction '[ 'SQLBool, 'SQLBool ] 'SQLBool In, NotIn :: PrimSQLFunction '[ a, 'SQLRel a ] 'SQLBool Exists :: PrimSQLFunction '[ 'SQLRel a ] 'SQLBool GroupBy :: PrimSQLFunction '[ 'SQLRel a, a ] ('SQLRel ('SQLRel a)) SortBy :: PrimSQLFunction '[ 'SQLRel a, a ] ('SQLRel a) Max, Min, Sum, Avg :: {- IsSQLNumeric a => -} PrimSQLFunction '[ 'SQLRel a ] a Alias :: (RecAssocs ts ~ RecAssocs ts') => PrimSQLFunction '[ 'SQLRel ('SQLRow ts) ] ('SQLRel ('SQLRow ts')) primSQL :: PrimSQLFunction args out -> Prod SQLVal args -> SQLVal out primSQL PTrue = \PNil -> SQLScalarVal $ Sm.In True (Sm.NumLit "0") $ Sm.InList [Sm.NumLit "0"] primSQL PFalse = \PNil -> SQLScalarVal $ Sm.In True (Sm.NumLit "1") $ Sm.InList [Sm.NumLit "0"] primSQL Not = \(SQLScalarVal x :> PNil) -> SQLScalarVal $ Sm.PrefixOp ["NOT"] x primSQL In = \(SQLScalarVal x :> SQLQueryVal y :> PNil) -> SQLScalarVal $ Sm.In True x (Sm.InQueryExpr y) primSQL NotIn = \(SQLScalarVal x :> SQLQueryVal y :> PNil) -> SQLScalarVal $ Sm.In False x (Sm.InQueryExpr y) primSQL Or = \(SQLScalarVal x :> SQLScalarVal y :> PNil) -> SQLScalarVal $ Sm.BinOp x ["OR"] y primSQL And = \(SQLScalarVal x :> SQLScalarVal y :> PNil) -> SQLScalarVal $ Sm.BinOp x ["AND"] y primSQL Exists = \(SQLQueryVal x :> PNil) -> SQLScalarVal $ Sm.SubQueryExpr Sm.SqExists x sql :: (Uncurry SQLVal args out fun) => PrimSQLFunction args out -> fun sql fun = uncurryN $ primSQL fun {- -- The type of select is much too complex... data Aliased t where NoAlias :: SQLVal t -> Aliased (nm ::: t) Alias :: SQLVal t -> SingT nm -> Aliased (nm ::: t) newtype Table t = MkTable { tableRows :: SQLVal ('SQLRel ('SQLRow t)) } data SortSpec t = SortSpec (SQLVal t) Direction NullsOrder select :: Sm.SetQuantifier -- Quantifier [DISTINCT,ALL] -> Prod Aliased out_ts -- Select list ( <expr> [as col], ... ) -> Prod Table src_ts -- Source tables ( can be almost anything ) -> Maybe (SQLVal 'SQLBool) -- WHERE clause ( [ WHERE <expr> ] ) -> Maybe (SQLVal 'SQLBool) -- HAVING clause ( [ HAVING <expr> ] ) -> -}
4ZP6Capstone2015/ampersand
src/Database/Design/Ampersand/ECA2SQL/TSQLCombinators.hs
gpl-3.0
5,342
13
29
1,344
1,601
865
736
-1
-1
module Main where import Test.HUnit import System.FilePath import System.IO (stdout) import System.Exit (exitFailure, exitSuccess) import LoadFileTests import ColorAnalysisTests import DownloaderTests myRunTestTT t = do (counts, 0) <- runTestText (putTextToHandle stdout True) t return $ (errors counts) + (failures counts) runAllTests = myRunTestTT $ test $ concat [ loadFileTests , getColorTests , makeGraphTests , colorAnalysisTests , averageColorTests , toColorTests , downloadsTests , roundingTests , convertTests , converterTests] main = do nerr <- runAllTests if nerr /= 0 then exitFailure else exitSuccess
gltronred/haskell-collage
test/Tests.hs
gpl-3.0
741
0
10
207
176
99
77
25
2
{-# 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.AdExchangeBuyer2.Bidders.FilterSets.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 requested filter set from the account with the given account -- ID. -- -- /See:/ <https://developers.google.com/authorized-buyers/apis/reference/rest/ Ad Exchange Buyer API II Reference> for @adexchangebuyer2.bidders.filterSets.delete@. module Network.Google.Resource.AdExchangeBuyer2.Bidders.FilterSets.Delete ( -- * REST Resource BiddersFilterSetsDeleteResource -- * Creating a Request , biddersFilterSetsDelete , BiddersFilterSetsDelete -- * Request Lenses , bfsdXgafv , bfsdUploadProtocol , bfsdAccessToken , bfsdUploadType , bfsdName , bfsdCallback ) where import Network.Google.AdExchangeBuyer2.Types import Network.Google.Prelude -- | A resource alias for @adexchangebuyer2.bidders.filterSets.delete@ method which the -- 'BiddersFilterSetsDelete' request conforms to. type BiddersFilterSetsDeleteResource = "v2beta1" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] Empty -- | Deletes the requested filter set from the account with the given account -- ID. -- -- /See:/ 'biddersFilterSetsDelete' smart constructor. data BiddersFilterSetsDelete = BiddersFilterSetsDelete' { _bfsdXgafv :: !(Maybe Xgafv) , _bfsdUploadProtocol :: !(Maybe Text) , _bfsdAccessToken :: !(Maybe Text) , _bfsdUploadType :: !(Maybe Text) , _bfsdName :: !Text , _bfsdCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BiddersFilterSetsDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'bfsdXgafv' -- -- * 'bfsdUploadProtocol' -- -- * 'bfsdAccessToken' -- -- * 'bfsdUploadType' -- -- * 'bfsdName' -- -- * 'bfsdCallback' biddersFilterSetsDelete :: Text -- ^ 'bfsdName' -> BiddersFilterSetsDelete biddersFilterSetsDelete pBfsdName_ = BiddersFilterSetsDelete' { _bfsdXgafv = Nothing , _bfsdUploadProtocol = Nothing , _bfsdAccessToken = Nothing , _bfsdUploadType = Nothing , _bfsdName = pBfsdName_ , _bfsdCallback = Nothing } -- | V1 error format. bfsdXgafv :: Lens' BiddersFilterSetsDelete (Maybe Xgafv) bfsdXgafv = lens _bfsdXgafv (\ s a -> s{_bfsdXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). bfsdUploadProtocol :: Lens' BiddersFilterSetsDelete (Maybe Text) bfsdUploadProtocol = lens _bfsdUploadProtocol (\ s a -> s{_bfsdUploadProtocol = a}) -- | OAuth access token. bfsdAccessToken :: Lens' BiddersFilterSetsDelete (Maybe Text) bfsdAccessToken = lens _bfsdAccessToken (\ s a -> s{_bfsdAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). bfsdUploadType :: Lens' BiddersFilterSetsDelete (Maybe Text) bfsdUploadType = lens _bfsdUploadType (\ s a -> s{_bfsdUploadType = a}) -- | Full name of the resource to delete. For example: - For a bidder-level -- filter set for bidder 123: \`bidders\/123\/filterSets\/abc\` - For an -- account-level filter set for the buyer account representing bidder 123: -- \`bidders\/123\/accounts\/123\/filterSets\/abc\` - For an account-level -- filter set for the child seat buyer account 456 whose bidder is 123: -- \`bidders\/123\/accounts\/456\/filterSets\/abc\` bfsdName :: Lens' BiddersFilterSetsDelete Text bfsdName = lens _bfsdName (\ s a -> s{_bfsdName = a}) -- | JSONP bfsdCallback :: Lens' BiddersFilterSetsDelete (Maybe Text) bfsdCallback = lens _bfsdCallback (\ s a -> s{_bfsdCallback = a}) instance GoogleRequest BiddersFilterSetsDelete where type Rs BiddersFilterSetsDelete = Empty type Scopes BiddersFilterSetsDelete = '["https://www.googleapis.com/auth/adexchange.buyer"] requestClient BiddersFilterSetsDelete'{..} = go _bfsdName _bfsdXgafv _bfsdUploadProtocol _bfsdAccessToken _bfsdUploadType _bfsdCallback (Just AltJSON) adExchangeBuyer2Service where go = buildClient (Proxy :: Proxy BiddersFilterSetsDeleteResource) mempty
brendanhay/gogol
gogol-adexchangebuyer2/gen/Network/Google/Resource/AdExchangeBuyer2/Bidders/FilterSets/Delete.hs
mpl-2.0
5,193
0
15
1,094
702
413
289
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.Directory.ChromeosDevices.Patch -- 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) -- -- Update Chrome OS Device. This method supports patch semantics. -- -- /See:/ <https://developers.google.com/admin-sdk/directory/ Admin Directory API Reference> for @directory.chromeosdevices.patch@. module Network.Google.Resource.Directory.ChromeosDevices.Patch ( -- * REST Resource ChromeosDevicesPatchResource -- * Creating a Request , chromeosDevicesPatch , ChromeosDevicesPatch -- * Request Lenses , cdpPayload , cdpCustomerId , cdpDeviceId , cdpProjection ) where import Network.Google.Directory.Types import Network.Google.Prelude -- | A resource alias for @directory.chromeosdevices.patch@ method which the -- 'ChromeosDevicesPatch' request conforms to. type ChromeosDevicesPatchResource = "admin" :> "directory" :> "v1" :> "customer" :> Capture "customerId" Text :> "devices" :> "chromeos" :> Capture "deviceId" Text :> QueryParam "projection" ChromeosDevicesPatchProjection :> QueryParam "alt" AltJSON :> ReqBody '[JSON] ChromeOSDevice :> Patch '[JSON] ChromeOSDevice -- | Update Chrome OS Device. This method supports patch semantics. -- -- /See:/ 'chromeosDevicesPatch' smart constructor. data ChromeosDevicesPatch = ChromeosDevicesPatch' { _cdpPayload :: !ChromeOSDevice , _cdpCustomerId :: !Text , _cdpDeviceId :: !Text , _cdpProjection :: !(Maybe ChromeosDevicesPatchProjection) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ChromeosDevicesPatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cdpPayload' -- -- * 'cdpCustomerId' -- -- * 'cdpDeviceId' -- -- * 'cdpProjection' chromeosDevicesPatch :: ChromeOSDevice -- ^ 'cdpPayload' -> Text -- ^ 'cdpCustomerId' -> Text -- ^ 'cdpDeviceId' -> ChromeosDevicesPatch chromeosDevicesPatch pCdpPayload_ pCdpCustomerId_ pCdpDeviceId_ = ChromeosDevicesPatch' { _cdpPayload = pCdpPayload_ , _cdpCustomerId = pCdpCustomerId_ , _cdpDeviceId = pCdpDeviceId_ , _cdpProjection = Nothing } -- | Multipart request metadata. cdpPayload :: Lens' ChromeosDevicesPatch ChromeOSDevice cdpPayload = lens _cdpPayload (\ s a -> s{_cdpPayload = a}) -- | Immutable id of the Google Apps account cdpCustomerId :: Lens' ChromeosDevicesPatch Text cdpCustomerId = lens _cdpCustomerId (\ s a -> s{_cdpCustomerId = a}) -- | Immutable id of Chrome OS Device cdpDeviceId :: Lens' ChromeosDevicesPatch Text cdpDeviceId = lens _cdpDeviceId (\ s a -> s{_cdpDeviceId = a}) -- | Restrict information returned to a set of selected fields. cdpProjection :: Lens' ChromeosDevicesPatch (Maybe ChromeosDevicesPatchProjection) cdpProjection = lens _cdpProjection (\ s a -> s{_cdpProjection = a}) instance GoogleRequest ChromeosDevicesPatch where type Rs ChromeosDevicesPatch = ChromeOSDevice type Scopes ChromeosDevicesPatch = '["https://www.googleapis.com/auth/admin.directory.device.chromeos"] requestClient ChromeosDevicesPatch'{..} = go _cdpCustomerId _cdpDeviceId _cdpProjection (Just AltJSON) _cdpPayload directoryService where go = buildClient (Proxy :: Proxy ChromeosDevicesPatchResource) mempty
rueshyna/gogol
gogol-admin-directory/gen/Network/Google/Resource/Directory/ChromeosDevices/Patch.hs
mpl-2.0
4,376
0
18
1,074
549
324
225
90
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.DFAReporting.FloodlightActivities.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 an existing floodlight activity. -- -- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.floodlightActivities.delete@. module Network.Google.Resource.DFAReporting.FloodlightActivities.Delete ( -- * REST Resource FloodlightActivitiesDeleteResource -- * Creating a Request , floodlightActivitiesDelete , FloodlightActivitiesDelete -- * Request Lenses , fadProFileId , fadId ) where import Network.Google.DFAReporting.Types import Network.Google.Prelude -- | A resource alias for @dfareporting.floodlightActivities.delete@ method which the -- 'FloodlightActivitiesDelete' request conforms to. type FloodlightActivitiesDeleteResource = "dfareporting" :> "v2.7" :> "userprofiles" :> Capture "profileId" (Textual Int64) :> "floodlightActivities" :> Capture "id" (Textual Int64) :> QueryParam "alt" AltJSON :> Delete '[JSON] () -- | Deletes an existing floodlight activity. -- -- /See:/ 'floodlightActivitiesDelete' smart constructor. data FloodlightActivitiesDelete = FloodlightActivitiesDelete' { _fadProFileId :: !(Textual Int64) , _fadId :: !(Textual Int64) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'FloodlightActivitiesDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'fadProFileId' -- -- * 'fadId' floodlightActivitiesDelete :: Int64 -- ^ 'fadProFileId' -> Int64 -- ^ 'fadId' -> FloodlightActivitiesDelete floodlightActivitiesDelete pFadProFileId_ pFadId_ = FloodlightActivitiesDelete' { _fadProFileId = _Coerce # pFadProFileId_ , _fadId = _Coerce # pFadId_ } -- | User profile ID associated with this request. fadProFileId :: Lens' FloodlightActivitiesDelete Int64 fadProFileId = lens _fadProFileId (\ s a -> s{_fadProFileId = a}) . _Coerce -- | Floodlight activity ID. fadId :: Lens' FloodlightActivitiesDelete Int64 fadId = lens _fadId (\ s a -> s{_fadId = a}) . _Coerce instance GoogleRequest FloodlightActivitiesDelete where type Rs FloodlightActivitiesDelete = () type Scopes FloodlightActivitiesDelete = '["https://www.googleapis.com/auth/dfatrafficking"] requestClient FloodlightActivitiesDelete'{..} = go _fadProFileId _fadId (Just AltJSON) dFAReportingService where go = buildClient (Proxy :: Proxy FloodlightActivitiesDeleteResource) mempty
rueshyna/gogol
gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/FloodlightActivities/Delete.hs
mpl-2.0
3,493
0
14
761
425
251
174
63
1
module Git.Command.MergeFile (run) where run :: [String] -> IO () run args = return ()
wereHamster/yag
Git/Command/MergeFile.hs
unlicense
87
0
7
15
42
23
19
3
1
module Miscellaneous.A280521Spec (main, spec) where import Test.Hspec import Miscellaneous.A280521 (a280521) main :: IO () main = hspec spec spec :: Spec spec = describe "A280521" $ it "correctly computes the first 20 elements" $ take 20 (map a280521 [1..]) `shouldBe` expectedValue where expectedValue = [1,1,2,1,2,2,1,2,2,3,2,1,2,2,3,2,3,3,2,1]
peterokagey/haskellOEIS
test/Miscellaneous/A280521Spec.hs
apache-2.0
361
0
10
59
160
95
65
10
1
{-# LANGUAGE ImpredicativeTypes #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiWayIf #-} {-# OPTIONS_HADDOCK hide #-} module Text.HTML.Scalpel.Internal.Select.Combinators ( (//) , (@:) , (@=) , (@=~) , atDepth , hasClass , match , notP ) where import Text.HTML.Scalpel.Internal.Select.Types import qualified Data.Text as T import qualified Text.Regex.Base.RegexLike as RE import qualified Text.StringLike as TagSoup -- | The '@:' operator creates a 'Selector' by combining a 'TagName' with a list -- of 'AttributePredicate's. (@:) :: TagName -> [AttributePredicate] -> Selector (@:) tag attrs = MkSelector [(toSelectNode tag attrs, defaultSelectSettings)] infixl 9 @: -- | The '@=' operator creates an 'AttributePredicate' that will match -- attributes with the given name and value. -- -- If you are attempting to match a specific class of a tag with potentially -- multiple classes, you should use the 'hasClass' utility function. (@=) :: AttributeName -> String -> AttributePredicate (@=) key value = anyAttrPredicate $ \(attrKey, attrValue) -> matchKey key attrKey && TagSoup.fromString value == attrValue infixl 6 @= -- | The '@=~' operator creates an 'AttributePredicate' that will match -- attributes with the given name and whose value matches the given regular -- expression. (@=~) :: RE.RegexLike re String => AttributeName -> re -> AttributePredicate (@=~) key re = anyAttrPredicate $ \(attrKey, attrValue) -> matchKey key attrKey && RE.matchTest re (TagSoup.toString attrValue) infixl 6 @=~ -- | The 'atDepth' operator constrains a 'Selector' to only match when it is at -- @depth@ below the previous selector. -- -- For example, @"div" // "a" `atDepth` 1@ creates a 'Selector' that matches -- anchor tags that are direct children of a div tag. atDepth :: Selector -> Int -> Selector atDepth (MkSelector xs) depth = MkSelector (addDepth xs) where addDepth [] = [] addDepth [(node, settings)] = [ (node, settings { selectSettingsDepth = Just depth }) ] addDepth (x : xs) = x : addDepth xs infixl 6 `atDepth` -- | The '//' operator creates an 'Selector' by nesting one 'Selector' in -- another. For example, @"div" // "a"@ will create a 'Selector' that matches -- anchor tags that are nested arbitrarily deep within a div tag. (//) :: Selector -> Selector -> Selector (//) a b = MkSelector (as ++ bs) where (MkSelector as) = a (MkSelector bs) = b infixl 5 // -- | The classes of a tag are defined in HTML as a space separated list given by -- the @class@ attribute. The 'hasClass' function will match a @class@ attribute -- if the given class appears anywhere in the space separated list of classes. hasClass :: String -> AttributePredicate hasClass clazz = anyAttrPredicate hasClass' where hasClass' (attrName, classes) | "class" == TagSoup.toString attrName = textClass `elem` classList | otherwise = False where textClass = TagSoup.castString clazz textClasses = TagSoup.castString classes classList = T.split (== ' ') textClasses -- | Negates an 'AttributePredicate'. notP :: AttributePredicate -> AttributePredicate notP (MkAttributePredicate p) = MkAttributePredicate $ not . p -- | The 'match' function allows for the creation of arbitrary -- 'AttributePredicate's. The argument is a function that takes the attribute -- key followed by the attribute value and returns a boolean indicating if the -- attribute satisfies the predicate. match :: (String -> String -> Bool) -> AttributePredicate match f = anyAttrPredicate $ \(attrKey, attrValue) -> f (TagSoup.toString attrKey) (TagSoup.toString attrValue)
fimad/scalpel
scalpel-core/src/Text/HTML/Scalpel/Internal/Select/Combinators.hs
apache-2.0
3,862
0
12
876
693
404
289
-1
-1