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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module Misc where
import Data.List
import Data.Map (Map,keys,(!))
-- ---------------------------------------------------------------------
-- List-related functions ----------------------------------------------
-- ---------------------------------------------------------------------
-- A function that generates a string with the given number
-- of whitespaces. Empty string if number less or equal 0.
ostring :: Int -> String
ostring n = replicate n ' '
-- check whether all elements in a list are distinct
distinct :: Eq a => [a] -> Bool
distinct [] = True
distinct (x:xs) = if elem x xs then False
else distinct xs
-- calculate the equivalence classes in a list with respect to an equivalence relation
duplicates :: (a -> a -> Bool) -> [a] -> [[a]]
duplicates eq [] = []
duplicates eq (x:xs) = let ecx = [y | y <- (x:xs) , eq x y]
in ecx : duplicates eq [y | y <- (x:xs) , not (eq x y)]
-- update a list at a certain position; it is assumed that the given index is greater or equal 0 and
-- that it is less then the length of the list
listUpdate :: [a] -> Int -> a -> [a]
listUpdate (x:xs) i e = if i==0 then e:xs
else x : (listUpdate xs (i-1) e)
-- remove the element at a given position in a list; it is assumed that the given index is greater or equal 0 and
-- that it is less then the length of the list
removeIndex :: [a] -> Int -> [a]
removeIndex (x:xs) 0 = xs
removeIndex (x:xs) n = x : removeIndex xs (n-1)
-- check whether two lists are permutations of each other
permut :: Eq a => [a] -> [a] -> Bool
permut [] [] = True
permut xs [] = False
permut [] ys = False
permut (x:xs) ys = if (elem x ys) then permut xs (delete x ys)
else False
-- ---------------------------------------------------------------------
-- (Ordered) Map-related functions -------------------------------------
-- ---------------------------------------------------------------------
-- check whether all keys in an ordered Map are distinct
-- (this should be the case if constructed using the basic constructors of Map)
validM :: Eq k => Map k v -> Bool
validM m = distinct (keys m)
-- new printing function for (ordered) Maps
printMap :: (Ord k,Show k,Show v) => Map k v -> String
printMap m = "**************************************************** \n" ++
printMap_help m (keys m) ++
"\n**************************************************** \n"
printMap_help m ([]) = ""
printMap_help m ([k]) = (show k) ++ " --> \n\n" ++
(show (m!k))
printMap_help m (k:ks) = (show k) ++ " --> \n\n" ++
(show (m!k)) ++ "\n---------------------------------------------------- \n" ++
(printMap_help m ks)
| Booster2/Booster2 | Workflow_Precond/impl_nondisjoint/Misc.hs | bsd-3-clause | 2,828 | 0 | 13 | 684 | 747 | 401 | 346 | 37 | 2 |
module Haskus.Apps.System.Build.GMP
( gmpMain
)
where
import Haskus.Apps.System.Build.Utils
import Haskus.Utils.Flow
import System.IO.Temp
import System.Directory
import System.FilePath
gmpMain :: IO ()
gmpMain = do
appDir <- getAppDir
let
usrDir = appDir </> "usr"
gmpVer = "6.1.2"
libFile = usrDir </> "lib" </> "libgmp.a"
createDirectoryIfMissing True usrDir
unlessM (doesFileExist libFile) $ do
withSystemTempDirectory "haskus-system-build" $ \fp -> do
showStep $ "Downloading libgmp " ++ gmpVer ++"..."
let fp2 = fp </> "gmp.tar.lz"
download
("https://gmplib.org/download/gmp/gmp-"++gmpVer++".tar.lz")
fp2
showStep "Unpacking libgmp..."
untar fp2 fp
let fp3 = fp </> ("gmp-"++gmpVer)
showStep "Configuring libgmp..."
shellInErr fp3 ("./configure --prefix=" ++ usrDir)
$ failWith "Cannot configure libgmp"
showStep "Building libgmp..."
shellInErr fp3 "make -j8"
$ failWith "Cannot build libgmp"
showStep "Installing libgmp..."
shellInErr fp3 "make install"
$ failWith "Cannot install libgmp"
workDir <- getWorkDir
let libDir = workDir </> "lib"
createDirectoryIfMissing True libDir
unlessM (doesFileExist (libDir </> "libgmp.a")) $ do
showStep "Copying libgmp.a into .system-work"
copyFile libFile (libDir </> "libgmp.a")
| hsyl20/ViperVM | haskus-system-build/src/apps/Haskus/Apps/System/Build/GMP.hs | bsd-3-clause | 1,484 | 0 | 19 | 410 | 359 | 171 | 188 | 40 | 1 |
import MatrixTree ; import SpAMM ; import System.Directory (removeFile)
main = do testReadWrite ; testAdd ; testMultiply
testReadWrite = do tree1 <- mmReadTree "Matrices/rect4arr.txt"
mmWriteTree tree1 "coordinate" "Matrices/tempfile.txt"
tree2 <- mmReadTree "Matrices/tempfile.txt"
testReport "readWrite" (tree1 == tree2)
removeFile "Matrices/tempfile.txt"
testAdd = do addZeros ; addZeroToValue ; addZeroToRect;
addValueToValue ; addRectToRect
addZeros = do zeroTree <- mmReadTree "Matrices/zerorectcoor.txt"
testReport "addZeros" (zeroTree `treeAdd` zeroTree == zeroTree)
addZeroToValue = do valueTree <- mmReadTree "Matrices/value1coor.txt"
zeroTree <- mmReadTree "Matrices/zerovaluecoor.txt"
testReport "addValuetoZero" (valueTree `treeAdd` zeroTree
== valueTree)
testReport "addZerotoValue" (zeroTree `treeAdd` valueTree
== valueTree)
addZeroToRect = do rectTree <- mmReadTree "Matrices/rect1coor.txt"
zeroTree <- mmReadTree "Matrices/zerorectcoor.txt"
testReport "addRectToZero" (rectTree `treeAdd` zeroTree
== rectTree)
testReport "addZeroToRect" (zeroTree `treeAdd` rectTree
== rectTree)
addValueToValue = do valueTree1 <- mmReadTree "Matrices/value1coor.txt"
valueTree2 <- mmReadTree "Matrices/value2coor.txt"
valueTree3 <- mmReadTree "Matrices/value3coor.txt"
testReport "addValueToValue" (valueTree1 `treeAdd`
valueTree2 ==
valueTree3)
addRectToRect = do rectTree1 <- mmReadTree "Matrices/rect1coor.txt"
rectTree2 <- mmReadTree "Matrices/rect2coor.txt"
rectTree3 <- mmReadTree "Matrices/rect3coor.txt"
testReport "addRectToRect" (rectTree1 `treeAdd` rectTree2
== rectTree3)
testMultiply = do multZeros ; multZeroByValue ; multZeroByRect ;
multValueByValue ; multValueByRect ; multRectByRect ;
multRectByRectArray
multZeros = do zeroTree <- mmReadTree "Matrices/zerorectcoor.txt"
zeroSquare <- mmReadTree "Matrices/zerosquarecoor.txt"
testReport "multZeros" (zeroTree `treeMult`
(treeTranspose zeroTree)
== zeroSquare)
multZeroByValue = do zeroRow <- mmReadTree "Matrices/zerorowcoor.txt"
valueTree <- mmReadTree "Matrices/value1coor.txt"
testReport "multValueByZero" (valueTree `treeMult`
zeroRow == zeroRow)
testReport "multZeroByValue" ((treeTranspose zeroRow)
`treeMult`
(treeTranspose valueTree)
== treeTranspose zeroRow)
multZeroByRect = do zeroTree <- mmReadTree "Matrices/zerorectcoor.txt"
rectTree <- mmReadTree "Matrices/rect1coor.txt"
zeroSquare <- mmReadTree "Matrices/zerosquarecoor.txt"
testReport "multZeroByRect" (zeroTree `treeMult`
(treeTranspose rectTree)
== zeroSquare)
testReport "multZeroByRect" (rectTree `treeMult`
(treeTranspose zeroTree)
== zeroSquare)
multValueByValue =
do valueTree1 <- mmReadTree "Matrices/value2coor.txt"
valueTree2 <- mmReadTree "Matrices/value3coor.txt"
valueTree3 <- mmReadTree "Matrices/value4coor.txt"
testReport "multValueByValue" (valueTree1 `treeMult` valueTree2
== valueTree3)
multValueByRect =
do valueTree <- mmReadTree "Matrices/value2coor.txt"
rowTree <- mmReadTree "Matrices/rowcoor.txt"
valuetimesrowTree <- mmReadTree "Matrices/valuetimesrowcoor.txt"
testReport "multValueByRect" (valueTree `treeMult` rowTree
== valuetimesrowTree)
testReport "multRectByValue" ((treeTranspose rowTree) `treeMult`
(treeTranspose valueTree) ==
treeTranspose valuetimesrowTree)
multRectByRect =
do rectTree1 <- mmReadTree "Matrices/rect1coor.txt"
rectTree2 <- mmReadTree "Matrices/rect2coor.txt"
rectTree4 <- mmReadTree "Matrices/rect4coor.txt"
testReport "multRectByRect" (rectTree1 `treeMult`
(treeTranspose rectTree2) == rectTree4)
multRectByRectArray =
do rectTree1 <- mmReadTree "Matrices/rect1arr.txt"
rectTree2 <- mmReadTree "Matrices/rect2arr.txt"
rectTree4 <- mmReadTree "Matrices/rect4arr.txt"
testReport "multRectByRectArray" (rectTree1 `treeMult`
(treeTranspose rectTree2)
== rectTree4)
testReport testName result =
putStrLn $ (if result then "Yes " else "No ") ++ testName | FreeON/spammpack | src-Haskell/Testing/tests.hs | bsd-3-clause | 5,611 | 0 | 12 | 2,138 | 953 | 460 | 493 | 89 | 2 |
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "Data/ByteString/Builder/Prim/Internal.hs" #-}
{-# LANGUAGE ScopedTypeVariables, CPP, BangPatterns #-}
{-# LANGUAGE Unsafe #-}
{-# OPTIONS_HADDOCK hide #-}
-- |
-- Copyright : 2010-2011 Simon Meier, 2010 Jasper van der Jeugt
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Simon Meier <[email protected]>
-- Stability : unstable, private
-- Portability : GHC
--
-- *Warning:* this module is internal. If you find that you need it please
-- contact the maintainers and explain what you are trying to do and discuss
-- what you would need in the public API. It is important that you do this as
-- the module may not be exposed at all in future releases.
--
-- The maintainers are glad to accept patches for further
-- standard encodings of standard Haskell values.
--
-- If you need to write your own builder primitives, then be aware that you are
-- writing code with /all saftey belts off/; i.e.,
-- *this is the code that might make your application vulnerable to buffer-overflow attacks!*
-- The "Data.ByteString.Builder.Prim.Tests" module provides you with
-- utilities for testing your encodings thoroughly.
--
module Data.ByteString.Builder.Prim.Internal (
-- * Fixed-size builder primitives
Size
, FixedPrim
, fixedPrim
, size
, runF
, emptyF
, contramapF
, pairF
-- , liftIOF
, storableToF
-- * Bounded-size builder primitives
, BoundedPrim
, boudedPrim
, sizeBound
, runB
, emptyB
, contramapB
, pairB
, eitherB
, condB
-- , liftIOB
, toB
, liftFixedToBounded
-- , withSizeFB
-- , withSizeBB
-- * Shared operators
, (>$<)
, (>*<)
) where
import Foreign
import Prelude hiding (maxBound)
------------------------------------------------------------------------------
-- Supporting infrastructure
------------------------------------------------------------------------------
-- | Contravariant functors as in the @contravariant@ package.
class Contravariant f where
contramap :: (b -> a) -> f a -> f b
infixl 4 >$<
-- | A fmap-like operator for builder primitives, both bounded and fixed size.
--
-- Builder primitives are contravariant so it's like the normal fmap, but
-- backwards (look at the type). (If it helps to remember, the operator symbol
-- is like (<$>) but backwards.)
--
-- We can use it for example to prepend and/or append fixed values to an
-- primitive.
--
-- >showEncoding ((\x -> ('\'', (x, '\''))) >$< fixed3) 'x' = "'x'"
-- > where
-- > fixed3 = char7 >*< char7 >*< char7
--
-- Note that the rather verbose syntax for composition stems from the
-- requirement to be able to compute the size / size bound at compile time.
--
(>$<) :: Contravariant f => (b -> a) -> f a -> f b
(>$<) = contramap
instance Contravariant FixedPrim where
contramap = contramapF
instance Contravariant BoundedPrim where
contramap = contramapB
-- | Type-constructors supporting lifting of type-products.
class Monoidal f where
pair :: f a -> f b -> f (a, b)
instance Monoidal FixedPrim where
pair = pairF
instance Monoidal BoundedPrim where
pair = pairB
infixr 5 >*<
-- | A pairing/concatenation operator for builder primitives, both bounded and
-- fixed size.
--
-- For example,
--
-- > toLazyByteString (primFixed (char7 >*< char7) ('x','y')) = "xy"
--
-- We can combine multiple primitives using '>*<' multiple times.
--
-- > toLazyByteString (primFixed (char7 >*< char7 >*< char7) ('x',('y','z'))) = "xyz"
--
(>*<) :: Monoidal f => f a -> f b -> f (a, b)
(>*<) = pair
-- | The type used for sizes and sizeBounds of sizes.
type Size = Int
------------------------------------------------------------------------------
-- Fixed-size builder primitives
------------------------------------------------------------------------------
-- | A builder primitive that always results in a sequence of bytes of a
-- pre-determined, fixed size.
data FixedPrim a = FP {-# UNPACK #-} !Int (a -> Ptr Word8 -> IO ())
fixedPrim :: Int -> (a -> Ptr Word8 -> IO ()) -> FixedPrim a
fixedPrim = FP
-- | The size of the sequences of bytes generated by this 'FixedPrim'.
{-# INLINE CONLIKE size #-}
size :: FixedPrim a -> Int
size (FP l _) = l
{-# INLINE CONLIKE runF #-}
runF :: FixedPrim a -> a -> Ptr Word8 -> IO ()
runF (FP _ io) = io
-- | The 'FixedPrim' that always results in the zero-length sequence.
{-# INLINE CONLIKE emptyF #-}
emptyF :: FixedPrim a
emptyF = FP 0 (\_ _ -> return ())
-- | Encode a pair by encoding its first component and then its second component.
{-# INLINE CONLIKE pairF #-}
pairF :: FixedPrim a -> FixedPrim b -> FixedPrim (a, b)
pairF (FP l1 io1) (FP l2 io2) =
FP (l1 + l2) (\(x1,x2) op -> io1 x1 op >> io2 x2 (op `plusPtr` l1))
-- | Change a primitives such that it first applies a function to the value
-- to be encoded.
--
-- Note that primitives are 'Contrafunctors'
-- <http://hackage.haskell.org/package/contravariant>. Hence, the following
-- laws hold.
--
-- >contramapF id = id
-- >contramapF f . contramapF g = contramapF (g . f)
{-# INLINE CONLIKE contramapF #-}
contramapF :: (b -> a) -> FixedPrim a -> FixedPrim b
contramapF f (FP l io) = FP l (\x op -> io (f x) op)
-- | Convert a 'FixedPrim' to a 'BoundedPrim'.
{-# INLINE CONLIKE toB #-}
toB :: FixedPrim a -> BoundedPrim a
toB (FP l io) = BP l (\x op -> io x op >> (return $! op `plusPtr` l))
-- | Lift a 'FixedPrim' to a 'BoundedPrim'.
{-# INLINE CONLIKE liftFixedToBounded #-}
liftFixedToBounded :: FixedPrim a -> BoundedPrim a
liftFixedToBounded = toB
{-# INLINE CONLIKE storableToF #-}
storableToF :: forall a. Storable a => FixedPrim a
storableToF = FP (sizeOf (undefined :: a)) (\x op -> poke (castPtr op) x)
{-
{-# INLINE CONLIKE liftIOF #-}
liftIOF :: FixedPrim a -> FixedPrim (IO a)
liftIOF (FP l io) = FP l (\xWrapped op -> do x <- xWrapped; io x op)
-}
------------------------------------------------------------------------------
-- Bounded-size builder primitives
------------------------------------------------------------------------------
-- | A builder primitive that always results in sequence of bytes that is no longer
-- than a pre-determined bound.
data BoundedPrim a = BP {-# UNPACK #-} !Int (a -> Ptr Word8 -> IO (Ptr Word8))
-- | The bound on the size of sequences of bytes generated by this 'BoundedPrim'.
{-# INLINE CONLIKE sizeBound #-}
sizeBound :: BoundedPrim a -> Int
sizeBound (BP b _) = b
boudedPrim :: Int -> (a -> Ptr Word8 -> IO (Ptr Word8)) -> BoundedPrim a
boudedPrim = BP
{-# INLINE CONLIKE runB #-}
runB :: BoundedPrim a -> a -> Ptr Word8 -> IO (Ptr Word8)
runB (BP _ io) = io
-- | Change a 'BoundedPrim' such that it first applies a function to the
-- value to be encoded.
--
-- Note that 'BoundedPrim's are 'Contrafunctors'
-- <http://hackage.haskell.org/package/contravariant>. Hence, the following
-- laws hold.
--
-- >contramapB id = id
-- >contramapB f . contramapB g = contramapB (g . f)
{-# INLINE CONLIKE contramapB #-}
contramapB :: (b -> a) -> BoundedPrim a -> BoundedPrim b
contramapB f (BP b io) = BP b (\x op -> io (f x) op)
-- | The 'BoundedPrim' that always results in the zero-length sequence.
{-# INLINE CONLIKE emptyB #-}
emptyB :: BoundedPrim a
emptyB = BP 0 (\_ op -> return op)
-- | Encode a pair by encoding its first component and then its second component.
{-# INLINE CONLIKE pairB #-}
pairB :: BoundedPrim a -> BoundedPrim b -> BoundedPrim (a, b)
pairB (BP b1 io1) (BP b2 io2) =
BP (b1 + b2) (\(x1,x2) op -> io1 x1 op >>= io2 x2)
-- | Encode an 'Either' value using the first 'BoundedPrim' for 'Left'
-- values and the second 'BoundedPrim' for 'Right' values.
--
-- Note that the functions 'eitherB', 'pairB', and 'contramapB' (written below
-- using '>$<') suffice to construct 'BoundedPrim's for all non-recursive
-- algebraic datatypes. For example,
--
-- @
--maybeB :: BoundedPrim () -> BoundedPrim a -> BoundedPrim (Maybe a)
--maybeB nothing just = 'maybe' (Left ()) Right '>$<' eitherB nothing just
-- @
{-# INLINE CONLIKE eitherB #-}
eitherB :: BoundedPrim a -> BoundedPrim b -> BoundedPrim (Either a b)
eitherB (BP b1 io1) (BP b2 io2) =
BP (max b1 b2)
(\x op -> case x of Left x1 -> io1 x1 op; Right x2 -> io2 x2 op)
-- | Conditionally select a 'BoundedPrim'.
-- For example, we can implement the ASCII primitive that drops characters with
-- Unicode codepoints above 127 as follows.
--
-- @
--charASCIIDrop = 'condB' (< '\128') ('fromF' 'char7') 'emptyB'
-- @
{-# INLINE CONLIKE condB #-}
condB :: (a -> Bool) -> BoundedPrim a -> BoundedPrim a -> BoundedPrim a
condB p be1 be2 =
contramapB (\x -> if p x then Left x else Right x) (eitherB be1 be2)
| phischu/fragnix | tests/packages/scotty/Data.ByteString.Builder.Prim.Internal.hs | bsd-3-clause | 8,685 | 0 | 12 | 1,683 | 1,507 | 850 | 657 | 105 | 2 |
-- Copyright (c) 2014-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is distributed under the terms of a BSD license,
-- found in the LICENSE file.
{-# LANGUAGE OverloadedStrings #-}
module TestUtils
( makeTestEnv
, expectRoundsWithEnv
, expectRounds
, expectFetches
, testinput
, id1, id2, id3, id4
) where
import TestTypes
import MockTAO
import Data.IORef
import Data.Aeson
import Test.HUnit
import qualified Data.HashMap.Strict as HashMap
import Haxl.Core
import Prelude()
import Haxl.Prelude
testinput :: Object
testinput = HashMap.fromList [
"A" .= (1 :: Int),
"B" .= (2 :: Int),
"C" .= (3 :: Int),
"D" .= (4 :: Int) ]
id1 :: Haxl Id
id1 = lookupInput "A"
id2 :: Haxl Id
id2 = lookupInput "B"
id3 :: Haxl Id
id3 = lookupInput "C"
id4 :: Haxl Id
id4 = lookupInput "D"
makeTestEnv :: Bool -> IO (Env UserEnv)
makeTestEnv future = do
tao <- MockTAO.initGlobalState future
let st = stateSet tao stateEmpty
env <- initEnv st testinput
return env { flags = (flags env) { report = 2 } }
expectRoundsWithEnv
:: (Eq a, Show a) => Int -> a -> Haxl a -> Env UserEnv -> Assertion
expectRoundsWithEnv n result haxl env = do
a <- runHaxl env haxl
assertEqual "result" result a
stats <- readIORef (statsRef env)
assertEqual "rounds" n (numRounds stats)
expectRounds :: (Eq a, Show a) => Int -> a -> Haxl a -> Bool -> Assertion
expectRounds n result haxl future = do
env <- makeTestEnv future
expectRoundsWithEnv n result haxl env
expectFetches :: (Eq a, Show a) => Int -> Haxl a -> Bool -> Assertion
expectFetches n haxl future = do
env <- makeTestEnv future
_ <- runHaxl env haxl
stats <- readIORef (statsRef env)
assertEqual "fetches" n (numFetches stats)
| simonmar/Haxl | tests/TestUtils.hs | bsd-3-clause | 1,738 | 0 | 12 | 356 | 594 | 308 | 286 | 54 | 1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ru-RU">
<title>Browser View | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Индекс</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Поиск</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | kingthorin/zap-extensions | addOns/browserView/src/main/javahelp/org/zaproxy/zap/extension/browserView/resources/help_ru_RU/helpset_ru_RU.hs | apache-2.0 | 984 | 78 | 66 | 159 | 433 | 218 | 215 | -1 | -1 |
{-# OPTIONS_GHC -Werror -O #-}
-- Add -O so the UNPACK has some effect
module T3966 where
data Foo a b = Foo {-# UNPACK #-} !(a -> b)
| hvr/jhc | regress/tests/1_typecheck/4_fail/ghc/T3966.hs | mit | 136 | 0 | 9 | 31 | 26 | 17 | 9 | 3 | 0 |
{-|
Module : Idris.Package.Common
Description : Data structures common to all `iPKG` file formats.
License : BSD3
Maintainer : The Idris Community.
-}
module Idris.Package.Common where
import Idris.Core.TT (Name)
import Idris.Imports
import Idris.Options (Opt(..))
-- | Description of an Idris package.
data PkgDesc = PkgDesc {
pkgname :: PkgName -- ^ Name associated with a package.
, pkgdeps :: [PkgName] -- ^ List of packages this package depends on.
, pkgbrief :: Maybe String -- ^ Brief description of the package.
, pkgversion :: Maybe String -- ^ Version string to associate with the package.
, pkgreadme :: Maybe String -- ^ Location of the README file.
, pkglicense :: Maybe String -- ^ Description of the licensing information.
, pkgauthor :: Maybe String -- ^ Author information.
, pkgmaintainer :: Maybe String -- ^ Maintainer information.
, pkghomepage :: Maybe String -- ^ Website associated with the package.
, pkgsourceloc :: Maybe String -- ^ Location of the source files.
, pkgbugtracker :: Maybe String -- ^ Location of the project's bug tracker.
, libdeps :: [String] -- ^ External dependencies.
, objs :: [String] -- ^ Object files required by the package.
, makefile :: Maybe String -- ^ Makefile used to build external code. Used as part of the FFI process.
, idris_opts :: [Opt] -- ^ List of options to give the compiler.
, sourcedir :: String -- ^ Source directory for Idris files.
, modules :: [Name] -- ^ Modules provided by the package.
, idris_main :: Maybe Name -- ^ If an executable in which module can the Main namespace and function be found.
, execout :: Maybe String -- ^ What to call the executable.
, idris_tests :: [Name] -- ^ Lists of tests to execute against the package.
} deriving (Show)
-- | Default settings for package descriptions.
defaultPkg :: PkgDesc
defaultPkg = PkgDesc unInitializedPkgName [] Nothing Nothing Nothing Nothing
Nothing Nothing Nothing Nothing
Nothing [] [] Nothing [] "" [] Nothing Nothing []
| kojiromike/Idris-dev | src/Idris/Package/Common.hs | bsd-3-clause | 2,185 | 0 | 9 | 558 | 313 | 192 | 121 | 30 | 1 |
{-
(c) The University of Glasgow 2006
(c) The AQUA Project, Glasgow University, 1994-1998
UniqFM: Specialised finite maps, for things with @Uniques@.
Basically, the things need to be in class @Uniquable@, and we use the
@getUnique@ method to grab their @Uniques@.
(A similar thing to @UniqSet@, as opposed to @Set@.)
The interface is based on @FiniteMap@s, but the implementation uses
@Data.IntMap@, which is both maintained and faster than the past
implementation (see commit log).
The @UniqFM@ interface maps directly to Data.IntMap, only
``Data.IntMap.union'' is left-biased and ``plusUFM'' right-biased
and ``addToUFM\_C'' and ``Data.IntMap.insertWith'' differ in the order
of arguments of combining function.
-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# OPTIONS_GHC -Wall #-}
module UniqFM (
-- * Unique-keyed mappings
UniqFM, -- abstract type
-- ** Manipulating those mappings
emptyUFM,
unitUFM,
unitDirectlyUFM,
listToUFM,
listToUFM_Directly,
listToUFM_C,
addToUFM,addToUFM_C,addToUFM_Acc,
addListToUFM,addListToUFM_C,
addToUFM_Directly,
addListToUFM_Directly,
adjustUFM, alterUFM,
adjustUFM_Directly,
delFromUFM,
delFromUFM_Directly,
delListFromUFM,
plusUFM,
plusUFM_C,
plusUFM_CD,
minusUFM,
intersectUFM,
intersectUFM_C,
disjointUFM,
foldUFM, foldUFM_Directly,
mapUFM, mapUFM_Directly,
elemUFM, elemUFM_Directly,
filterUFM, filterUFM_Directly, partitionUFM,
sizeUFM,
isNullUFM,
lookupUFM, lookupUFM_Directly,
lookupWithDefaultUFM, lookupWithDefaultUFM_Directly,
eltsUFM, keysUFM, splitUFM,
ufmToSet_Directly,
ufmToList,
joinUFM, pprUniqFM
) where
import FastString
import Unique ( Uniquable(..), Unique, getKey )
import Outputable
import Compiler.Hoopl hiding (Unique)
import qualified Data.IntMap as M
import qualified Data.IntSet as S
import qualified Data.Foldable as Foldable
import qualified Data.Traversable as Traversable
import Data.Typeable
import Data.Data
#if __GLASGOW_HASKELL__ < 709
import Data.Monoid
#endif
{-
************************************************************************
* *
\subsection{The signature of the module}
* *
************************************************************************
-}
emptyUFM :: UniqFM elt
isNullUFM :: UniqFM elt -> Bool
unitUFM :: Uniquable key => key -> elt -> UniqFM elt
unitDirectlyUFM -- got the Unique already
:: Unique -> elt -> UniqFM elt
listToUFM :: Uniquable key => [(key,elt)] -> UniqFM elt
listToUFM_Directly
:: [(Unique, elt)] -> UniqFM elt
listToUFM_C :: Uniquable key => (elt -> elt -> elt)
-> [(key, elt)]
-> UniqFM elt
addToUFM :: Uniquable key => UniqFM elt -> key -> elt -> UniqFM elt
addListToUFM :: Uniquable key => UniqFM elt -> [(key,elt)] -> UniqFM elt
addListToUFM_Directly :: UniqFM elt -> [(Unique,elt)] -> UniqFM elt
addToUFM_Directly
:: UniqFM elt -> Unique -> elt -> UniqFM elt
addToUFM_C :: Uniquable key => (elt -> elt -> elt) -- old -> new -> result
-> UniqFM elt -- old
-> key -> elt -- new
-> UniqFM elt -- result
addToUFM_Acc :: Uniquable key =>
(elt -> elts -> elts) -- Add to existing
-> (elt -> elts) -- New element
-> UniqFM elts -- old
-> key -> elt -- new
-> UniqFM elts -- result
alterUFM :: Uniquable key =>
(Maybe elt -> Maybe elt) -- How to adjust
-> UniqFM elt -- old
-> key -- new
-> UniqFM elt -- result
addListToUFM_C :: Uniquable key => (elt -> elt -> elt)
-> UniqFM elt -> [(key,elt)]
-> UniqFM elt
adjustUFM :: Uniquable key => (elt -> elt) -> UniqFM elt -> key -> UniqFM elt
adjustUFM_Directly :: (elt -> elt) -> UniqFM elt -> Unique -> UniqFM elt
delFromUFM :: Uniquable key => UniqFM elt -> key -> UniqFM elt
delListFromUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
delFromUFM_Directly :: UniqFM elt -> Unique -> UniqFM elt
-- Bindings in right argument shadow those in the left
plusUFM :: UniqFM elt -> UniqFM elt -> UniqFM elt
plusUFM_C :: (elt -> elt -> elt)
-> UniqFM elt -> UniqFM elt -> UniqFM elt
-- | `plusUFM_CD f m1 d1 m2 d2` merges the maps using `f` as the
-- combinding function and `d1` resp. `d2` as the default value if
-- there is no entry in `m1` reps. `m2`. The domain is the union of
-- the domains of `m1` and `m2`.
--
-- Representative example:
--
-- @
-- plusUFM_CD f {A: 1, B: 2} 23 {B: 3, C: 4} 42
-- == {A: f 1 42, B: f 2 3, C: f 23 4 }
-- @
plusUFM_CD :: (elt -> elt -> elt)
-> UniqFM elt -> elt -> UniqFM elt -> elt -> UniqFM elt
minusUFM :: UniqFM elt1 -> UniqFM elt2 -> UniqFM elt1
intersectUFM :: UniqFM elt -> UniqFM elt -> UniqFM elt
intersectUFM_C :: (elt1 -> elt2 -> elt3)
-> UniqFM elt1 -> UniqFM elt2 -> UniqFM elt3
disjointUFM :: UniqFM elt1 -> UniqFM elt2 -> Bool
foldUFM :: (elt -> a -> a) -> a -> UniqFM elt -> a
foldUFM_Directly:: (Unique -> elt -> a -> a) -> a -> UniqFM elt -> a
mapUFM :: (elt1 -> elt2) -> UniqFM elt1 -> UniqFM elt2
mapUFM_Directly :: (Unique -> elt1 -> elt2) -> UniqFM elt1 -> UniqFM elt2
filterUFM :: (elt -> Bool) -> UniqFM elt -> UniqFM elt
filterUFM_Directly :: (Unique -> elt -> Bool) -> UniqFM elt -> UniqFM elt
partitionUFM :: (elt -> Bool) -> UniqFM elt -> (UniqFM elt, UniqFM elt)
sizeUFM :: UniqFM elt -> Int
--hashUFM :: UniqFM elt -> Int
elemUFM :: Uniquable key => key -> UniqFM elt -> Bool
elemUFM_Directly:: Unique -> UniqFM elt -> Bool
splitUFM :: Uniquable key => UniqFM elt -> key -> (UniqFM elt, Maybe elt, UniqFM elt)
-- Splits a UFM into things less than, equal to, and greater than the key
lookupUFM :: Uniquable key => UniqFM elt -> key -> Maybe elt
lookupUFM_Directly -- when you've got the Unique already
:: UniqFM elt -> Unique -> Maybe elt
lookupWithDefaultUFM
:: Uniquable key => UniqFM elt -> elt -> key -> elt
lookupWithDefaultUFM_Directly
:: UniqFM elt -> elt -> Unique -> elt
keysUFM :: UniqFM elt -> [Unique] -- Get the keys
eltsUFM :: UniqFM elt -> [elt]
ufmToSet_Directly :: UniqFM elt -> S.IntSet
ufmToList :: UniqFM elt -> [(Unique, elt)]
{-
************************************************************************
* *
\subsection{Monoid interface}
* *
************************************************************************
-}
instance Monoid (UniqFM a) where
mempty = emptyUFM
mappend = plusUFM
{-
************************************************************************
* *
\subsection{Implementation using ``Data.IntMap''}
* *
************************************************************************
-}
newtype UniqFM ele = UFM (M.IntMap ele)
deriving (Data, Eq, Functor, Traversable.Traversable,
Typeable)
deriving instance Foldable.Foldable UniqFM
emptyUFM = UFM M.empty
isNullUFM (UFM m) = M.null m
unitUFM k v = UFM (M.singleton (getKey $ getUnique k) v)
unitDirectlyUFM u v = UFM (M.singleton (getKey u) v)
listToUFM = foldl (\m (k, v) -> addToUFM m k v) emptyUFM
listToUFM_Directly = foldl (\m (u, v) -> addToUFM_Directly m u v) emptyUFM
listToUFM_C f = foldl (\m (k, v) -> addToUFM_C f m k v) emptyUFM
alterUFM f (UFM m) k = UFM (M.alter f (getKey $ getUnique k) m)
addToUFM (UFM m) k v = UFM (M.insert (getKey $ getUnique k) v m)
addListToUFM = foldl (\m (k, v) -> addToUFM m k v)
addListToUFM_Directly = foldl (\m (k, v) -> addToUFM_Directly m k v)
addToUFM_Directly (UFM m) u v = UFM (M.insert (getKey u) v m)
-- Arguments of combining function of M.insertWith and addToUFM_C are flipped.
addToUFM_C f (UFM m) k v =
UFM (M.insertWith (flip f) (getKey $ getUnique k) v m)
addToUFM_Acc exi new (UFM m) k v =
UFM (M.insertWith (\_new old -> exi v old) (getKey $ getUnique k) (new v) m)
addListToUFM_C f = foldl (\m (k, v) -> addToUFM_C f m k v)
adjustUFM f (UFM m) k = UFM (M.adjust f (getKey $ getUnique k) m)
adjustUFM_Directly f (UFM m) u = UFM (M.adjust f (getKey u) m)
delFromUFM (UFM m) k = UFM (M.delete (getKey $ getUnique k) m)
delListFromUFM = foldl delFromUFM
delFromUFM_Directly (UFM m) u = UFM (M.delete (getKey u) m)
-- M.union is left-biased, plusUFM should be right-biased.
plusUFM (UFM x) (UFM y) = UFM (M.union y x)
-- Note (M.union y x), with arguments flipped
-- M.union is left-biased, plusUFM should be right-biased.
plusUFM_C f (UFM x) (UFM y) = UFM (M.unionWith f x y)
plusUFM_CD f (UFM xm) dx (UFM ym) dy
= UFM $ M.mergeWithKey
(\_ x y -> Just (x `f` y))
(M.map (\x -> x `f` dy))
(M.map (\y -> dx `f` y))
xm ym
minusUFM (UFM x) (UFM y) = UFM (M.difference x y)
intersectUFM (UFM x) (UFM y) = UFM (M.intersection x y)
intersectUFM_C f (UFM x) (UFM y) = UFM (M.intersectionWith f x y)
disjointUFM (UFM x) (UFM y) = M.null (M.intersection x y)
foldUFM k z (UFM m) = M.fold k z m
foldUFM_Directly k z (UFM m) = M.foldWithKey (k . getUnique) z m
mapUFM f (UFM m) = UFM (M.map f m)
mapUFM_Directly f (UFM m) = UFM (M.mapWithKey (f . getUnique) m)
filterUFM p (UFM m) = UFM (M.filter p m)
filterUFM_Directly p (UFM m) = UFM (M.filterWithKey (p . getUnique) m)
partitionUFM p (UFM m) = case M.partition p m of
(left, right) -> (UFM left, UFM right)
sizeUFM (UFM m) = M.size m
elemUFM k (UFM m) = M.member (getKey $ getUnique k) m
elemUFM_Directly u (UFM m) = M.member (getKey u) m
splitUFM (UFM m) k = case M.splitLookup (getKey $ getUnique k) m of
(less, equal, greater) -> (UFM less, equal, UFM greater)
lookupUFM (UFM m) k = M.lookup (getKey $ getUnique k) m
lookupUFM_Directly (UFM m) u = M.lookup (getKey u) m
lookupWithDefaultUFM (UFM m) v k = M.findWithDefault v (getKey $ getUnique k) m
lookupWithDefaultUFM_Directly (UFM m) v u = M.findWithDefault v (getKey u) m
keysUFM (UFM m) = map getUnique $ M.keys m
eltsUFM (UFM m) = M.elems m
ufmToSet_Directly (UFM m) = M.keysSet m
ufmToList (UFM m) = map (\(k, v) -> (getUnique k, v)) $ M.toList m
-- Hoopl
joinUFM :: JoinFun v -> JoinFun (UniqFM v)
joinUFM eltJoin l (OldFact old) (NewFact new) = foldUFM_Directly add (NoChange, old) new
where add k new_v (ch, joinmap) =
case lookupUFM_Directly joinmap k of
Nothing -> (SomeChange, addToUFM_Directly joinmap k new_v)
Just old_v -> case eltJoin l (OldFact old_v) (NewFact new_v) of
(SomeChange, v') -> (SomeChange, addToUFM_Directly joinmap k v')
(NoChange, _) -> (ch, joinmap)
{-
************************************************************************
* *
\subsection{Output-ery}
* *
************************************************************************
-}
instance Outputable a => Outputable (UniqFM a) where
ppr ufm = pprUniqFM ppr ufm
pprUniqFM :: (a -> SDoc) -> UniqFM a -> SDoc
pprUniqFM ppr_elt ufm
= brackets $ fsep $ punctuate comma $
[ ppr uq <+> ptext (sLit ":->") <+> ppr_elt elt
| (uq, elt) <- ufmToList ufm ]
| acowley/ghc | compiler/utils/UniqFM.hs | bsd-3-clause | 12,598 | 0 | 14 | 3,844 | 3,612 | 1,875 | 1,737 | 202 | 3 |
module Vectorise.Utils.Hoisting
( Inline(..)
, addInlineArity
, inlineMe
, hoistBinding
, hoistExpr
, hoistVExpr
, hoistPolyVExpr
, takeHoisted
)
where
import Vectorise.Monad
import Vectorise.Env
import Vectorise.Vect
import Vectorise.Utils.Poly
import CoreSyn
import CoreUtils
import CoreUnfold
import Type
import Id
import BasicTypes (Arity)
import FastString
import Control.Monad
import Control.Applicative
import Prelude -- avoid redundant import warning due to AMP
-- Inline ---------------------------------------------------------------------
-- |Records whether we should inline a particular binding.
--
data Inline
= Inline Arity
| DontInline
-- |Add to the arity contained within an `Inline`, if any.
--
addInlineArity :: Inline -> Int -> Inline
addInlineArity (Inline m) n = Inline (m+n)
addInlineArity DontInline _ = DontInline
-- |Says to always inline a binding.
--
inlineMe :: Inline
inlineMe = Inline 0
-- Hoisting --------------------------------------------------------------------
hoistBinding :: Var -> CoreExpr -> VM ()
hoistBinding v e = updGEnv $ \env ->
env { global_bindings = (v,e) : global_bindings env }
hoistExpr :: FastString -> CoreExpr -> Inline -> VM Var
hoistExpr fs expr inl
= do
var <- mk_inline `liftM` newLocalVar fs (exprType expr)
hoistBinding var expr
return var
where
mk_inline var = case inl of
Inline arity -> var `setIdUnfolding`
mkInlineUnfolding (Just arity) expr
DontInline -> var
hoistVExpr :: VExpr -> Inline -> VM VVar
hoistVExpr (ve, le) inl
= do
fs <- getBindName
vv <- hoistExpr ('v' `consFS` fs) ve inl
lv <- hoistExpr ('l' `consFS` fs) le (addInlineArity inl 1)
return (vv, lv)
-- |Hoist a polymorphic vectorised expression into a new top-level binding (representing a closure
-- function).
--
-- The hoisted expression is parameterised by (1) a set of type variables and (2) a set of value
-- variables that are passed as conventional type and value arguments. The latter is implicitly
-- extended by the set of 'PA' dictionaries required for the type variables.
--
hoistPolyVExpr :: [TyVar] -> [Var] -> Inline -> VM VExpr -> VM VExpr
hoistPolyVExpr tvs vars inline p
= do { inline' <- addInlineArity inline . (+ length vars) <$> polyArity tvs
; expr <- closedV . polyAbstract tvs $ \args ->
mapVect (mkLams $ tvs ++ args ++ vars) <$> p
; fn <- hoistVExpr expr inline'
; let varArgs = varsToCoreExprs vars
; mapVect (\e -> e `mkApps` varArgs) <$> polyVApply (vVar fn) (mkTyVarTys tvs)
}
takeHoisted :: VM [(Var, CoreExpr)]
takeHoisted
= do
env <- readGEnv id
setGEnv $ env { global_bindings = [] }
return $ global_bindings env
| tjakway/ghcjvm | compiler/vectorise/Vectorise/Utils/Hoisting.hs | bsd-3-clause | 2,850 | 0 | 15 | 670 | 716 | 385 | 331 | 65 | 2 |
<?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="sl-SI">
<title>WebSockets | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | ccgreen13/zap-extensions | src/org/zaproxy/zap/extension/websocket/resources/help_sl_SI/helpset_sl_SI.hs | apache-2.0 | 972 | 80 | 66 | 159 | 413 | 209 | 204 | -1 | -1 |
{-# LANGUAGE ExtendedDefaultRules #-}
module T11974b where
default (Either, Monad, [], Maybe, Either Bool, Integer, Double, Blah)
data Blah
| ezyang/ghc | testsuite/tests/typecheck/should_fail/T11974b.hs | bsd-3-clause | 143 | 0 | 5 | 22 | 40 | 26 | 14 | -1 | -1 |
{-# LANGUAGE RankNTypes, GeneralizedNewtypeDeriving, ImpredicativeTypes #-}
module Foo where
class C a where op :: (forall b. b -> a) -> a
newtype T x = MkT x deriving( C )
| urbanslug/ghc | testsuite/tests/typecheck/should_compile/T8565.hs | bsd-3-clause | 175 | 0 | 10 | 33 | 51 | 30 | 21 | 4 | 0 |
module Parse.Basics where
import System.Environment
import System.IO
import Data.Char
import Data.Maybe
import Data.List
import Data.Either
import Control.Monad
import Text.Megaparsec
import Text.Megaparsec.Expr
import Text.Megaparsec.String
import qualified Text.Megaparsec.Lexer as L
sc :: Parser ()
sc = L.space (void spaceChar) lineComment blockComment
where lineComment = L.skipLineComment "//"
blockComment = L.skipBlockComment "/*" "*/"
withRecovery' a = withRecovery recover (Right <$> a)
where recover err = Left err <$ skippable
lexeme = L.lexeme sc
symbol = L.symbol sc
parens = between (symbol "(") (symbol ")")
brackets = between (symbol "[") (symbol "]")
angles = between (symbol "{") (symbol "}")
quotes = between (symbol "\"") (symbol "\"")
-- semicolon = withRecovery recover (Right <$> symbol ";")
-- where recover err = Left err <$ skippable
semicolon = symbol ";"
skippable :: Parser ()
skippable =
do a <- manyTill anyChar eol
return ()
comma = symbol ","
colon = symbol ":"
eq = symbol "="
concEq = symbol "<="
at = symbol "@"
idChar = alphaNumChar <|> char '_' <|> char '$'
idHeadChar = letterChar <|> char '_'
wrap :: Monad m => m a -> (a -> r) -> m r
wrap a b = a >>= \c -> return $ b c
wrapStatement :: Monad m => m a -> m [a]
wrapStatement a = a >>= \b -> return [b]
-- parsed data types know their location. for a given element, their location is the start of the element
-- for now, we are only handling unescaped identifiers. escaped identifiers are some horrifying trash
data Identifier = Identifier String SourcePos
| CompositeIdentifier [Identifier] SourcePos deriving (Show)
instance Eq Identifier where
(Identifier a _) == (Identifier b _) = a == b
(CompositeIdentifier a _) == (CompositeIdentifier b _) = a == b
class GetIdentifiers a where
getIdentifiers :: a -> [Identifier]
getIdentifierDeclarations :: a -> [Identifier]
getIdentifierUtilizations :: a -> [Identifier]
identifier :: Parser Identifier
identifier = try identifier' <|> try composite
idName :: Parser String
idName = do
x <- idHeadChar
xs <- many idChar
let name = x:xs
_ <- if name `elem` reservedWords then unexpected ("keyword " ++ show name ++ " cannot be an identifier") else sc
return $ x:xs
composite :: Parser Identifier
composite =
do
location <- getPosition
a <-angles (identifier `sepBy1` comma)
sc
return $ CompositeIdentifier a location
identifier' :: Parser Identifier
identifier' =
do
location <- getPosition
name <- try idName
sc
return $ Identifier (name) location
rword :: String -> Parser ()
rword w = string w *> notFollowedBy idChar *> sc
reservedWords :: [String]
reservedWords = ["localparam", "param", "parameter", "begin", "if", "else", "end", "always", "module", "endmodule", "input", "output", "inout", "wire", "reg", "integer", "assign", "default"]
| akindle/hdlint | Parse/Basics.hs | mit | 3,077 | 0 | 13 | 739 | 954 | 494 | 460 | 76 | 2 |
module Ch22.PodMain
where
import Ch22.PodDownload (mkManager, downloadURL, updatePodcastFromFeed, getEpisode)
import Ch21.PodDB (Podcast(..), Episode(..), addPodcast, getPodcasts, getEpisodes)
import Ch22.PodParser (Feed(..), parse')
import System.Environment (getArgs)
import Network.Socket (withSocketsDo)
import Network.HTTP.Client (Manager)
import Data.Either (either)
import qualified Data.Text as T
main :: IO ()
main =
withSocketsDo $ do
args <- getLine -- test it on ghci for now
manager <- mkManager
case words args of
["add", url] ->
add manager (T.pack url)
["update"] ->
update manager
["download"] ->
download manager
["fetch"] -> do
update manager
download manager
_ ->
syntaxError
retrieveFeed :: Manager -> T.Text -> IO (Maybe Feed)
retrieveFeed m url = do
bs <- downloadURL url m
either (\_ -> return Nothing) (return . flip parse' "new") bs
add :: Manager -> T.Text -> IO ()
add m url =
maybe (return ()) (\x -> do addPodcast x ; return ()) =<< mpc
where
mpc = do
mfeed <- retrieveFeed m url
let mpc =
maybe Nothing (\feed -> Just $ Podcast (channelTitle feed) url) mfeed
return mpc
update :: Manager -> IO ()
update m =
mapM_ procPodcast =<< getPodcasts
where
procPodcast pc = do
putStrLn ("Updating from: " ++ T.unpack (podcastUrl pc))
updatePodcastFromFeed pc m
download :: Manager -> IO ()
download m =
mapM_ procPodcast =<< getPodcasts
where
procPodcast pc = do
putStrLn $ "Considering " ++ T.unpack (podcastUrl pc)
eps <- getEpisodes pc
let pendingEps =
filter (\ep -> episodeDone ep == False) eps
mapM_ procEpisode pendingEps
procEpisode ep = do
putStrLn $ "Downloading " ++ T.unpack (episodeUrl ep)
getEpisode ep m
syntaxError =
putStrLn "Usage: pod command [args]\n\
\\n\
\pod add url Adds a new podcast with the given URL\n\
\pod download Downloads all pending episodes\n\
\pod fetch Updates, then downloads\n\
\pod update Downloads podcast feeds, looks for new episodes\n"
| futtetennista/IntroductionToFunctionalProgramming | RWH/src/Ch22/PodMain.hs | mit | 2,213 | 0 | 18 | 606 | 679 | 342 | 337 | 58 | 5 |
module Graphics.Urho3D.Resource.Internal.Cache(
ResourceCache
, resourceCacheCntx
) where
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Context as C
import qualified Language.C.Types as C
import qualified Data.Map as Map
data ResourceCache
resourceCacheCntx :: C.Context
resourceCacheCntx = mempty {
C.ctxTypesTable = Map.fromList [
(C.TypeName "ResourceCache", [t| ResourceCache |])
]
} | Teaspot-Studio/Urho3D-Haskell | src/Graphics/Urho3D/Resource/Internal/Cache.hs | mit | 446 | 0 | 11 | 76 | 101 | 69 | 32 | -1 | -1 |
module FrozenBeagle.Genes (length', DnaString(..)) where
data DnaString a = DnaStringConstr [a] deriving (Show)
length' :: DnaString a -> Int
length' (DnaStringConstr xs) = length xs
| satai/FrozenBeagleH | src/FrozenBeagle/Genes.hs | mit | 185 | 0 | 7 | 27 | 67 | 38 | 29 | 4 | 1 |
module Dotfiles.ConfigSpec where
import System.Directory (getHomeDirectory, getTemporaryDirectory)
import System.FilePath ((</>))
import Test.Hspec
import Dotfiles
import Dotfiles.Config
import SpecHelper
spec :: Spec
spec = do
describe "Dotfiles.Config" $ do
around withEnv $ do
it "covers default env" $ \_ -> do
env' <- defaultEnv
home <- getHomeDirectory
tmp <- getTemporaryDirectory
envRoot env' `shouldBe` home
envTmp env' `shouldBe` tmp
envAppDir env' `shouldBe` home </> ".dotfiles"
it "reads user config" $ \env -> do
let appdir = envRoot env </> "appdir"
let cfg = Config {appDir = Just appdir, dfNames = []}
writeConfig (envCfgPath env) cfg
env' <- readEnv (envRoot env)
envAppDir env' `shouldBe` appdir
| ilya-yurtaev/hdotfiles | tests/Dotfiles/ConfigSpec.hs | mit | 830 | 0 | 22 | 217 | 254 | 128 | 126 | 24 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Internal.SpockExt (serveFile, xml) where
import Control.Monad.IO.Class (MonadIO)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Network.Mime
import Web.Spock
-- | Serve a file, set the content-type in accordance with the file name.
serveFile :: MonadIO m => FileName -> BS8.ByteString -> ActionCtxT ctx m a
serveFile fileName val = do
let mimeType = defaultMimeLookup fileName
setHeader "Content-Type" (T.decodeUtf8 mimeType)
bytes val
-- | Send xml as response. Content-Type will be "application/xml"
xml :: MonadIO m => BS8.ByteString -> ActionCtxT ctx m a
xml val = do
setHeader "Content-Type" "application/xml; charset=utf-8"
bytes val
{-# INLINE xml #-}
| mayeranalytics/nanoPage | src/Internal/SpockExt.hs | mit | 897 | 0 | 10 | 192 | 194 | 107 | 87 | 19 | 1 |
{-# LANGUAGE NoMonomorphismRestriction
#-}
module Plugins.Gallery.Gallery.Manual30 where
import Diagrams.Prelude
eff = text "F" <> square 1 # lw 0
example = eff
<> reflectAbout (p2 (0.2,0.2)) (rotateBy (-1/10) unitX) eff
| andrey013/pluginstest | Plugins/Gallery/Gallery/Manual30.hs | mit | 240 | 0 | 11 | 49 | 81 | 44 | 37 | 6 | 1 |
module EitherMonadImplementation where
data Sum a b =
First a
| Second b
deriving (Eq, Show)
instance Functor (Sum a) where
fmap _ (First e) = First e
fmap f (Second x) = Second $ f x
instance Applicative (Sum a) where
pure = Second
(First e) <*> _ = First e
_ <*> (First e) = First e
(Second f) <*> (Second x) = Second $ f x
instance Monad (Sum a) where
return = pure
(First e) >>= _ = First e
(Second x) >>= f = f x
| NickAger/LearningHaskell | HaskellProgrammingFromFirstPrinciples/Chapter18.hsproj/EitherMonadImplementation.hs | mit | 468 | 0 | 8 | 141 | 235 | 116 | 119 | 17 | 0 |
{-# LANGUAGE OverloadedStrings, ExistentialQuantification, TemplateHaskell, QuasiQuotes, ViewPatterns #-}
module Timesheet where
import Data.Time.Calendar
import qualified Data.Aeson as JSON
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.ByteString as BS
import Data.List
import Data.Time
import Data.Aeson
import Control.Error hiding (err)
import Data.List.Utils (mergeBy)
import Data.Function (on)
import Control.Monad (when)
import Text.Printf.TH
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Network.HTTP.Types.URI (urlEncode)
import qualified Data.Aeson as Aeson
import Data.Char (chr)
import System.Timeout (timeout)
import Control.Concurrent.MSem
import Control.Concurrent.Async
import qualified Data.Traversable as T
import System.FilePath
import Paths_cigale_timesheet
import qualified Config
import qualified EventProviders
import EventProvider
import TsEvent
import Communication
-- 30 seconds max runtime before a fetch is aborted.
maxRuntimeFetchMicros :: Int
maxRuntimeFetchMicros = 30000000
fetchingConcurrentThreads :: Int
fetchingConcurrentThreads = 3
process :: Day -> IO (Bool, BL.ByteString)
process month = do
config <- Config.readConfig EventProviders.plugins
processConfig month config
fetchResponseAdd :: FetchResponse -> Either String [TsEvent] -> FetchResponse
fetchResponseAdd sofar@(FetchResponse _ errs) (Left err) = sofar { fetchErrors = err:errs }
fetchResponseAdd sofar@(FetchResponse ev _) (Right evts) =
sofar { fetchedEvents = mergeBy orderByDate ev (sortBy orderByDate evts) }
where orderByDate = compare `on` eventDate
-- http://stackoverflow.com/a/18898822/516188
mapPool :: T.Traversable t => Int -> (a -> IO b) -> t a -> IO (t b)
mapPool count f xs = do
sem <- new count
mapConcurrently (with sem . f) xs
processConfig :: Day -> [Config.EventSource Value Value] -> IO (Bool, BL.ByteString)
processConfig date config = do
myTz <- getTimeZone $ UTCTime date (secondsToDiffTime 8*3600)
putStrLn "before the fetching..."
settings <- getGlobalSettings
allEventsSeq <- mapPool fetchingConcurrentThreads
(\c -> fetchProvider (Config.srcName c) settings date c) config
let allEvents = foldl' fetchResponseAdd (FetchResponse [] []) allEventsSeq
let errors = filter isLeft allEventsSeq
when (not $ null errors) $ print errors
let eventDates = TsEvent.eventDate <$> fetchedEvents allEvents
let eventDatesLocal = fmap (utcToLocalTime myTz) eventDates
putStrLn "after the fetching!"
-- well would be faster to just check the first and last
-- element... but it's actually shorter to code like this..
let outOfRangeData = filter (outOfRange date (addDays 1 date)) eventDatesLocal
if null outOfRangeData
then return (null $ fetchErrors allEvents, JSON.encode allEvents)
else do
putStrLn "*** SOME EVENTS ARE NOT IN TIME RANGE"
print outOfRangeData
print $ head $ fetchedEvents allEvents
print $ last $ fetchedEvents allEvents
return (False, BL.empty)
where
outOfRange start end time = time < LocalTime start midnight || time > LocalTime end midnight
getGlobalSettings :: IO GlobalSettings
getGlobalSettings = do
settingsFolder <- Config.getSettingsFolder
appDataDir <- Paths_cigale_timesheet.getDataFileName "."
return GlobalSettings
{
getSettingsFolder = settingsFolder,
getDataFolder = appDataDir </> "../../cigale-web.jsexe/"
}
fetchProvider :: Text -> GlobalSettings -> Day -> Config.EventSource Value Value -> IO (Either String [TsEvent])
fetchProvider configItemName settings day eventSource = do
let provider = Config.srcProvider eventSource
putStrLn $ [s|fetching from %s (provider: %s)|]
(Config.srcName eventSource) (getModuleName provider)
let errorInfo = ((T.unpack (Config.srcName eventSource) ++ ": ") ++)
evts <- timeout maxRuntimeFetchMicros $
runExceptT $ fmapLT errorInfo $ getEvents provider
(Config.srcConfig eventSource) settings day (getExtraDataUrl configItemName)
putStrLn "Done"
return $ fromMaybe (Left $ errorInfo "Timeouted") evts
getExtraDataUrl :: Text -> Value -> Url
getExtraDataUrl (TE.encodeUtf8 -> configItemName) key = [s|/getExtraData?configItemName=%s&queryParams=%s|]
(toUrlParam configItemName) (toUrlParam $ BL.toStrict $ Aeson.encode key)
where toUrlParam = fmap (chr . fromIntegral) . BS.unpack . urlEncode True
getEventProvidersConfig :: BL.ByteString
getEventProvidersConfig = JSON.encode $ fmap getPluginConfig EventProviders.plugins
getPluginConfig :: EventProvider a b -> PluginConfig
getPluginConfig plugin = PluginConfig
{
cfgPluginName = getModuleName plugin,
cfgPluginConfig = getConfigType plugin
}
| emmanueltouzery/cigale-timesheet | src/WebServer/Timesheet.hs | mit | 4,879 | 0 | 16 | 882 | 1,314 | 684 | 630 | 99 | 2 |
module Data.Metric (
Metric(..),
Discrete(..),
Hamming(..),
Levenshtein(..),
RestrictedDamerauLevenshtein(..),
Euclidean(..),
Taxicab(..),
Chebyshev(..),
PostOffice(..)
) where
import Data.Metric.Class (Metric(..))
import Data.Metric.Set (Discrete(..))
import Data.Metric.String (Hamming(..), Levenshtein(..), RestrictedDamerauLevenshtein(..))
import Data.Metric.Vector.Real (Euclidean(..), Taxicab(..), Chebyshev(..), PostOffice(..))
| fmap/metric | src/Data/Metric.hs | mit | 455 | 0 | 6 | 51 | 167 | 116 | 51 | 14 | 0 |
--Find out whether a list is a palindrome.
module Main where
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome [] = True
isPalindrome xs = xs == reverse xs
main = do
if isPalindrome [1,2,3]
then putStrLn "fail"
else putStrLn "pass"
if isPalindrome [1,2,1]
then putStrLn "pass"
else putStrLn "fail"
if isPalindrome "madamimadam"
then putStrLn "pass"
else putStrLn "fail"
-- Why does this one error out???
-- answer: because isPalindrome is defined to require as using a list of objects which derive from Eq
-- the empty list is not a list of Eq objects
--if isPalindrome []
-- then putStrLn "pass"
-- else putStrLn "fail"
| butchhoward/xhaskell | 99questions/p06/p06.hs | mit | 655 | 12 | 9 | 140 | 152 | 82 | 70 | 14 | 4 |
{-# LANGUAGE TypeSynonymInstances,FlexibleInstances #-}
module DiffMonoid where
import Data.Monoid
type DiffMonoid a = a -> a
abs :: Monoid a => DiffMonoid a -> a
abs a = a mempty
rep :: Monoid a => a -> DiffMonoid a
rep = mappend
instance Monoid a => Monoid (DiffMonoid a) where
mempty = rep mempty
mappend = (.)
| atzeus/reflectionwithoutremorse | CPS/DiffMonoid.hs | mit | 324 | 0 | 7 | 67 | 111 | 59 | 52 | 11 | 1 |
module Import
( module Import
) where
import Prelude as Import hiding (head, init, last,
readFile, tail, writeFile)
import Yesod as Import hiding (Route (..))
import Control.Applicative as Import (pure, (<$>), (<*>))
import Data.Text as Import (Text)
import Foundation as Import
import Model as Import
import Settings as Import
import Settings.Development as Import
import Settings.StaticFiles as Import
-- | Yesod-Angular Client Route specific
import ClientHandler as Import
import ClientRoutes as Import
import Controllers as Import
#if __GLASGOW_HASKELL__ >= 704
import Data.Monoid as Import
(Monoid (mappend, mempty, mconcat),
(<>))
#else
import Data.Monoid as Import
(Monoid (mappend, mempty, mconcat))
infixr 5 <>
(<>) :: Monoid m => m -> m -> m
(<>) = mappend
#endif
| smurphy8/yesod-angular-sqlite | Import.hs | mit | 1,245 | 0 | 6 | 585 | 158 | 117 | 41 | 20 | 1 |
{- main = do -}
{- a <- getLine -}
{- b <- getLine -}
{- c <- getLine -}
{- print [a,b,c] -}
main = do
rs <- sequence [getLine, getLine, getLine]
print rs
| yhoshino11/learning_haskell | ch8/sequence.hs | mit | 168 | 0 | 9 | 48 | 36 | 20 | 16 | 3 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.RTCStatsReport
(js_stat, stat, js_names, names, js_getTimestamp, getTimestamp,
js_getId, getId, js_getType, getType, js_getLocal, getLocal,
js_getRemote, getRemote, RTCStatsReport, castToRTCStatsReport,
gTypeRTCStatsReport)
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 (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
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.Enums
foreign import javascript unsafe "$1[\"stat\"]($2)" js_stat ::
JSRef RTCStatsReport -> JSString -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCStatsReport.stat Mozilla RTCStatsReport.stat documentation>
stat ::
(MonadIO m, ToJSString name, FromJSString result) =>
RTCStatsReport -> name -> m result
stat self name
= liftIO
(fromJSString <$>
(js_stat (unRTCStatsReport self) (toJSString name)))
foreign import javascript unsafe "$1[\"names\"]()" js_names ::
JSRef RTCStatsReport -> IO (JSRef [result])
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCStatsReport.names Mozilla RTCStatsReport.names documentation>
names ::
(MonadIO m, FromJSString result) => RTCStatsReport -> m [result]
names self
= liftIO
((js_names (unRTCStatsReport self)) >>= fromJSRefUnchecked)
foreign import javascript unsafe "$1[\"timestamp\"]"
js_getTimestamp :: JSRef RTCStatsReport -> IO (JSRef Date)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCStatsReport.timestamp Mozilla RTCStatsReport.timestamp documentation>
getTimestamp :: (MonadIO m) => RTCStatsReport -> m (Maybe Date)
getTimestamp self
= liftIO ((js_getTimestamp (unRTCStatsReport self)) >>= fromJSRef)
foreign import javascript unsafe "$1[\"id\"]" js_getId ::
JSRef RTCStatsReport -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCStatsReport.id Mozilla RTCStatsReport.id documentation>
getId ::
(MonadIO m, FromJSString result) => RTCStatsReport -> m result
getId self
= liftIO (fromJSString <$> (js_getId (unRTCStatsReport self)))
foreign import javascript unsafe "$1[\"type\"]" js_getType ::
JSRef RTCStatsReport -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCStatsReport.type Mozilla RTCStatsReport.type documentation>
getType ::
(MonadIO m, FromJSString result) => RTCStatsReport -> m result
getType self
= liftIO (fromJSString <$> (js_getType (unRTCStatsReport self)))
foreign import javascript unsafe "$1[\"local\"]" js_getLocal ::
JSRef RTCStatsReport -> IO (JSRef RTCStatsReport)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCStatsReport.local Mozilla RTCStatsReport.local documentation>
getLocal ::
(MonadIO m) => RTCStatsReport -> m (Maybe RTCStatsReport)
getLocal self
= liftIO ((js_getLocal (unRTCStatsReport self)) >>= fromJSRef)
foreign import javascript unsafe "$1[\"remote\"]" js_getRemote ::
JSRef RTCStatsReport -> IO (JSRef RTCStatsReport)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCStatsReport.remote Mozilla RTCStatsReport.remote documentation>
getRemote ::
(MonadIO m) => RTCStatsReport -> m (Maybe RTCStatsReport)
getRemote self
= liftIO ((js_getRemote (unRTCStatsReport self)) >>= fromJSRef) | plow-technologies/ghcjs-dom | src/GHCJS/DOM/JSFFI/Generated/RTCStatsReport.hs | mit | 3,966 | 44 | 11 | 578 | 953 | 539 | 414 | 65 | 1 |
module Handler.Quiz where
import Import
import Yesod.Form.Jquery
import Data.Aeson.Types (Result(..))
import Data.List (nub)
data FormQuiz = FormQuiz {
fqTitle :: Text,
fqTopic :: Text,
fqPublic :: Bool
}
data FormQuestion = FormQuestion {
{- Hardcoded answers is ugly, but I don't see a better way to do it with plain HTML -}
fqQuestion :: Text,
fqAnswer1 :: Text, fqAnswer1C :: Bool,
fqAnswer2 :: Text, fqAnswer2C :: Bool,
fqAnswer3 :: Text, fqAnswer3C :: Bool,
fqAnswer4 :: Text, fqAnswer4C :: Bool
}
createQuestionForm :: Html -> MForm Handler (FormResult FormQuestion, Widget)
createQuestionForm = renderDivs $ FormQuestion
<$> areq textField "Question" Nothing
<*> areq textField "Answer 1" Nothing
<*> areq checkBoxField "Correct?" Nothing
<*> areq textField "Answer 2" Nothing
<*> areq checkBoxField "Correct?" Nothing
<*> areq textField "Answer 3" Nothing
<*> areq checkBoxField "Correct?" Nothing
<*> areq textField "Answer 4" Nothing
<*> areq checkBoxField "Correct?" Nothing
createAnswers :: [(Text, Bool)] -> Key Question -> Handler ()
createAnswers ((answer, correct):answers) qId = do
_ <- runDB $ insert (Answer qId answer correct)
createAnswers answers qId
createAnswers [] _ = return ()
createAnswersJson :: [Answer] -> Handler ()
createAnswersJson [] = return ()
createAnswersJson (answer:answers) = (runDB $ insert answer) >> createAnswersJson answers
createQuestion :: Question -> [(Text, Bool)] -> Key Quiz -> Handler ()
createQuestion question answers qId = do
questionId <- runDB $ insert $ question {questionQuizId = qId}
_ <- createAnswers answers questionId
return ()
createQuestionNoAnswers :: Question -> Key Quiz -> Handler (Key Question)
createQuestionNoAnswers question quizId = runDB $ insert $ question {questionQuizId = quizId}
createQuestionF :: FormResult FormQuestion -> Key Quiz -> HandlerT App IO ()
createQuestionF formResult qId =
case formResult of
FormSuccess (FormQuestion question a1 c1 a2 c2 a3 c3 a4 c4) -> createQuestion (Question qId question) [(a1, c1), (a2, c2), (a3, c3), (a4, c4)] qId
_ -> return ()
createQuizForm :: Html -> MForm Handler (FormResult FormQuiz, Widget)
createQuizForm = renderDivs $ FormQuiz
<$> areq textField "Title" Nothing
<*> areq textField "Topic" Nothing
<*> areq checkBoxField "Public" Nothing
createQuizF :: FormQuiz -> Key User -> HandlerT App IO ()
createQuizF (FormQuiz title topic public) userId = createQuiz (Quiz title userId topic public) userId
createQuiz :: Quiz -> Key User -> Handler ()
createQuiz quiz userId = do
_ <- runDB $ insert $ quiz {quizUserId = userId}
return ()
getQuizzesR :: Handler TypedContent
getQuizzesR = do
mAuth <- maybeAuth
(quizForm, enctype) <- generateFormPost createQuizForm
quizzes <- getAvailableQuizzes $ fmap entityKey mAuth
selectRep $ do
provideJson quizzes
provideRep $ defaultLayout $ do
setTitle "Quizzes"
$(widgetFile "quizlist")
postQuizzesR :: Handler TypedContent
postQuizzesR = do
auth <- requireAuth
((result, _), _) <- runFormPost createQuizForm
jsonQuiz <- parseJsonBody
case jsonQuiz of
Success quiz -> do
createQuiz quiz $ entityKey auth
redirect QuizzesR
Error jsonError -> do
case result of
FormSuccess fq -> do
createQuizF fq $ entityKey auth
redirect QuizzesR
FormFailure formError -> do
selectRep $ do
provideJson $ object ["error" .= jsonError]
provideRep $ return [shamlet|<p>Error in form submission: #{show formError}|]
data QuizQuestion = QuizQuestion Text [Answer]
instance ToJSON QuizQuestion where
toJSON (QuizQuestion question answers) = object
[
"question" .= question
, "answers" .= answers
]
data QuizInfo = QuizInfo (Key Quiz) (Maybe Quiz) [QuizQuestion] Bool
instance ToJSON QuizInfo where
toJSON (QuizInfo k q qs o) = object
[
"id" .= k
, "maybequiz" .= q
, "questions" .= qs
, "owner" .= o
]
getQuizR :: Key Quiz -> Handler TypedContent
getQuizR qId = do
(questionForm, enctype) <- generateFormPost createQuestionForm
questions <- getQuestions qId
let jsonQuestions = map (\(question, answers) -> QuizQuestion (questionQuestion $ entityVal question) (map entityVal answers)) questions
mAuth <- maybeAuth
quiz <- runDB $ get qId
-- Get the data out of the various Monads involved and determine if the user is the owner of the quiz
{- let ownsQuiz = case (quiz >>= (\q -> mAuth >>= (\m -> return (entityKey m == quizUserId q)))) of
Nothing -> False
Just x -> x -}
let ownsQuiz = case do { -- Haven't compiled yet, might not pass the type checker
quizResult <- quiz;
auth <- mAuth;
return $ entityKey auth == quizUserId quizResult;
} of
Nothing -> False
Just x -> x
let quizAccess = ownsQuiz ||
case quiz of
Nothing -> False
Just q -> quizPublicAccess q
selectRep $ do
provideJson $ case quizAccess of
True -> QuizInfo qId quiz jsonQuestions ownsQuiz
False -> QuizInfo qId Nothing [] False
provideRep $ defaultLayout $ do
setTitle "Quiz"
$(widgetFile "quiz")
deleteQuizR :: Key Quiz -> Handler TypedContent
deleteQuizR quizId = do
auth <- requireAuth
mQuiz <- runDB $ get quizId
case mQuiz of
Nothing -> redirect QuizzesR
Just quiz -> if quizUserId quiz == entityKey auth
then (runDB $ delete quizId) >> redirect QuizzesR
else selectRep $ do
provideJson $ object ["error" .= ("You do not own this quiz" :: Text)]
provideRep $ return [shamlet|<p>You do not own this quiz|]
postQuestionR :: Key Quiz -> Handler TypedContent
postQuestionR qId = do
auth <- requireAuth
mQuiz <- runDB $ get qId
case mQuiz of
Just quiz ->
if (quizUserId quiz) == entityKey auth -- Verify that the person sending the request owns the quiz
then do
((result, _), _) <- runFormPost createQuestionForm
jsonQuestion <- parseJsonBody
case jsonQuestion of
Success question -> do
questionId <- createQuestionNoAnswers question qId
selectRep $ do
provideJson questionId
provideRep $ return [shamlet|<p>Question id: #{show questionId}|]
Error _ -> do
createQuestionF result qId
redirect (QuizR qId)
else redirect (QuizR qId)
Nothing -> redirect HomeR
postAnswerR :: Handler Value
postAnswerR = do
auth <- requireAuth
jsonAnswers <- parseJsonBody
case jsonAnswers of
Success answers -> do
case answers of
[] -> return $ object ["error" .= ("empty answer list" :: Text)]
answers@(answer:_) -> do
maybeQuestion <- runDB $ get $ answerQuestionId answer
maybeQuiz <- case maybeQuestion of
Nothing -> return Nothing
Just question -> (runDB . get. questionQuizId) question
case maybeQuiz of
Nothing -> return $ object ["error" .= ("nonexistent quiz" :: Text)]
Just quiz -> if quizUserId quiz == entityKey auth
then do
createAnswersJson $ map (\x -> x {answerQuestionId = answerQuestionId answer}) answers -- Make sure the question IDs are all the same
return $ object ["success" .= True]
else return $ object ["error" .= ("user does not own quiz" :: Text)]
Error error -> return $ object ["error" .= error]
getFilteredQuizzesR :: Text -> Handler TypedContent
getFilteredQuizzesR topic = do
mAuth <- maybeAuth
quizzes <- case mAuth of
Just auth -> filterByTopic (entityKey auth) topic
Nothing -> filterByTopicNoUser topic
selectRep $ do
provideJson quizzes
provideRep $ do
(quizForm, enctype) <- generateFormPost createQuizForm
defaultLayout $ do
setTitle $ toHtml $ "Quizzes with Topic: " ++ topic
$(widgetFile "quizlist")
getAvailableQuizzes :: Maybe (Key User) -> Handler [Entity Quiz]
getAvailableQuizzes mUserId = case mUserId of
Nothing -> getPublicQuizzes
Just userId -> runDB $ do
shared <- selectList [SharedQuizUserId ==. userId] []
let ownedFilter = [QuizUserId ==. userId]
let sharedQuizIds = map (sharedQuizQuizId . entityVal) shared
let ownedOrSharedFilter = foldr (||.) ownedFilter $ map (\id -> [QuizId ==. id]) sharedQuizIds
let availableFilter = ownedOrSharedFilter ||. [QuizPublicAccess ==. True]
selectList availableFilter []
getPublicQuizzes :: Handler [Entity Quiz]
getPublicQuizzes = runDB $ selectList [QuizPublicAccess ==. True] []
getAnswers :: Key Question -> HandlerT App IO [Entity Answer]
getAnswers qId = runDB $ do
answers <- selectList [AnswerQuestionId ==. qId] []
return answers
getAllAnswers :: [Entity Question] -> HandlerT App IO [(Entity Question, [Entity Answer])]
-- Loop to recursively get answers, paird with the appropriate questions, for a given quiz
getAllAnswers (q:questions) = do
answers <- getAnswers $ entityKey q
rest <- getAllAnswers questions
return $ (q, answers):rest
getAllAnswers [] = return []
getQuestions :: Key Quiz -> HandlerT App IO [(Entity Question, [Entity Answer])]
getQuestions qId = do
questions <- runDB $ selectList [QuestionQuizId ==. qId] []
allAnswers <- getAllAnswers questions
return allAnswers
filterByTopic :: Key User -> Text -> Handler [Entity Quiz]
filterByTopic userId topic = runDB $ selectList (([QuizPublicAccess ==. True] ||. [QuizUserId ==. userId]) ++ [QuizTopic ==. topic]) []
filterByTopicNoUser :: Text -> Handler [Entity Quiz]
filterByTopicNoUser topic = runDB $ selectList [QuizPublicAccess ==. True, QuizTopic ==. topic] []
| quantum-dan/HasKnowledge | Handler/Quiz.hs | mit | 9,786 | 0 | 29 | 2,288 | 3,020 | 1,489 | 1,531 | -1 | -1 |
import System.Environment (getArgs)
import Data.Char (isUpper)
import Control.Monad (liftM, (>=>))
import Control.Monad.Writer.Lazy (Writer, writer, tell, execWriter)
import Control.Monad.Trans.Maybe (MaybeT, runMaybeT)
type Out a = MaybeT (Writer String) a
exitWith :: String -> Out a
exitWith s = tell s >> fail ""
data Cmd = I Item
| Apply
instance Show Cmd where
show (I i) = "C" ++ show i
show Apply = "!"
data Item = Blank
| Funct {arity :: Int,
rule :: [Item] -> Out [Item]}
instance Show Item where
show Blank = "?"
show (Funct n _) = show n ++ "F"
apply :: Cmd -> [Item] -> Out [Item]
apply Apply (Funct 1 f : i : is) = liftM (++is) $ f [i]
apply Apply (Funct n f : i : is) = return $ (Funct (n-1) $ f . (i:)) : is
apply Apply (Blank : _) = exitWith $ "Error: tried to apply blank"
apply Apply [Funct n f] = f []
apply Apply [] = exitWith "Error: tried to apply empty list"
apply (I i) is = return $ i : is
parse :: String -> [Cmd]
parse = map parse'
. concatMap separate
. concatMap (words . takeWhile (not . isUpper))
. lines
where separate "" = []
separate s@(c:str) =
if c `elem` symbols
then [c] : separate str
else wd : separate rest
where (wd,rest) = span (not . (`elem` symbols)) s
symbols = "!?+>/$.@"
parse' "!" = Apply
parse' "?" = I Blank
parse' "clone" = clone
parse' "+" = clone
parse' "shift" = shift
parse' ">" = shift
parse' "fork" = fork
parse' "/" = fork
parse' "call" = call
parse' "$" = call
parse' "chain" = chain
parse' "." = chain
parse' "say" = say
parse' "@" = say
interpret :: String -> String
interpret = execWriter . runMaybeT . ($ []) . foldr1 (>=>) . map apply . parse
main :: IO ()
main = do
[file] <- getArgs
prog <- readFile file
putStrLn $ interpret prog
clone = let f (i : is) = return $ i:i:is
f [] = exitWith "Error: tried to apply clone to empty list"
in I $ Funct 1 f
shift = let f (Funct n g : is) = return $ Funct (n+1) h : is
where h (x:xs) = liftM (x:) $ g xs
h [] = exitWith $ "Error: tried to apply shifted " ++ show (n+1) ++ "-ary function to empty list"
f is@(Blank:_) = exitWith "Error: tried to apply shift to blank"
f [] = exitWith "Error: tried to apply shift to empty list"
in I $ Funct 1 f
fork = let f (Blank : i : _ : is) = return $ i : is
f (_ : _ : is) = return is
f is = exitWith $ "Error: tried to apply fork to " ++ show (length is) ++ "-element list"
in I $ Funct 3 f
call = I $ Funct 2 $ apply Apply
chain = let f (Funct m h : Funct n g : is) =
return $ (Funct m $ h >=> \js -> liftM (++ drop n js) $ g (take n js)):is
f (_ : _ : is) = exitWith "Error: tried to apply chain to blank"
f is = exitWith $ "Error: tried to apply fork to " ++ show (length is) ++ "-element list"
in I $ Funct 2 f
say = let f is@(Blank : _) = writer (is,"0")
f is@(_ : _) = writer (is,"1")
f is = exitWith "Error: tried to apply say to empty list"
in I $ Funct 1 f | iatorm/shift | shift.hs | mit | 3,268 | 0 | 17 | 1,060 | 1,390 | 714 | 676 | 82 | 16 |
module Cmds ( cmdList ) where
import Types
import IrcBot
import Data.List
import Network
import System.Time
import System.Exit
import Data.List.Split
import Control.Concurrent.MVar
import Control.Monad.Reader
cmdList = [ IRCCommand { name="updatetopic", function=cmdUpdateTopic, description="Updates to topic to display the current Topic " ++ nick ++ " has (Must be Owner)" }
, IRCCommand { name="uptime", function=cmdUpTime, description="Displays " ++ nick ++ " current uptime" }
, IRCCommand { name="addtopic", function=cmdAddTopic, description="Adds any text after '!addtopic' as an entry onto the topic (Must be Owner)" }
, IRCCommand { name="deltopic", function=cmdDelTopic, description="Removes the left-most entry in the current Topic (Must be Owner)" }
, IRCCommand { name="echo", function=cmdEcho, description="Makes " ++ nick ++ " say any text after '!echo'" }
, IRCCommand { name="quit", function=cmdQuit, description="Make " ++ nick ++ " Exit the " ++ chan ++ " and quit (Must be Owner)" }
, IRCCommand { name="displayowners", function=cmdDisplayOwners, description="Show a list of all the owners" }
, IRCCommand { name="help", function=cmdHelp, description="Display usage and list of commands" }
]
cmdUpdateTopic :: IRCMessage -> Net ()
cmdUpdateTopic (IRCMessage { user = usr })=
liftIO (usrIsOwner usr) >>= \isUser ->
if isUser
then updateTopic topic
else return ()
cmdUpTime :: IRCMessage -> Net ()
cmdUpTime (IRCMessage { channel = ch }) =
uptime >>= privmsg (ch)
cmdAddTopic :: IRCMessage -> Net ()
cmdAddTopic (IRCMessage { fullText = x, user = usr }) =
liftIO (usrIsOwner usr) >>= \isUser ->
if isUser
then liftIO $ addTopic (drop 10 x) topic
else return ()
cmdDelTopic :: IRCMessage -> Net ()
cmdDelTopic (IRCMessage { user = usr }) =
liftIO (usrIsOwner usr) >>= \isUser ->
if isUser
then liftIO $ delTopic topic
else return ()
cmdEcho :: IRCMessage -> Net ()
cmdEcho (IRCMessage { semiText = x, channel = ch }) =
privmsg (ch) (drop 6 x)
cmdQuit :: IRCMessage -> Net ()
cmdQuit (IRCMessage { user = usr }) =
liftIO (usrIsOwner usr) >>= \isUser ->
if isUser
then write "QUIT" ":Exiting" >> (liftIO (exitWith ExitSuccess))
else return ()
cmdHelp :: IRCMessage -> Net ()
cmdHelp (IRCMessage { fullText = x, user = usr }) =
privmsg usr ("To use me, type one of the below commands as a message. Include any text after the command as nessisary") >>
displayOwners usr >>
cmdHelp' usr cmdList
cmdHelp' :: String -> [IRCCommand] -> Net ()
cmdHelp' _ [] = return ()
cmdHelp' usr (cmd:cmds) = privmsg usr (formatCmd cmd) >> cmdHelp' usr cmds
where
formatCmd (IRCCommand { name = name, description = desc }) = (name) ++ " -- " ++ (desc)
cmdDisplayOwners :: IRCMessage -> Net ()
cmdDisplayOwners (IRCMessage { channel = ch }) = displayOwners ch
usrIsOwner :: String -> IO Bool
usrIsOwner usr = readMVar owners >>= \own -> return (usr `elem` own)
uptime :: Net String
uptime =
liftIO (getClockTime) >>= \now ->
asks starttime >>= \zero ->
(return (pretty (diffClockTimes now zero)))
pretty :: TimeDiff -> String
pretty td = join . intersperse " " . filter (not . null) . map f $
[ (years ,"y") ,(months `mod` 11,"m")
, (days `mod` 18,"d") ,(hours `mod` 24,"h")
, (mins `mod` 60,"m") ,(secs `mod` 60,"s")
]
where
secs = abs $ tdSec td ; mins = secs `div` 60
hours = mins `div` 60 ; days = hours `div` 24
months = days `div` 28 ; years = months `div` 12
f (i,s) | i == 0 = []
| otherwise = show i ++ s
formatTopic :: [String] -> String
formatTopic t = intercalate " | " t
addTopic :: String -> MVar [String] -> IO ()
addTopic x t =
takeMVar t >>= \top ->
putMVar t (x : top)
delTopic :: MVar [String] -> IO ()
delTopic t =
takeMVar t >>= \top ->
putMVar t (drop 1 top)
updateTopic :: MVar [String] -> Net ()
updateTopic t =
liftIO (readMVar t) >>= \top ->
liftIO (putStrLn ("NewTopic: " ++ head top)) >>
write "TOPIC" (chan ++ " :" ++ formatTopic top)
numberList :: [String] -> [String]
numberList [] = []
numberList lis = numberList' lis 1
numberList' :: [String] -> Int -> [String]
numberList' [] n = []
numberList' (x:xs) n = ((show n) ++ ". " ++ x) : numberList' xs (n+1)
displayOwners :: String -> Net ()
displayOwners ch =
liftIO (readMVar owners) >>= \o ->
privmsg ch ("Owners: " ++ (intercalate " " (numberList o)))
| DSMan195276/QB64Bot | Cmds.hs | gpl-2.0 | 4,680 | 0 | 14 | 1,179 | 1,676 | 912 | 764 | 101 | 2 |
import System.IO
import System.Random
main = do
contents <- readFile "/home/anand/workspace/my_projects/Miscellaneous/Quotes.txt"
let Quotes = split "~Aang Jie" contents
writeFile "/home/anand/.signature" rand_quote
| softwaremechanic/Miscellaneous | Haskell/I_O/rand_quote.hs | gpl-2.0 | 223 | 0 | 10 | 28 | 49 | 22 | 27 | 6 | 1 |
{- HHammer: Haskell bindings to Hammer.
Copyright 2013 Nikita Karetnikov <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 2.
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.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-}
import Distribution.Simple
main = defaultMain
| nkaretnikov/hhammer | Setup.hs | gpl-2.0 | 800 | 0 | 4 | 157 | 12 | 7 | 5 | 2 | 1 |
module Hdcpu16.Parser (parseins) where
import Hdcpu16.Types
import Text.Parsec
import Text.Parsec.String
import Data.Either
import qualified Text.Parsec.Token as P
import Text.Parsec.Language (emptyDef)
import Data.Map
import Data.Word
import Data.Maybe
--The Big daddy
parseins :: String -> IO [Instruction]
parseins fn = do
str <- readFile fn
let ins = runParser program () fn str
case ins of
Right res -> do
let ins' = Prelude.filter (not .islbl) $ Prelude.map (\x -> fixids x (rlabels (concat res) 0 Data.Map.empty)) (concat res)
return ins'
(Left _) -> error "Parsing error"
--
--
--since it's not horribly fancy I won't bother with monads here
--init values are rlabels ins 0 Map.empty
rlabels :: [Instruction] -> Word16 -> Map String Word16 -> Map String Word16
rlabels [] _ m = m
rlabels ((L (Label s)):xs) i m = rlabels xs i (insert s i m)
rlabels (n:ns) i m = rlabels ns (i+(inslen n)) m
fixids :: Instruction -> Map String Word16 -> Instruction
fixids (BI oc (Ident s1) (Ident s2)) m = BI oc (fixop s1 m) (fixop s2 m)
fixids (BI oc (Ident s1) o) m = BI oc (fixop s1 m) o
fixids (BI oc o (Ident s1)) m = BI oc o (fixop s1 m)
fixids (NBI oc (Ident s1)) m = NBI oc (fixop s1 m)
fixids n _ = n
fixop i m = let r = fromJust $ Data.Map.lookup i m
in NWLit r
islbl ((L _)) = True
islbl _ = False
---Parsec stuff
program = do
ins <- manyTill line eof
return ins
-- Main Program
--
lexer :: P.TokenParser ()
lexer = P.makeTokenParser
(emptyDef
{
P.commentLine = ";",
P.reservedNames = ["A","B","C","X","Y","Z","I","J","POP","PEEK","PUSH","SP","PC","O",
"SET","ADD","SUB","MUL","DIV","MOD","SHL","SHR","AND","BOR","XOR",
"IFE","IFN","IFG","IFB","JSR"]
})
whiteSpace = P.whiteSpace lexer
lexeme = P.lexeme lexer
symbol = P.symbol lexer
natural = P.natural lexer
parens = P.parens lexer
brackets = P.brackets lexer
semi = P.semi lexer
colon = P.colon lexer
identifier = P.identifier lexer
reserved = P.reserved lexer
reservedOp = P.reservedOp lexer
line = do
optional whiteSpace
l <- optionMaybe lbl
whiteSpace
i <- optionMaybe instruction
optional whiteSpace
case (l,i) of
(Nothing,Nothing) -> return []
(Just x,Nothing) -> return [L x]
(Just x,Just y) -> return [L x,y]
(Nothing,Just y) -> return [y]
instruction :: Parser Instruction
instruction = do
try (do
oc <- opcode
op1 <- operand
symbol (",")
op2 <- operand
return $ BI oc op1 op2)
<|> try (do nb <- nbopcode; op <- operand; return $ NBI nb op)
lbl :: Parser Label
lbl = do
colon
n <- identifier
return $ Label n
opcode :: Parser Opcode
opcode = try (do
reserved "SET"
return SET)
<|>try (do
reserved "ADD"
return ADD)
<|>try (do
reserved "SUB"
return SUB)
<|>try (do
reserved "MUL"
return MUL)
<|>try (do
reserved "DIV"
return DIV)
<|>try (do
reserved "MOD"
return MOD)
<|>try (do
reserved "SHL"
return SHL)
<|>try (do
reserved "SHR"
return SHR)
<|>try (do
reserved "AND"
return AND)
<|>try (do
reserved "BOR"
return BOR)
<|>try (do
reserved "XOR"
return XOR)
<|>try (do
reserved "IFE"
return IFE)
<|>try (do
reserved "IFN"
return IFN)
<|>try (do
reserved "IFG"
return IFG)
<|>do
reserved "IFB"
return IFB
nbopcode :: Parser NBOpcode
nbopcode = do
reserved "JSR"
return JSR
operand :: Parser Operand
operand = do
reg <- register --should probably be tidied up to use "reserved" instead
return $ Reg reg
<|>do
try (do reserved "PC"; return PC) <|> try (do reserved "PEEK"; return PEEK) <|> try (do reserved "POP"; return POP) <|> do reserved "PUSH"; return PUSH
<|>do
reserved "SP"
return SP
<|>do
reserved "O"
return SP
<|>do
try (brackets (do reg <- register; return $ RRef reg))
<|>do
try (brackets (do nat <- natural; return $ NWRef (fromIntegral nat))) --TODO: Add error checking on nat size
<|>do
try (brackets (do nat <- natural; oplus; reg <- register; return $ RNW reg (fromIntegral nat))) --TODO: Clean this up to check for small nums
<|>do
try (do
nat <- natural
if nat >=0x0 && nat <= 0x1F
then return $ LV $ fromIntegral (nat + 0x20)
else return $ NWLit $ fromIntegral nat) --TODO: Add error checking on nat size
<|>do
i <- identifier
return $ Ident i
oplus :: Parser ()
oplus = do
whiteSpace
char '+'
whiteSpace
return ()
register :: Parser Register
register = do
whiteSpace
reg <- oneOf "ABCXYZIJ"
whiteSpace
return $ mpreg reg
--testing and debugging
testparser p str = runParser p () "tester" str
testprog fn = do
s <- readFile fn
let output = testparser program s
return output
--Ancillary character mappings
mpreg str = case str of
'A' -> A
'B' -> B
'C' -> C
'X' -> X
'Y' -> Y
'Z' -> Z
'I' -> I
'J' -> J
--word length of operands
oplen op = case op of
(RNW _ _) -> 1
(NWRef _) -> 1
(NWLit _) -> 1
(Ident _) -> 1
_ -> 0
--byte length of instructions
inslen (BI _ o1 o2) = (1 + (oplen o1) + (oplen o2))
inslen (NBI _ o1) = (1 + (oplen o1))
inslen (L _) = 0
| igraves/hdcpu16 | Hdcpu16/Parser.hs | gpl-3.0 | 6,544 | 1 | 23 | 2,646 | 2,270 | 1,097 | 1,173 | 191 | 8 |
module Lamdu.Sugar.Convert.TIdG
( convert
) where
import Data.UUID.Types (UUID)
import qualified Lamdu.Calc.Type as T
import qualified Lamdu.Expr.UniqueId as UniqueId
import Lamdu.Sugar.Types
convert :: T.NominalId -> TIdG UUID
convert tid =
TIdG
{ _tidgName = UniqueId.toUUID tid
, _tidgTId = tid
}
| da-x/lamdu | Lamdu/Sugar/Convert/TIdG.hs | gpl-3.0 | 346 | 0 | 8 | 87 | 89 | 56 | 33 | 11 | 1 |
{-# LANGUAGE ScopedTypeVariables
#-}
module Crypto.Simple (newMasterKey, readMasterKey, encrypt, decrypt)
where
import qualified Crypto.NaCl.Encrypt.Stream as NaCl
import qualified Crypto.NaCl.Nonce as Nonce
import Data.ByteString.Char8 as B
import Data.Serialize as S
import Data.Word
import System.Entropy (getEntropy)
import Crypto.Classes (hash')
import Crypto.HMAC (MacKey(..), hmac')
import Crypto.Skein (Skein_256_256)
import Crypto.Scrypt (scrypt')
type PlainText = ByteString
type CipherText = ByteString
{-| Key types -}
newtype MasterKey = MasterKey { unMasterKey :: ByteString }
instance S.Serialize MasterKey where
get = MasterKey `fmap` S.getByteString NaCl.keyLength
put = S.putByteString . unMasterKey
newtype Passphrase = Passphrase { unPassphrase :: ByteString }
newtype ExportedKey = ExportedKey { unExportedKey :: ByteString }
newtype Key = Key { unKey :: ByteString }
newMasterKey :: FilePath -> IO ()
newMasterKey path =
do key <- MasterKey `fmap` getEntropy NaCl.keyLength
B.writeFile path $ encode key
readMasterKey :: FilePath -> IO (Either String MasterKey)
readMasterKey path =
S.decode `fmap` B.readFile path
encrypt :: MasterKey -> ByteString -> IO ByteString
encrypt (MasterKey key) plainT = cipherT
where
cipherT = do
nonce <- Nonce.createRandomNonce NaCl.nonceLength
return $ encode (Nonce.toBS nonce, NaCl.encrypt nonce plainT key)
decrypt :: MasterKey -> CipherText -> Either String PlainText
decrypt (MasterKey key) cipherT =
case decode cipherT of
Left s -> Left s
Right (bsNonce, bsCipher) ->
Right $ NaCl.decrypt (Nonce.fromBS bsNonce) bsCipher key
| br0ns/hindsight | src/Crypto/Simple.hs | gpl-3.0 | 1,722 | 0 | 13 | 346 | 489 | 274 | 215 | 39 | 2 |
module Main where
import System.Environment
l :: Int -> Int
l n = Prelude.sum
[ k * m
| k <- [1..n]
, m <- [1..k]
]
main :: IO ()
main = do
[arg] <- getArgs
print (l (read arg))
{-
$ time ./ComprehensionsFoldrBuild 3000 +RTS -K200M -s
10136253375250
396,388,640 bytes allocated in the heap
83,384 bytes copied during GC
44,416 bytes maximum residency (2 sample(s))
21,120 bytes maximum slop
1 MB total memory in use (0 MB lost due to fragmentation)
Tot time (elapsed) Avg pause Max pause
Gen 0 764 colls, 0 par 0.00s 0.00s 0.0000s 0.0000s
Gen 1 2 colls, 0 par 0.00s 0.00s 0.0001s 0.0001s
INIT time 0.00s ( 0.00s elapsed)
MUT time 0.05s ( 0.05s elapsed)
GC time 0.00s ( 0.00s elapsed)
EXIT time 0.00s ( 0.00s elapsed)
Total time 0.06s ( 0.06s elapsed)
%GC time 4.7% (4.7% elapsed)
Alloc rate 7,403,040,409 bytes per MUT second
Productivity 95.1% of total user, 96.8% of total elapsed
real 0m0.058s
user 0m0.053s
sys 0m0.003s
-}
| jyp/ControlledFusion | ComprehensionsFoldrBuild.hs | gpl-3.0 | 1,189 | 0 | 11 | 430 | 108 | 57 | 51 | 11 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- |
-- Copyright : (c) 2012 Simon Meier
-- License : GPL v3 (see LICENSE)
--
-- Maintainer : Simon Meier <[email protected]>
-- Portability : portable
--
-- Computate an under-approximation to the set of all facts with unique
-- instances, i.e., fact whose instances never occur more than once in a
-- state. We use this information to reason about protocols that exploit
-- exclusivity of linear facts.
module Theory.Tools.InjectiveFactInstances (
-- * Computing injective fact instances.
simpleInjectiveFactInstances
) where
import Extension.Prelude (sortednub)
import Control.Applicative
import Control.Monad.Fresh
import Data.Label
import qualified Data.Set as S
import Safe (headMay)
import Theory.Model
-- | Compute a simple under-approximation to the set of facts with injective
-- instances. A fact-tag is has injective instances, if there is no state of
-- the protocol with more than one instance with the same term as a first
-- argument of the fact-tag.
--
-- We compute the under-approximation by checking that
-- (1) the fact-tag is linear,
-- (2) every introduction of such a fact-tag is protected by a Fr-fact of the
-- first term, and
-- (3) every rule has at most one copy of this fact-tag in the conlcusion and
-- the first term arguments agree.
--
-- We exclude facts that are not copied in a rule, as they are already handled
-- properly by the naive backwards reasoning.
simpleInjectiveFactInstances :: [ProtoRuleE] -> S.Set FactTag
simpleInjectiveFactInstances rules = S.fromList $ do
tag <- candidates
guard (all (guardedSingletonCopy tag) rules)
return tag
where
candidates = sortednub $ do
ru <- rules
tag <- factTag <$> get rConcs ru
guard $ (factTagMultiplicity tag == Linear)
&& (tag `elem` (factTag <$> get rPrems ru))
return tag
guardedSingletonCopy tag ru =
length copies <= 1 && all guardedCopy copies
where
prems = get rPrems ru
copies = filter ((tag ==) . factTag) (get rConcs ru)
firstTerm = headMay . factTerms
-- True if there is a first term and a premise guarding it
guardedCopy faConc = case firstTerm faConc of
Nothing -> False
Just tConc -> freshFact tConc `elem` prems || guardedInPrems tConc
-- True if there is a premise with the same tag and first term
guardedInPrems tConc = (`any` prems) $ \faPrem ->
factTag faPrem == tag && maybe False (tConc ==) (firstTerm faPrem)
| ekr/tamarin-prover | lib/theory/src/Theory/Tools/InjectiveFactInstances.hs | gpl-3.0 | 2,698 | 0 | 15 | 720 | 407 | 226 | 181 | 31 | 2 |
module OSC.Message
( oscMessage
, readOSC
, sendOSC ) where
import qualified OSC.Atom as A
import qualified OSC.UDPSocket as U
import qualified Data.Maybe as M
import qualified Data.ByteString as B (ByteString)
import qualified Data.ByteString.Lazy as L
data Message = Message
{ msgAddress :: A.OSCString
, msgTypeTag :: A.OSCString
, msgData :: L.ByteString } deriving Show
c2w8 :: Char -> W.Word8
c2w8 = fromIntegral . fromEnum
parseType :: L.ByteString -> L.ByteString -> [A.Atom] -- where atomizeable type =>
parseType t m
| L.null t && L.null m = []
| c2w8 ',' == h = parseType y m
| c2w8 'f' == h = (A.decode m :: Float) : parseType y (L.drop 4 m)
| c2w8 'i' == h = (A.decode m :: Int) : parseType y (L.drop 4 m)
| c2w8 's' == h || c2w8 's' == h =
let b = A.decode m :: A.OSCString
l = A.length b
in b : parseType y (L.drop l m)
| c2w8 'b' == h || c2w8 's' == h =
let b = A.decode m :: A.Blob
l = A.length b
in b : parseType y (L.drop l m)
| otherwise = []
where (h, y) = (L.head t, L.tail t)
readOSC :: B.ByteString -> Message
readOSC m =
let l = L.fromStrict m
(a, r) = parseMsgString l
(t, d) = parseMsgString r
in Message (A.oscAtom 's' a) -- check if vaild.
(A.oscAtom 's' t)
(parseType t d)
oscMessage :: String -> [A.Atom] -> Message
oscMessage a d = Message (A.oscString a) (A.oscString $ ',' : map A.typeTag d) d
-- | isAddress a = Just $
-- | otherwise = Nothing
sendOSC :: Message -> U.UdpOscHandle -> IO Int
sendOSC p = U.sendBytes (toBytes p)
where
toBytes :: Message -> L.ByteString
toBytes (Message a t d) =
let at = L.concat (map A.oscBytes [a, t])
bd = L.concat (map A.oscBytes d)
in L.append at bd
| destroyhimmyrobots/osc.hs | OSC/Message.hs | gpl-3.0 | 1,773 | 26 | 14 | 468 | 801 | 412 | 389 | 48 | 1 |
{-# LANGUAGE OverloadedStrings, BangPatterns #-}
module Greg.Bot where
import Greg.Types
import Greg.IRC (send)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Map as M
import Data.Sequence as S ((|>), singleton)
import Control.Concurrent
import Control.Monad (when)
-- | Send a message to the bot's channel.
message :: Bot -> T.Text -> IO ()
message !bot !str = T.hPutStrLn (socket bot) $ "PRIVMSG " `T.append` channel (config bot) `T.append` " :" `T.append` str
parseMessage :: T.Text -> Bot -> Maybe Message
parseMessage !mg !bot = case T.breakOn expected mg of
("", _) -> Nothing
(_ , "") -> Nothing
(!talker, !unparsed) ->
let (!nick, !host) = T.breakOn "!" (T.init (T.tail talker))
in Just $ Msg nick host (T.drop (T.length expected) unparsed)
where
expected :: T.Text
expected = "PRIVMSG " `T.append` channel (config bot) `T.append` " :"
parseCommand :: Message -> [Command] -> Maybe (Command, T.Text)
parseCommand (Msg _ _ !m) !cmds = if fst (T.splitAt 1 m) == "~"
then uncurry getCmd (T.breakOn " " m)
else Nothing
where
getCmd !cmd !args = case lookupByAlias (T.tail (T.strip cmd)) cmds of
Just !c -> Just (c, args)
Nothing -> Nothing
addToQuotes :: Bot -> Message -> IO ()
addToQuotes !bot (Msg !sr _ !mg) = modifyMVar_ (quotes bot) $ \qs -> return $
if M.member sr qs
then M.adjust (|> T.init mg) sr qs
else M.insert sr (singleton (T.init mg)) qs
addToPermissions :: Bot -> T.Text -> Permission -> IO ()
addToPermissions !bot !dude Normal = modifyMVar_ (permissions bot) $ \ps -> return $ M.delete dude ps -- delete permit as Normal is the default anyway
addToPermissions !bot !dude !permission = modifyMVar_ (permissions bot) $ return . M.insert dude permission
-- | True if a user has the required level to run a command.
ok :: Bot -> T.Text -> Command -> IO Bool
ok !bot !dude !cmd = {-# SCC "ok" #-} do
ps <- readMVar (permissions bot)
case M.lookup dude ps of
Just p -> return $ p >= reqp cmd
Nothing -> return $ reqp cmd == Normal
lookupByAlias :: T.Text -> [Command] -> Maybe Command
lookupByAlias !as !cs = {-# SCC "lookupByAlias" #-} case [ cms | cms <- cs, alias cms == as ] of
(!c:_) -> Just c
_ -> Nothing
-- | Run a command, and send the output to the channel, or
-- yell at the person who called the command for an error.
msgCommand :: Bot -> Message -> Command -> IO ()
msgCommand !bot !mg !cmd = {-# SCC "msgCommand" #-} do
okay <- ok bot (sender mg) cmd
when okay $ do
result <- run cmd mg{msg = T.strip (msg mg)} bot
case result of
Right !m -> mapM_ (message bot) (T.lines m)
Left !err -> send bot ("NOTICE " `T.append` sender mg `T.append` " :" `T.append` err)
| mikeplus64/Greg | src/Greg/Bot.hs | gpl-3.0 | 2,880 | 0 | 18 | 717 | 1,102 | 554 | 548 | 54 | 3 |
{-
Copyright (C) 2015 Leon Medvinsky
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-}
{-|
Module : Needles.Bot.Trigger.Examples
Description : Example Triggers
Copyright : (c) Leon Medvinsky, 2015
License : GPL-3
Maintainer : [email protected]
Stability : experimental
Portability : ghc
-}
{-# LANGUAGE OverloadedStrings #-}
module Needles.Bot.Trigger.Examples (
replyTrig
, replyPmTrig
, simpleStateTrig
, stateTrig
) where
import Data.Text (Text, append)
import qualified Data.Text as T
import Needles.Bot.Trigger
-- | Trigger that replies with an example message
replyTrig :: Trigger
replyTrig = mkTrigger "reply" (ProtoTrigger replyTest replyAct) ()
replyTest :: MessageInfo -> Bool
replyTest mi = mType mi == MTChat && (".replychat" == what mi)
replyAct :: MessageInfo -> TriggerAct a b ()
replyAct mi = respond mi message
where message = "Hi " `append` who mi `append` ", this is an example message."
-- | Replies in pm
replyPmTrig :: Trigger
replyPmTrig = mkTrigger "replyPm" (ProtoTrigger replyPmTest replyPmAct) ()
replyPmTest :: MessageInfo -> Bool
replyPmTest mi = (mType mi == MTChat || mType mi == MTPm) && (".replypm" == what mi)
replyPmAct :: MessageInfo -> TriggerAct a b ()
replyPmAct mi = sendPm (who mi) "This is an example pm."
-- | Simple state
simpleStateTrig :: Trigger
simpleStateTrig =
mkTrigger "simpleState" (ProtoTrigger simpleStateTest simpleStateAct) "Not Set"
simpleStateTest :: MessageInfo -> Bool
simpleStateTest mi = (mType mi == MTChat || mType mi == MTPm) &&
(".sSimple " `T.isPrefixOf` what mi)
simpleStateAct :: MessageInfo -> TriggerAct Text b ()
simpleStateAct mi = do
prev <- getVar
respond mi ("Previous data: " `append` prev)
storeVar (T.drop 9 $ what mi)
-- | Shared state
statePutTest :: MessageInfo -> Bool
statePutTest mi = (mType mi == MTChat || mType mi == MTPm) &&
(".sPut " `T.isPrefixOf` what mi)
statePutAct :: MessageInfo -> TriggerAct Text b ()
statePutAct mi = do
storeVar (T.drop 6 $ what mi)
testdata <- getVar
respond mi ("Data stored: " `append` testdata)
statePutProto :: ProtoTrigger Text b
statePutProto = ProtoTrigger statePutTest statePutAct
stateGetTest :: MessageInfo -> Bool
stateGetTest mi = (mType mi == MTChat || mType mi == MTPm) &&
(".sGet" `T.isPrefixOf` what mi)
stateGetAct :: MessageInfo -> TriggerAct Text b ()
stateGetAct mi = do
datas <- getVar
respond mi ("Data: " `append` datas)
stateGetProto :: ProtoTrigger Text b
stateGetProto = ProtoTrigger stateGetTest stateGetAct
stateTrig :: Trigger
stateTrig =
clusterTrigger "state" [stateGetProto, statePutProto] ""
| raymoo/needles | src/Needles/Bot/Trigger/Examples.hs | gpl-3.0 | 3,522 | 0 | 11 | 835 | 738 | 385 | 353 | 55 | 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.CloudUserAccounts.Users.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns the specified User resource.
--
-- /See:/ <https://cloud.google.com/compute/docs/access/user-accounts/api/latest/ Cloud User Accounts API Reference> for @clouduseraccounts.users.get@.
module Network.Google.Resource.CloudUserAccounts.Users.Get
(
-- * REST Resource
UsersGetResource
-- * Creating a Request
, usersGet
, UsersGet
-- * Request Lenses
, ugProject
, ugUser
) where
import Network.Google.Prelude
import Network.Google.UserAccounts.Types
-- | A resource alias for @clouduseraccounts.users.get@ method which the
-- 'UsersGet' request conforms to.
type UsersGetResource =
"clouduseraccounts" :>
"beta" :>
"projects" :>
Capture "project" Text :>
"global" :>
"users" :>
Capture "user" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] User
-- | Returns the specified User resource.
--
-- /See:/ 'usersGet' smart constructor.
data UsersGet = UsersGet'
{ _ugProject :: !Text
, _ugUser :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'UsersGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ugProject'
--
-- * 'ugUser'
usersGet
:: Text -- ^ 'ugProject'
-> Text -- ^ 'ugUser'
-> UsersGet
usersGet pUgProject_ pUgUser_ =
UsersGet'
{ _ugProject = pUgProject_
, _ugUser = pUgUser_
}
-- | Project ID for this request.
ugProject :: Lens' UsersGet Text
ugProject
= lens _ugProject (\ s a -> s{_ugProject = a})
-- | Name of the user resource to return.
ugUser :: Lens' UsersGet Text
ugUser = lens _ugUser (\ s a -> s{_ugUser = a})
instance GoogleRequest UsersGet where
type Rs UsersGet = User
type Scopes UsersGet =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
"https://www.googleapis.com/auth/cloud.useraccounts",
"https://www.googleapis.com/auth/cloud.useraccounts.readonly"]
requestClient UsersGet'{..}
= go _ugProject _ugUser (Just AltJSON)
userAccountsService
where go
= buildClient (Proxy :: Proxy UsersGetResource)
mempty
| rueshyna/gogol | gogol-useraccounts/gen/Network/Google/Resource/CloudUserAccounts/Users/Get.hs | mpl-2.0 | 3,156 | 0 | 15 | 776 | 394 | 237 | 157 | 64 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.Config.GetResourceConfigHistory
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Returns a list of configuration items for the specified resource. The list
-- contains details about each state of the resource during the specified time
-- interval. You can specify a 'limit' on the number of results returned on the
-- page. If a limit is specified, a 'nextToken' is returned as part of the result
-- that you can use to continue this request.
--
-- <http://docs.aws.amazon.com/config/latest/APIReference/API_GetResourceConfigHistory.html>
module Network.AWS.Config.GetResourceConfigHistory
(
-- * Request
GetResourceConfigHistory
-- ** Request constructor
, getResourceConfigHistory
-- ** Request lenses
, grchChronologicalOrder
, grchEarlierTime
, grchLaterTime
, grchLimit
, grchNextToken
, grchResourceId
, grchResourceType
-- * Response
, GetResourceConfigHistoryResponse
-- ** Response constructor
, getResourceConfigHistoryResponse
-- ** Response lenses
, grchrConfigurationItems
, grchrNextToken
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.Config.Types
import qualified GHC.Exts
data GetResourceConfigHistory = GetResourceConfigHistory
{ _grchChronologicalOrder :: Maybe ChronologicalOrder
, _grchEarlierTime :: Maybe POSIX
, _grchLaterTime :: Maybe POSIX
, _grchLimit :: Maybe Nat
, _grchNextToken :: Maybe Text
, _grchResourceId :: Text
, _grchResourceType :: ResourceType
} deriving (Eq, Read, Show)
-- | 'GetResourceConfigHistory' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'grchChronologicalOrder' @::@ 'Maybe' 'ChronologicalOrder'
--
-- * 'grchEarlierTime' @::@ 'Maybe' 'UTCTime'
--
-- * 'grchLaterTime' @::@ 'Maybe' 'UTCTime'
--
-- * 'grchLimit' @::@ 'Maybe' 'Natural'
--
-- * 'grchNextToken' @::@ 'Maybe' 'Text'
--
-- * 'grchResourceId' @::@ 'Text'
--
-- * 'grchResourceType' @::@ 'ResourceType'
--
getResourceConfigHistory :: ResourceType -- ^ 'grchResourceType'
-> Text -- ^ 'grchResourceId'
-> GetResourceConfigHistory
getResourceConfigHistory p1 p2 = GetResourceConfigHistory
{ _grchResourceType = p1
, _grchResourceId = p2
, _grchLaterTime = Nothing
, _grchEarlierTime = Nothing
, _grchChronologicalOrder = Nothing
, _grchLimit = Nothing
, _grchNextToken = Nothing
}
-- | The chronological order for configuration items listed. By default the
-- results are listed in reverse chronological order.
grchChronologicalOrder :: Lens' GetResourceConfigHistory (Maybe ChronologicalOrder)
grchChronologicalOrder =
lens _grchChronologicalOrder (\s a -> s { _grchChronologicalOrder = a })
-- | The time stamp that indicates an earlier time. If not specified, the action
-- returns paginated results that contain configuration items that start from
-- when the first configuration item was recorded.
grchEarlierTime :: Lens' GetResourceConfigHistory (Maybe UTCTime)
grchEarlierTime = lens _grchEarlierTime (\s a -> s { _grchEarlierTime = a }) . mapping _Time
-- | The time stamp that indicates a later time. If not specified, current time is
-- taken.
grchLaterTime :: Lens' GetResourceConfigHistory (Maybe UTCTime)
grchLaterTime = lens _grchLaterTime (\s a -> s { _grchLaterTime = a }) . mapping _Time
-- | The maximum number of configuration items returned in each page. The default
-- is 10. You cannot specify a limit greater than 100.
grchLimit :: Lens' GetResourceConfigHistory (Maybe Natural)
grchLimit = lens _grchLimit (\s a -> s { _grchLimit = a }) . mapping _Nat
-- | An optional parameter used for pagination of the results.
grchNextToken :: Lens' GetResourceConfigHistory (Maybe Text)
grchNextToken = lens _grchNextToken (\s a -> s { _grchNextToken = a })
-- | The ID of the resource (for example., 'sg-xxxxxx').
grchResourceId :: Lens' GetResourceConfigHistory Text
grchResourceId = lens _grchResourceId (\s a -> s { _grchResourceId = a })
-- | The resource type.
grchResourceType :: Lens' GetResourceConfigHistory ResourceType
grchResourceType = lens _grchResourceType (\s a -> s { _grchResourceType = a })
data GetResourceConfigHistoryResponse = GetResourceConfigHistoryResponse
{ _grchrConfigurationItems :: List "configurationItems" ConfigurationItem
, _grchrNextToken :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'GetResourceConfigHistoryResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'grchrConfigurationItems' @::@ ['ConfigurationItem']
--
-- * 'grchrNextToken' @::@ 'Maybe' 'Text'
--
getResourceConfigHistoryResponse :: GetResourceConfigHistoryResponse
getResourceConfigHistoryResponse = GetResourceConfigHistoryResponse
{ _grchrConfigurationItems = mempty
, _grchrNextToken = Nothing
}
-- | A list that contains the configuration history of one or more resources.
grchrConfigurationItems :: Lens' GetResourceConfigHistoryResponse [ConfigurationItem]
grchrConfigurationItems =
lens _grchrConfigurationItems (\s a -> s { _grchrConfigurationItems = a })
. _List
-- | A token used for pagination of results.
grchrNextToken :: Lens' GetResourceConfigHistoryResponse (Maybe Text)
grchrNextToken = lens _grchrNextToken (\s a -> s { _grchrNextToken = a })
instance ToPath GetResourceConfigHistory where
toPath = const "/"
instance ToQuery GetResourceConfigHistory where
toQuery = const mempty
instance ToHeaders GetResourceConfigHistory
instance ToJSON GetResourceConfigHistory where
toJSON GetResourceConfigHistory{..} = object
[ "resourceType" .= _grchResourceType
, "resourceId" .= _grchResourceId
, "laterTime" .= _grchLaterTime
, "earlierTime" .= _grchEarlierTime
, "chronologicalOrder" .= _grchChronologicalOrder
, "limit" .= _grchLimit
, "nextToken" .= _grchNextToken
]
instance AWSRequest GetResourceConfigHistory where
type Sv GetResourceConfigHistory = Config
type Rs GetResourceConfigHistory = GetResourceConfigHistoryResponse
request = post "GetResourceConfigHistory"
response = jsonResponse
instance FromJSON GetResourceConfigHistoryResponse where
parseJSON = withObject "GetResourceConfigHistoryResponse" $ \o -> GetResourceConfigHistoryResponse
<$> o .:? "configurationItems" .!= mempty
<*> o .:? "nextToken"
| kim/amazonka | amazonka-config/gen/Network/AWS/Config/GetResourceConfigHistory.hs | mpl-2.0 | 7,627 | 0 | 12 | 1,605 | 981 | 583 | 398 | 102 | 1 |
-- | Compile with: fay examples/canvaswater.hs
{-# LANGUAGE EmptyDataDecls #-}
module TicTacToe_UI (main) where
import Prelude
import FFI
import TicTacToe_Web as Game
-- | Main entry point.
main :: Fay ()
main = do
player <- newRef (1::Int)
board <- newRef Game.newBoard
playing <- newRef True
let
newGame :: Fay ()
newGame = do
board <- drawBoard
step <- newRef (1 :: Int)
--addEventListener board "click" log_pos False
addEventListener board "click" doMovement False
drawBoard :: Fay (Element)
drawBoard = do img <- newImage
canvas <- getElementById "game"
context <- getContext canvas "2d"
setSrc img "board.png"
drawImage context img 0 0
return canvas
doMovement :: Event -> Fay ()
doMovement e = do play <- readRef playing
if play
then do currentPlayer <- readRef player
currentBoard <- readRef board
(row, col) <- readMovement e
case Game.doMovement currentBoard row col currentPlayer of
Just b -> do writeRef board b
drawMovement currentPlayer row col
if Game.isWinner b currentPlayer
then endGame currentPlayer
else do console_log $ "Player " ++ (show currentPlayer) ++ ": " ++ (show (row,col))
Game.showBoard b
writeRef player $ Game.otherPlayer currentPlayer
changePlayerLabel $ Game.otherPlayer currentPlayer
Nothing -> return ()
else return ()
readMovement :: Event -> Fay (Int, Int)
readMovement e = do x <- xpos e
y <- ypos e
let col = x `div` 200
let row = y `div` 200
console_log $ show row ++ "," ++ show col
return (row, col)
drawMovement :: Int -> Int -> Int -> Fay()
drawMovement player r c = do canvas <- getElementById "game"
context <- getContext canvas "2d"
img <- newImage
setSrc img $ if player == 1 then "x.png" else "o.png"
drawImage context img (c * 200) (r * 200)
changePlayerLabel :: Int -> Fay()
changePlayerLabel p = innerText "playerName" $ "Player " ++ (show p)
endGame :: Int -> Fay()
endGame winner = do console_log $ "Winner: " ++ (show winner)
innerText "instruct" $ "You won player " ++ (show winner) ++ "!"
board <- getElementById "game"
writeRef playing False
window <- getWindow
addEventListener_ window "load" newGame False
--------------------------------------------------------------------------------
-- Elements
class Eventable a
-- | A DOM element.
data Element
instance Eventable Element
instance Show Element
-- | Add an event listener to an element.
addEventListener_ :: (Eventable a) => a -> String -> Fay () -> Bool -> Fay ()
addEventListener_ = ffi "%1['addEventListener'](%2,%3,%4)"
data Event
addEventListener :: (Eventable a) => a -> String -> (Event -> Fay ()) -> Bool -> Fay ()
addEventListener = ffi "%1['addEventListener'](%2,%3,%4)"
removeEventListener :: (Eventable a) => a -> String -> (Event -> Fay ()) -> Bool -> Fay ()
removeEventListener = ffi "%1['removeEventListener'](%2,%3,%4)"
documentGetElements :: String -> Fay [Element]
documentGetElements = ffi "document.getElementsByTagName(%1)"
-- | Get an element by its ID.
getElementById :: String -> Fay Element
getElementById = ffi "document['getElementById'](%1)"
data Window
instance Eventable Window
getWindow :: Fay (Window)
getWindow = ffi "window"
--------------
log_pos :: Event -> Fay ()
log_pos e = do x <- xpos e
y <- ypos e
console_log $ show y ++ "," ++ show x
xpos :: Event -> Fay (Int)
xpos = ffi "%1['offsetX']"
ypos :: Event -> Fay (Int)
ypos = ffi "%1['offsetY']"
--------------------------------------------------------------------------------
-- Images
data Image
instance Eventable Image
-- | Make a new image.
newImage :: Fay Image
newImage = ffi "new Image()"
-- | Make a new image.
setSrc :: Image -> String -> Fay ()
setSrc = ffi "%1['src'] = %2"
--------------------------------------------------------------------------------
-- Canvas
-- | A canvas context.
data Context
-- | Get an element by its ID.
getContext :: Element -> String -> Fay Context
getContext = ffi "%1['getContext'](%2)"
-- | Draw an image onto a canvas rendering context.
drawImage :: Context -> Image -> Int -> Int -> Fay ()
drawImage = ffi "%1['drawImage'](%2,%3,%4)"
-- | Draw an image onto a canvas rendering context.
--
-- Nine arguments: the element, source (x,y) coordinates, source width and
-- height (for cropping), destination (x,y) coordinates, and destination width
-- and height (resize).
--
-- context.drawImage(img_elem, sx, sy, sw, sh, dx, dy, dw, dh);
drawImageSpecific :: Context -> Image
-> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double
-> Fay ()
drawImageSpecific = ffi "%1['drawImage'](%2,%3,%4,%5,%6,%7,%8,%9,%10)"
-- | Set the fill style.
setFillStyle :: Context -> String -> Fay ()
setFillStyle = ffi "%1['fillStyle']=%2"
-- | Set the fill style.
setFillRect :: Context -> Double -> Double -> Double -> Double -> Fay ()
setFillRect = ffi "%1['fillRect'](%2,%3,%4,%5)"
--------------------------------------------------------------------------------
-- Ref
-- | A mutable reference like IORef.
data Ref a
-- | Make a new mutable reference.
newRef :: a -> Fay (Ref a)
newRef = ffi "new Fay$$Ref(%1)"
-- | Replace the value in the mutable reference.
writeRef :: Ref a -> a -> Fay ()
writeRef = ffi "Fay$$writeRef(%1,%2)"
-- | Get the referred value from the mutable value.
readRef :: Ref a -> Fay a
readRef = ffi "Fay$$readRef(%1)"
--------------------------------------------------------------------------------
-- Misc
-- | Alert using window.alert.
alert :: a -> Fay ()
alert = ffi "window['alert'](%1)"
-- | Alert using window.alert.
console_log :: String -> Fay ()
console_log = ffi "console['log'](%1)"
innerText :: String -> String -> Fay()
innerText = ffi "document['getElementById'](%1)['innerText']=%2" | LambdaMx/haskelldojo | session_4/tictactoe/domix_agus/web/ui.hs | unlicense | 6,928 | 0 | 27 | 2,203 | 1,581 | 785 | 796 | -1 | -1 |
module EKG.A169849 (a169849) where
import Helpers.EKGBuilder (buildEKG)
a169849 :: Int -> Integer
a169849 n = a169849_list !! (n - 1)
a169849_list :: [Integer]
a169849_list = buildEKG [9]
| peterokagey/haskellOEIS | src/EKG/A169849.hs | apache-2.0 | 190 | 0 | 7 | 29 | 68 | 39 | 29 | 6 | 1 |
-- Copyright (C) 2009-2012 John Millikin <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-- | Basic types, useful to every D-Bus application.
--
-- Authors of client applications should import "DBus.Client", which provides
-- an easy RPC-oriented interface to D-Bus methods and signals.
module DBus
(
-- * Messages
Message
-- ** Method calls
, MethodCall
, methodCall
, methodCallPath
, methodCallInterface
, methodCallMember
, methodCallSender
, methodCallDestination
, methodCallAutoStart
, methodCallReplyExpected
, methodCallBody
-- ** Method returns
, MethodReturn
, methodReturn
, methodReturnSerial
, methodReturnSender
, methodReturnDestination
, methodReturnBody
-- ** Method errors
, MethodError
, methodError
, methodErrorName
, methodErrorSerial
, methodErrorSender
, methodErrorDestination
, methodErrorBody
, methodErrorMessage
-- ** Signals
, Signal
, signal
, signalPath
, signalMember
, signalInterface
, signalSender
, signalDestination
, signalBody
-- ** Received messages
, ReceivedMessage(ReceivedMethodCall, ReceivedMethodReturn, ReceivedMethodError, ReceivedSignal)
, receivedMessageSerial
, receivedMessageSender
, receivedMessageBody
-- * Variants
, Variant
, IsVariant(..)
, variantType
, IsAtom
, IsValue
, typeOf
-- * Signatures
, Signature
, Type(..)
, signature
, signature_
, signatureTypes
, formatSignature
, parseSignature
-- * Object paths
, ObjectPath
, objectPath_
, formatObjectPath
, parseObjectPath
-- * Names
-- ** Interface names
, InterfaceName
, interfaceName_
, formatInterfaceName
, parseInterfaceName
-- ** Member names
, MemberName
, memberName_
, formatMemberName
, parseMemberName
-- ** Error names
, ErrorName
, errorName_
, formatErrorName
, parseErrorName
-- ** Bus names
, BusName
, busName_
, formatBusName
, parseBusName
-- * Non-native containers
-- ** Structures
, Structure
, structureItems
-- ** Arrays
, Array
, arrayItems
-- ** Dictionaries
, Dictionary
, dictionaryItems
-- * Addresses
, Address
, addressMethod
, addressParameters
, address
, formatAddress
, formatAddresses
, parseAddress
, parseAddresses
, getSystemAddress
, getSessionAddress
, getStarterAddress
-- * Message marshaling
, Endianness (..)
-- ** Marshal
, marshal
, MarshalError
, marshalErrorMessage
-- ** Unmarshal
, unmarshal
, UnmarshalError
, unmarshalErrorMessage
-- ** Message serials
, Serial
, serialValue
, firstSerial
, nextSerial
-- * D-Bus UUIDs
, UUID
, formatUUID
, randomUUID
) where
import Control.Monad (replicateM)
import qualified Data.ByteString.Char8 as Char8
import Data.Word (Word16)
import System.Random (randomRIO)
import Text.Printf (printf)
import DBus.Address
import DBus.Message
import qualified DBus.Types
import DBus.Types hiding (typeOf)
import DBus.Wire
-- | Get the D-Bus type corresponding to the given Haskell value. The value
-- may be @undefined@.
typeOf :: IsValue a => a -> Type
typeOf = DBus.Types.typeOf
-- | Construct a new 'MethodCall' for the given object, interface, and method.
--
-- Use fields such as 'methodCallDestination' and 'methodCallBody' to populate
-- a 'MethodCall'.
--
-- @
--{-\# LANGUAGE OverloadedStrings \#-}
--
--methodCall \"/\" \"org.example.Math\" \"Add\"
-- { 'methodCallDestination' = Just \"org.example.Calculator\"
-- , 'methodCallBody' = ['toVariant' (1 :: Int32), 'toVariant' (2 :: Int32)]
-- }
-- @
methodCall :: ObjectPath -> InterfaceName -> MemberName -> MethodCall
methodCall path iface member = MethodCall path (Just iface) member Nothing Nothing True True []
-- | Construct a new 'MethodReturn', in reply to a method call with the given
-- serial.
--
-- Use fields such as 'methodReturnBody' to populate a 'MethodReturn'.
methodReturn :: Serial -> MethodReturn
methodReturn s = MethodReturn s Nothing Nothing []
-- | Construct a new 'MethodError', in reply to a method call with the given
-- serial.
--
-- Use fields such as 'methodErrorBody' to populate a 'MethodError'.
methodError :: Serial -> ErrorName -> MethodError
methodError s name = MethodError name s Nothing Nothing []
-- | Construct a new 'Signal' for the given object, interface, and signal name.
--
-- Use fields such as 'signalBody' to populate a 'Signal'.
signal :: ObjectPath -> InterfaceName -> MemberName -> Signal
signal path iface member = Signal path iface member Nothing Nothing []
-- | No matter what sort of message was received, get its serial.
receivedMessageSerial :: ReceivedMessage -> Serial
receivedMessageSerial (ReceivedMethodCall s _) = s
receivedMessageSerial (ReceivedMethodReturn s _) = s
receivedMessageSerial (ReceivedMethodError s _) = s
receivedMessageSerial (ReceivedSignal s _) = s
receivedMessageSerial (ReceivedUnknown s _) = s
-- | No matter what sort of message was received, get its sender (if provided).
receivedMessageSender :: ReceivedMessage -> Maybe BusName
receivedMessageSender (ReceivedMethodCall _ msg) = methodCallSender msg
receivedMessageSender (ReceivedMethodReturn _ msg) = methodReturnSender msg
receivedMessageSender (ReceivedMethodError _ msg) = methodErrorSender msg
receivedMessageSender (ReceivedSignal _ msg) = signalSender msg
receivedMessageSender (ReceivedUnknown _ msg) = unknownMessageSender msg
-- | No matter what sort of message was received, get its body (if provided).
receivedMessageBody :: ReceivedMessage -> [Variant]
receivedMessageBody (ReceivedMethodCall _ msg) = methodCallBody msg
receivedMessageBody (ReceivedMethodReturn _ msg) = methodReturnBody msg
receivedMessageBody (ReceivedMethodError _ msg) = methodErrorBody msg
receivedMessageBody (ReceivedSignal _ msg) = signalBody msg
receivedMessageBody (ReceivedUnknown _ msg) = unknownMessageBody msg
-- | Convert a 'Message' into a 'Char8.ByteString'. Although unusual, it is
-- possible for marshaling to fail; if this occurs, an error will be
-- returned instead.
marshal :: Message msg => Endianness -> Serial -> msg -> Either MarshalError Char8.ByteString
marshal = marshalMessage
-- | Parse a 'Char8.ByteString' into a 'ReceivedMessage'. The result can be
-- inspected to see what type of message was parsed. Unknown message types
-- can still be parsed successfully, as long as they otherwise conform to
-- the D-Bus standard.
unmarshal :: Char8.ByteString -> Either UnmarshalError ReceivedMessage
unmarshal = unmarshalMessage
-- | A D-Bus UUID is 128 bits of data, usually randomly generated. They are
-- used for identifying unique server instances to clients.
--
-- Older versions of the D-Bus spec also called these values /GUIDs/.
--
-- D-Bus UUIDs are not the same as the RFC-standardized UUIDs or GUIDs.
newtype UUID = UUID Char8.ByteString
deriving (Eq, Ord, Show)
-- | Format a D-Bus UUID as hex-encoded ASCII.
formatUUID :: UUID -> String
formatUUID (UUID bytes) = Char8.unpack bytes
-- | Generate a random D-Bus UUID. This value is suitable for use in a
-- randomly-allocated address, or as a listener's socket address
-- @\"guid\"@ parameter.
randomUUID :: IO UUID
randomUUID = do
-- The version of System.Random bundled with ghc < 7.2 doesn't define
-- instances for any of the fixed-length word types, so we imitate
-- them using the instance for Int.
--
-- 128 bits is 8 16-bit integers. We use chunks of 16 instead of 32
-- because Int is not guaranteed to be able to store a Word32.
let hexInt16 i = printf "%04x" (i :: Int)
int16s <- replicateM 8 (randomRIO (0, fromIntegral (maxBound :: Word16)))
return (UUID (Char8.pack (concatMap hexInt16 int16s)))
| jmillikin/haskell-dbus | lib/DBus.hs | apache-2.0 | 8,208 | 8 | 13 | 1,449 | 1,209 | 719 | 490 | 156 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-incomplete-patterns
-fno-warn-name-shadowing
-fno-warn-unused-imports
-fno-warn-unused-matches #-}
{-
Copyright 2020 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Main where
import CodeWorld.Account (UserId)
import CodeWorld.Auth
( AuthConfig,
authMethod,
authRoutes,
authenticated,
getAuthConfig,
)
import CodeWorld.Compile
import CodeWorld.Compile.Base
import Control.Applicative
import Control.Concurrent (forkIO)
import Control.Concurrent.MSem (MSem)
import qualified Control.Concurrent.MSem as MSem
import Control.Exception (bracket_)
import Control.Exception.Lifted (catch)
import Control.Monad
import Control.Monad.Trans
import Data.Aeson
import qualified Data.ByteString as B
import Data.ByteString.Builder (toLazyByteString)
import qualified Data.ByteString.Lazy as LB
import Data.Char (isSpace)
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.IO as T
import qualified Data.Vector as V
import Model
import Network.HTTP.Simple
import Ormolu (OrmoluException, defaultConfig, ormolu)
import Snap.Core
import Snap.Http.Server (quickHttpServe)
import Snap.Util.FileServe
import Snap.Util.FileUploads
import System.Directory
import System.FileLock
import System.FilePath
import System.IO.Temp
import Util
maxSimultaneousCompiles :: Int
maxSimultaneousCompiles = 4
maxSimultaneousErrorChecks :: Int
maxSimultaneousErrorChecks = 2
data Context = Context
{ authConfig :: AuthConfig,
compileSem :: MSem Int,
errorSem :: MSem Int,
baseSem :: MSem Int
}
main :: IO ()
main = do
ctx <- makeContext
forkIO $ baseVersion >>= buildBaseIfNeeded ctx >> return ()
quickHttpServe $ (processBody >> site ctx) <|> site ctx
makeContext :: IO Context
makeContext = do
ctx <-
Context <$> (getAuthConfig =<< getCurrentDirectory)
<*> MSem.new maxSimultaneousCompiles
<*> MSem.new maxSimultaneousErrorChecks
<*> MSem.new 1
putStrLn $ "Authentication method: " ++ authMethod (authConfig ctx)
return ctx
-- | A CodeWorld Snap API action
type CodeWorldHandler = Context -> Snap ()
-- | A public handler that can be called from both authenticated and
-- unauthenticated clients and that does not need access to the user
-- ID.
public :: CodeWorldHandler -> CodeWorldHandler
public = id
-- | A private handler that can only be called from authenticated
-- clients and needs access to the user ID.
private :: (UserId -> CodeWorldHandler) -> CodeWorldHandler
private handler ctx = authenticated (flip handler ctx) (authConfig ctx)
-- A revised upload policy that allows up to 8 MB of uploaded data in a
-- request. This is needed to handle uploads of projects including editor
-- history.
codeworldUploadPolicy :: UploadPolicy
codeworldUploadPolicy =
setMaximumFormInputSize (2 ^ (23 :: Int)) defaultUploadPolicy
-- Processes the body of a multipart request.
#if MIN_VERSION_snap_core(1,0,0)
processBody :: Snap ()
processBody = do
handleMultipart codeworldUploadPolicy (\x y -> return ())
return ()
#else
processBody :: Snap ()
processBody = do
handleMultipart codeworldUploadPolicy (\x -> return ())
return ()
#endif
getBuildMode :: Snap BuildMode
getBuildMode =
getParam "mode" >>= \case
Just "haskell" -> return (BuildMode "haskell")
Just "blocklyXML" -> return (BuildMode "blocklyXML")
_ -> return (BuildMode "codeworld")
site :: CodeWorldHandler
site ctx =
let routes =
[ ("loadProject", loadProjectHandler ctx),
("saveProject", saveProjectHandler ctx),
("deleteProject", deleteProjectHandler ctx),
("createFolder", createFolderHandler ctx),
("deleteFolder", deleteFolderHandler ctx),
("listFolder", listFolderHandler False ctx),
("listFolders", listFolderHandler True ctx),
("updateChildrenIndexes", updateChildrenIndexesHandler ctx),
("shareFolder", shareFolderHandler ctx),
("shareContent", shareContentHandler ctx),
("moveProject", moveProjectHandler ctx),
("compile", compileHandler ctx),
("errorCheck", errorCheckHandler ctx),
("saveXMLhash", saveXMLHashHandler ctx),
("loadXML", loadXMLHandler ctx),
("loadSource", loadSourceHandler ctx),
("run", runHandler ctx),
("runJS", runHandler ctx),
("runBaseJS", runBaseHandler ctx),
("runMsg", runMessageHandler ctx),
("haskell", serveFile "web/env.html"),
("blocks", serveFile "web/blocks.html"),
("funblocks", serveFile "web/blocks.html"),
("indent", indentHandler ctx),
("gallery/:shareHash", galleryHandler ctx),
("log", logHandler ctx)
]
++ authRoutes (authConfig ctx)
in route routes <|> serveDirectory "web"
-- A DirectoryConfig that sets the cache-control header to avoid errors when new
-- changes are made to JavaScript.
dirConfig :: DirectoryConfig Snap
dirConfig = defaultDirectoryConfig {preServeHook = disableCache}
where
disableCache _ = modifyRequest (addHeader "Cache-control" "no-cache")
createFolderHandler :: CodeWorldHandler
createFolderHandler = private $ \userId ctx -> do
mode <- getBuildMode
Just path <- fmap (splitDirectories . T.unpack . T.decodeUtf8) <$> getParam "path"
let pathText = map T.pack path
dirIds = map nameToDirId pathText
finalDir = joinPath $ map dirBase dirIds
name = last pathText
liftIO $ ensureUserBaseDir mode userId finalDir
liftIO $ createDirectory $ userProjectDir mode userId </> finalDir
modifyResponse $ setContentType "text/plain"
liftIO $
T.writeFile
(userProjectDir mode userId </> finalDir </> "dir.info")
name
deleteFolderHandler :: CodeWorldHandler
deleteFolderHandler = private $ \userId ctx -> do
mode <- getBuildMode
Just path <- fmap (splitDirectories . T.unpack . T.decodeUtf8) <$> getParam "path"
let dirIds = map (nameToDirId . T.pack) path
let finalDir = joinPath $ map dirBase dirIds
liftIO $ ensureUserDir mode userId finalDir
let dir = userProjectDir mode userId </> finalDir
liftIO $ removeDirectoryIfExists dir
loadProjectHandler :: CodeWorldHandler
loadProjectHandler = private $ \userId ctx -> do
mode <- getBuildMode
Just name <- getParam "name"
let projectName = T.decodeUtf8 name
let projectId = nameToProjectId projectName
Just path <- fmap (splitDirectories . T.unpack . T.decodeUtf8) <$> getParam "path"
let dirIds = map (nameToDirId . T.pack) path
let finalDir = joinPath $ map dirBase dirIds
liftIO $ ensureProjectDir mode userId finalDir projectId
let file =
userProjectDir mode userId </> finalDir
</> projectFile projectId
modifyResponse $ setContentType "application/json"
serveFile file
saveProjectHandler :: CodeWorldHandler
saveProjectHandler = private $ \userId ctx -> do
mode <- getBuildMode
Just path <- fmap (splitDirectories . T.unpack . T.decodeUtf8) <$> getParam "path"
let dirIds = map (nameToDirId . T.pack) path
let finalDir = joinPath $ map dirBase dirIds
Just project <- decode . LB.fromStrict . fromJust <$> getParam "project"
let projectId = nameToProjectId (projectName project)
liftIO $ ensureProjectDir mode userId finalDir projectId
let file =
userProjectDir mode userId </> finalDir
</> projectFile projectId
liftIO $ LB.writeFile file $ encode project
deleteProjectHandler :: CodeWorldHandler
deleteProjectHandler = private $ \userId ctx -> do
mode <- getBuildMode
Just name <- getParam "name"
let projectName = T.decodeUtf8 name
let projectId = nameToProjectId projectName
Just path <- fmap (splitDirectories . T.unpack . T.decodeUtf8) <$> getParam "path"
let dirIds = map (nameToDirId . T.pack) path
let finalDir = joinPath $ map dirBase dirIds
liftIO $ ensureProjectDir mode userId finalDir projectId
let file =
userProjectDir mode userId </> finalDir
</> projectFile projectId
liftIO $ removeFileIfExists file
listFolderHandler :: Bool -> CodeWorldHandler
listFolderHandler recurse = private $ \userId ctx -> do
mode <- getBuildMode
Just path <- fmap (splitDirectories . T.unpack . T.decodeUtf8) <$> getParam "path"
let dirIds = map (nameToDirId . T.pack) path
let finalDir = joinPath $ map dirBase dirIds
liftIO $ ensureUserBaseDir mode userId finalDir
liftIO $ ensureUserDir mode userId finalDir
let projectDir = userProjectDir mode userId
entries <- liftIO $ fsEntries recurse (projectDir </> finalDir)
modifyResponse $ setContentType "application/json"
writeLBS (encode entries)
-- | Update order of elements inside of given directory
updateChildrenIndexesHandler :: CodeWorldHandler
updateChildrenIndexesHandler = private $ \userId ctx -> do
mode <- getBuildMode
let projectDir = userProjectDir mode userId
Just path <-
fmap
( (\p -> projectDir </> p </> "order.info")
. joinPath
. (map (dirBase . nameToDirId . T.pack))
. splitDirectories
. T.unpack
. T.decodeUtf8
)
<$> getParam "path"
param <- getParam "entries"
-- Encoding just to check if request param is correct
Just entries <- decodeStrict . fromJust <$> getParam "entries" :: Snap (Maybe [FileSystemEntry])
liftIO $ LB.writeFile path $ encode entries
shareFolderHandler :: CodeWorldHandler
shareFolderHandler = private $ \userId ctx -> do
mode <- getBuildMode
Just path <- fmap (splitDirectories . T.unpack . T.decodeUtf8) <$> getParam "path"
let dirIds = map (nameToDirId . T.pack) path
let finalDir = joinPath $ map dirBase dirIds
checkSum <-
liftIO $ dirToCheckSum $ userProjectDir mode userId </> finalDir
liftIO $ ensureShareDir mode $ ShareId checkSum
liftIO
$ B.writeFile (shareRootDir mode </> shareLink (ShareId checkSum))
$ T.encodeUtf8 (T.pack (userProjectDir mode userId </> finalDir))
modifyResponse $ setContentType "text/plain"
writeBS $ T.encodeUtf8 checkSum
shareContentHandler :: CodeWorldHandler
shareContentHandler = private $ \userId ctx -> do
mode <- getBuildMode
Just shash <- getParam "shash"
sharingFolder <-
liftIO $
B.readFile
(shareRootDir mode </> shareLink (ShareId $ T.decodeUtf8 shash))
Just name <- fmap T.decodeUtf8 <$> getParam "name"
let dirPath = dirBase $ nameToDirId name
liftIO $ ensureUserBaseDir mode userId dirPath
liftIO
$ copyDirIfExists (T.unpack (T.decodeUtf8 sharingFolder))
$ userProjectDir mode userId </> dirPath
liftIO $
T.writeFile
(userProjectDir mode userId </> dirPath </> "dir.info")
name
moveProjectHandler :: CodeWorldHandler
moveProjectHandler = private $ \userId ctx -> do
mode <- getBuildMode
Just moveTo <- fmap (splitDirectories . T.unpack . T.decodeUtf8) <$> getParam "moveTo"
let moveToDir = joinPath $ map (dirBase . nameToDirId . T.pack) moveTo
Just moveFrom <- fmap (splitDirectories . T.unpack . T.decodeUtf8) <$> getParam "moveFrom"
let projectDir = userProjectDir mode userId
let moveFromDir =
projectDir
</> joinPath (map (dirBase . nameToDirId . T.pack) moveFrom)
let parentFrom =
if moveFrom == []
then []
else init moveFrom
Just isFile <- getParam "isFile"
case (moveTo == moveFrom, moveTo == parentFrom, isFile) of
(False, _, "true") -> do
Just name <- getParam "name"
let projectId = nameToProjectId $ T.decodeUtf8 name
file = moveFromDir </> projectFile projectId
toFile = projectDir </> moveToDir </> projectFile projectId
liftIO $ ensureProjectDir mode userId moveToDir projectId
liftIO $ copyFile file toFile
liftIO $ removeFileIfExists file
(_, False, "false") -> do
let dirName = last $ splitDirectories moveFromDir
let dir = moveToDir </> dirName
liftIO $ ensureUserBaseDir mode userId dir
liftIO $ copyDirIfExists moveFromDir $ projectDir </> dir
liftIO $ removeDirectoryIfExists moveFromDir
(_, _, _) -> return ()
withProgramLock :: BuildMode -> ProgramId -> IO a -> IO a
withProgramLock (BuildMode mode) (ProgramId hash) action = do
tmpDir <- getTemporaryDirectory
let tmpFile = tmpDir </> "codeworld" <.> T.unpack hash <.> mode
withFileLock tmpFile Exclusive (const action)
saveXMLHashHandler :: CodeWorldHandler
saveXMLHashHandler = public $ \ctx -> do
mode <- getBuildMode
unless (mode == BuildMode "blocklyXML")
$ modifyResponse
$ setResponseCode 500
Just source <- getParam "source"
let programId = sourceToProgramId source
liftIO $ withProgramLock mode programId $ do
ensureSourceDir mode programId
B.writeFile (sourceRootDir mode </> sourceXML programId) source
modifyResponse $ setContentType "text/plain"
writeBS (T.encodeUtf8 (unProgramId programId))
compileHandler :: CodeWorldHandler
compileHandler = public $ \ctx -> do
mode <- getBuildMode
Just source <- getParam "source"
let programId = sourceToProgramId source
deployId = sourceToDeployId source
status <- liftIO $ withProgramLock mode programId $ do
ensureSourceDir mode programId
B.writeFile (sourceRootDir mode </> sourceFile programId) source
writeDeployLink mode deployId programId
compileIfNeeded ctx mode programId
modifyResponse $ setResponseCode (responseCodeFromCompileStatus status)
modifyResponse $ setContentType "text/plain"
let result = CompileResult (unProgramId programId) (unDeployId deployId)
writeLBS (encode result)
errorCheckHandler :: CodeWorldHandler
errorCheckHandler = public $ \ctx -> do
mode <- getBuildMode
Just source <- getParam "source"
(status, output) <- liftIO $ errorCheck ctx mode source
modifyResponse $ setResponseCode (responseCodeFromCompileStatus status)
modifyResponse $ setContentType "text/plain"
writeBS output
getHashParam :: Bool -> BuildMode -> Snap ProgramId
getHashParam allowDeploy mode = do
maybeHash <- getParam "hash"
case maybeHash of
Just h -> return (ProgramId (T.decodeUtf8 h))
Nothing
| allowDeploy -> do
Just dh <- getParam "dhash"
let deployId = DeployId (T.decodeUtf8 dh)
liftIO $ resolveDeployId mode deployId
| otherwise -> pass
loadXMLHandler :: CodeWorldHandler
loadXMLHandler = public $ \ctx -> do
mode <- getBuildMode
unless (mode == BuildMode "blocklyXML")
$ modifyResponse
$ setResponseCode 500
programId <- getHashParam False mode
modifyResponse $ setContentType "text/plain"
serveFile (sourceRootDir mode </> sourceXML programId)
loadSourceHandler :: CodeWorldHandler
loadSourceHandler = public $ \ctx -> do
mode <- getBuildMode
programId <- getHashParam False mode
modifyResponse $ setContentType "text/x-haskell"
serveFile (sourceRootDir mode </> sourceFile programId)
runHandler :: CodeWorldHandler
runHandler = public $ \ctx -> do
mode <- getBuildMode
programId <- getHashParam True mode
result <-
liftIO
$ withProgramLock mode programId
$ compileIfNeeded ctx mode programId
modifyResponse $ setResponseCode (responseCodeFromCompileStatus result)
when (result == CompileSuccess) $ do
modifyResponse $ setContentType "text/javascript"
serveFile (buildRootDir mode </> targetFile programId)
runBaseHandler :: CodeWorldHandler
runBaseHandler = public $ \ctx -> do
maybeVer <- fmap T.decodeUtf8 <$> getParam "version"
hasProgram <-
(\mode hash dhash -> mode && (hash || dhash))
<$> hasParam "mode" <*> hasParam "hash" <*> hasParam "dhash"
case maybeVer of
Just ver -> serveFile (baseCodeFile ver)
Nothing | hasProgram -> do
mode <- getBuildMode
programId <- getHashParam True mode
result <-
liftIO
$ withProgramLock mode programId
$ compileIfNeeded ctx mode programId
modifyResponse $ setResponseCode (responseCodeFromCompileStatus result)
when (result == CompileSuccess) $ do
ver <-
liftIO $
B.readFile (buildRootDir mode </> baseVersionFile programId)
impliedVersion ver
_ -> do
ver <- liftIO baseVersion
liftIO $ buildBaseIfNeeded ctx ver
impliedVersion (T.encodeUtf8 ver)
where
impliedVersion ver = redirect $ "/runBaseJS?version=" <> ver
hasParam name = (/= Nothing) <$> getParam name
runMessageHandler :: CodeWorldHandler
runMessageHandler = public $ \ctx -> do
mode <- getBuildMode
programId <- getHashParam False mode
modifyResponse $ setContentType "text/plain"
serveFile (buildRootDir mode </> resultFile programId)
indentHandler :: CodeWorldHandler
indentHandler = public $ \ctx -> do
mode <- getBuildMode
Just source <- getParam "source"
reformat source `catch` handleError
where
reformat source = do
result <- ormolu defaultConfig "program.hs" (T.unpack (T.decodeUtf8 source))
modifyResponse $ setContentType "text/x-haskell"
writeBS $ T.encodeUtf8 result
handleError (e :: OrmoluException) = do
modifyResponse $ setResponseCode 500 . setContentType "text/plain"
writeLBS $ LB.fromStrict $ T.encodeUtf8 $ T.pack (show e)
galleryHandler :: CodeWorldHandler
galleryHandler = public $ const $ do
mode <- getBuildMode
Just shareHash <- getParam "shareHash"
let shareId = ShareId (T.decodeUtf8 shareHash)
gallery <- liftIO $ do
folder <- T.unpack . T.decodeUtf8 <$> B.readFile (shareRootDir mode </> shareLink shareId)
files <- sort <$> projectFileNames folder
Gallery <$> mapM (galleryItemFromProject mode folder) files
writeLBS $ encode gallery
galleryItemFromProject :: BuildMode -> FilePath -> Text -> IO GalleryItem
galleryItemFromProject mode@(BuildMode modeName) folder name = do
let projectId = nameToProjectId name
let file = folder </> projectFile projectId
Just project <- decode <$> LB.readFile file
let source = T.encodeUtf8 $ projectSource project
let programId = sourceToProgramId source
let deployId = sourceToDeployId source
liftIO $ withProgramLock mode programId $ do
ensureSourceDir mode programId
B.writeFile (sourceRootDir mode </> sourceFile programId) source
writeDeployLink mode deployId programId
let baseURL = "/" <> if modeName == "codeworld" then "" else T.pack modeName
return
GalleryItem
{ galleryItemName = name,
galleryItemURL =
"run.html"
<> "?mode="
<> T.pack modeName
<> "&dhash="
<> unDeployId deployId,
galleryItemCode = Just (baseURL <> "#" <> unProgramId programId)
}
logHandler :: CodeWorldHandler
logHandler = public $ \ctx -> do
Just message <- fmap T.decodeUtf8 <$> getParam "message"
title <-
fromMaybe "User-reported unhelpful error message"
<$> fmap T.decodeUtf8
<$> getParam "title"
tag <- fromMaybe "error-message" <$> fmap T.decodeUtf8 <$> getParam "tag"
liftIO $ do
let body =
object
[ ("title", String title),
("body", String message),
("labels", toJSON [tag])
]
authToken <- B.readFile "github-auth-token.txt"
let authHeader = "token " <> authToken
let userAgent = "https://code.world github integration by cdsmith"
request <-
addRequestHeader "Authorization" authHeader
<$> addRequestHeader "User-agent" userAgent
<$> setRequestBodyJSON body
<$> parseRequestThrow "POST https://api.github.com/repos/google/codeworld/issues"
httpNoBody request
return ()
responseCodeFromCompileStatus :: CompileStatus -> Int
responseCodeFromCompileStatus CompileSuccess = 200
responseCodeFromCompileStatus CompileError = 400
responseCodeFromCompileStatus CompileAborted = 503
compileIfNeeded :: Context -> BuildMode -> ProgramId -> IO CompileStatus
compileIfNeeded ctx mode programId = do
hasResult <- doesFileExist (buildRootDir mode </> resultFile programId)
hasTarget <- doesFileExist (buildRootDir mode </> targetFile programId)
if
| hasResult && hasTarget -> return CompileSuccess
| hasResult -> return CompileError
| otherwise ->
MSem.with (compileSem ctx) $ compileProgram ctx mode programId
compileProgram :: Context -> BuildMode -> ProgramId -> IO CompileStatus
compileProgram ctx mode programId = do
ver <- baseVersion
baseStatus <- buildBaseIfNeeded ctx ver
case baseStatus of
CompileSuccess -> do
status <- compileIncrementally mode programId ver
T.writeFile (buildRootDir mode </> baseVersionFile programId) ver
-- It's possible that a new library was built during the compile. If so, then the code
-- we've just built is suspect, and it's better to just build it anew!
checkVer <- baseVersion
if ver == checkVer
then return status
else compileProgram ctx mode programId
_ -> return CompileAborted
compileIncrementally :: BuildMode -> ProgramId -> Text -> IO CompileStatus
compileIncrementally mode programId ver =
compileSource stage source (projectModuleFinder mode) result (getMode mode) False
where
source = sourceRootDir mode </> sourceFile programId
target = buildRootDir mode </> targetFile programId
result = buildRootDir mode </> resultFile programId
baseURL = "runBaseJS?version=" ++ T.unpack ver
stage = UseBase target (baseSymbolFile ver) baseURL
projectModuleFinder :: BuildMode -> String -> IO (Maybe FilePath)
projectModuleFinder mode modName
| length modName /= 23 || '.' `elem` modName = return Nothing
| "P" `isPrefixOf` modName = go (ProgramId (T.pack modName))
| "D" `isPrefixOf` modName = do
let deployId = DeployId (T.pack modName)
resolveDeployId mode deployId >>= go
| otherwise = return Nothing
where
go programId = do
let path = sourceRootDir mode </> sourceFile programId
exists <- doesFileExist path
if exists then return (Just path) else return Nothing
noModuleFinder :: String -> IO (Maybe FilePath)
noModuleFinder _ = return Nothing
buildBaseIfNeeded :: Context -> Text -> IO CompileStatus
buildBaseIfNeeded ctx ver = do
codeExists <- doesFileExist (baseCodeFile ver)
symbolsExist <- doesFileExist (baseSymbolFile ver)
if not codeExists || not symbolsExist
then MSem.with (baseSem ctx) $ withSystemTempDirectory "genbase" $ \tmpdir -> do
let linkMain = tmpdir </> "LinkMain.hs"
let linkBase = tmpdir </> "LinkBase.hs"
let err = tmpdir </> "output.txt"
generateBaseBundle basePaths baseIgnore "codeworld" linkMain linkBase
let stage = GenBase "LinkBase" linkBase (baseCodeFile ver) (baseSymbolFile ver)
compileSource stage linkMain noModuleFinder err "codeworld" False
else return CompileSuccess
basePaths :: [FilePath]
basePaths = ["codeworld-base/dist/doc/html/codeworld-base/codeworld-base.txt"]
baseIgnore :: [Text]
baseIgnore = ["fromCWText", "toCWText", "randomsFrom"]
errorCheck :: Context -> BuildMode -> B.ByteString -> IO (CompileStatus, B.ByteString)
errorCheck ctx mode source = withSystemTempDirectory "cw_errorCheck" $ \dir -> do
let srcFile = dir </> "program.hs"
let errFile = dir </> "output.txt"
B.writeFile srcFile source
status <-
MSem.with (errorSem ctx) $ MSem.with (compileSem ctx) $
compileSource ErrorCheck srcFile (projectModuleFinder mode) errFile (getMode mode) False
hasOutput <- doesFileExist errFile
output <- if hasOutput then B.readFile errFile else return B.empty
return (status, output)
getMode :: BuildMode -> String
getMode (BuildMode m) = m
| google/codeworld | codeworld-server/src/Main.hs | apache-2.0 | 24,271 | 0 | 23 | 4,869 | 6,724 | 3,249 | 3,475 | 540 | 4 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GADTs #-}
-- | Syntax tree for DNA program
module DNA.AST where
import Data.Typeable
import qualified Data.Vector.Storable as S
----------------------------------------------------------------
--
----------------------------------------------------------------
-- | Representation of the DNA program
--
--
data DNA a where
DotProduct :: DNA (DVector Double) -> DNA (DVector Double) -> DNA Double
ReadFile :: FilePath -> DNA (DVector Double)
FileLength :: FilePath -> DNA Int
Generate :: DNA Int -> DNA (DVector Double)
Literal :: a -> DNA a
deriving Typeable
-- | Distributed vector
data DVector a = DVector (S.Vector a)
| SKA-ScienceDataProcessor/RC | MS1/distributed-dot-product/DNA/AST.hs | apache-2.0 | 698 | 0 | 10 | 121 | 153 | 87 | 66 | 13 | 0 |
{-# LANGUAGE TemplateHaskell #-}
module Process where
import Data.UUID(UUID)
import Control.Lens hiding (element)
import Control.Monad.State.Lazy(State, gets, modify)
import System.Random(StdGen, random, mkStdGen)
import Grammar
{- Process State -}
data Sim = Sim {
_stateNouns :: [Noun]
, _stateNounSuper :: [NounTemplate]
, _stateAdjSuper :: [AdjTemplate]
, _stateRandGen :: StdGen
} deriving (Show)
makeLenses ''Sim
type SimState a = State Sim a
resetProcess :: Sim
resetProcess = Sim [] [] [] (mkStdGen 0)
{- Random Functions -}
nextUUID :: SimState UUID
nextUUID = do
randGen <- gets (^.stateRandGen)
let (newId, newGen) = random randGen
modify (set stateRandGen newGen)
return newId | Lambdanaut/Dahls | app/Process.hs | apache-2.0 | 714 | 0 | 10 | 122 | 231 | 131 | 100 | 23 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Codec.GHC.Log where
import Data.Attoparsec.Text
import Data.Text (Text)
data Message = Message Text Pos Level [Text]
deriving Show
data Pos = Pos { column :: Int, line :: Int }
deriving Show
data Level = Warning | Error
deriving Show
messageParser :: Parser Message
messageParser = do
fp <- takeWhile1 (\c -> c /= sepChar && c /= '\n' && c /= '\r') <* char sepChar
n <- decimal <* char sepChar
c <- decimal <* char sepChar
l <- choice
[ choice
[ string " warning:" *> return Warning
, string " error:" *> return Error ]
-- Before GHC 8.0
, choice
[ string " Warning:" *> return Warning
, return Error ] ]
txt <- choice
[ (string " [" *> untilLineBreak <* "\n") *> (multilinesComment <* end)
, return <$> untilLineBreak <* ("\n" <* end)
, takeLineBreak *> (multilinesComment <* end) ]
return $ Message fp (Pos c n) l txt
where
multilinesComment = many1 $ (" " *> (untilLineBreak <* "\n"))
untilLineBreak = takeWhile1 $ \w -> w /= '\n' && w /= '\r'
takeLineBreak = takeWhile1 $ \w -> w == '\n' || w == '\r'
end = choice [const () <$> "\n", endOfInput, return ()]
sepChar = ':'
| aloiscochard/sarsi | src/Codec/GHC/Log.hs | apache-2.0 | 1,220 | 0 | 16 | 312 | 443 | 233 | 210 | 32 | 1 |
{-# LANGUAGE NoImplicitPrelude, TemplateHaskell #-}
-- | Language.Lua.Annotated.Syntax is kind of an AST, but not completely.
-- This module exist to correct that deficiency.
module Language.Lua.Annotated.Syntax.HighLevel where
import BasicPrelude
import Control.Lens
import Control.Lens.TH
import Data.Text (unpack)
import Language.Lua.Annotated.Syntax
data AStat a =
AAssign a [(Var a, Exp a)]
| AFunCall a (FunCall a)
| ALabel a (Name a)
| ABreak a
| AGoto a (Name a)
| ADo a (Block a)
| AWhile a (Exp a) (Block a)
| ARepeat a (Block a) (Exp a)
| AIf a [(Exp a, Block a)] (Maybe (Block a))
| AForRange a (Name a) (Exp a) (Exp a) (Maybe (Exp a)) (Block a)
| AForIn a [(Name a, Exp a)] (Block a)
| AFunAssign a (FunName a) (FunBody a)
| ALocalFunAssign a (Name a) (FunBody a)
| ALocalAssign a (Either [Name a] [(Name a, Exp a)])
| AEmptyStat a
makePrisms ''AStat
abstract :: Show a => Iso' (Stat a) (AStat a)
abstract = iso abs con
where
abs (Assign a v e) | length v == length e = AAssign a $ zip v e
| otherwise = error $ unpack (show a) ++ ": Number of variables and expressions must be the same"
abs (FunCall a f) = AFunCall a f
abs (Label a n) = ALabel a n
abs (Break a) = ABreak a
abs (Goto a n) = AGoto a n
abs (Do a b) = ADo a b
abs (While a e b) = AWhile a e b
abs (Repeat a b e) = ARepeat a b e
abs (If a b c) = AIf a b c
abs (ForRange a n e f m b) = AForRange a n e f m b
abs (ForIn a n e b) | length n == length e = AForIn a (zip n e) b
| otherwise = error $ unpack (show a) ++ ": Number of variables and expressions must be the same"
abs (FunAssign a n b) = AFunAssign a n b
abs (LocalAssign a n (Just e)) | length n == length e = ALocalAssign a (Right $ zip n e)
| otherwise = error $ unpack (show a) ++ ": Number of variables and expressions must be the same"
abs (LocalAssign a n Nothing) = ALocalAssign a $ Left n
abs (EmptyStat a) = AEmptyStat a
con (AAssign a z) = uncurry (Assign a) $ unzip z
con (AFunCall a f) = FunCall a f
con (ABreak a) = Break a
con (AGoto a n) = Goto a n
con (ADo a b) = Do a b
con (AWhile a e b) = While a e b
con (ARepeat a b e) = Repeat a b e
con (AIf a b c) = If a b c
con (AForRange a n e f m b) = ForRange a n e f m b
con (AForIn a z b) = ForIn a n e b where (n,e) = unzip z
con (AFunAssign a n b) = FunAssign a n b
con (ALocalAssign a (Right z)) = LocalAssign a n $ Just e where (n,e) = unzip z
con (ALocalAssign a (Left n)) = LocalAssign a n Nothing
con (AEmptyStat a) = EmptyStat a
| lshift/hc2prosody | src/Language/Lua/Annotated/Syntax/HighLevel.hs | bsd-2-clause | 2,704 | 0 | 12 | 803 | 1,323 | 654 | 669 | 58 | 28 |
{-| Implementation of the LUXI loader.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.HTools.Backend.Luxi
( loadData
, parseData
) where
import qualified Control.Exception as E
import Control.Monad (liftM)
import Control.Monad.Fail (MonadFail)
import Text.JSON.Types
import qualified Text.JSON
import Ganeti.BasicTypes
import Ganeti.Errors
import qualified Ganeti.Luxi as L
import qualified Ganeti.Query.Language as Qlang
import Ganeti.Types (Hypervisor(..))
import Ganeti.HTools.Loader
import Ganeti.HTools.Types
import qualified Ganeti.HTools.Container as Container
import qualified Ganeti.HTools.Group as Group
import qualified Ganeti.HTools.Node as Node
import qualified Ganeti.HTools.Instance as Instance
import Ganeti.JSON (fromObj, fromJVal, tryFromObj, arrayMaybeFromJVal)
{-# ANN module "HLint: ignore Eta reduce" #-}
-- * Utility functions
-- | Get values behind \"data\" part of the result.
getData :: (MonadFail m) => JSValue -> m JSValue
getData (JSObject o) = fromObj (fromJSObject o) "data"
getData x = fail $ "Invalid input, expected dict entry but got " ++ show x
-- | Converts a (status, value) into m value, if possible.
parseQueryField :: (MonadFail m) => JSValue -> m (JSValue, JSValue)
parseQueryField (JSArray [status, result]) = return (status, result)
parseQueryField o =
fail $ "Invalid query field, expected (status, value) but got " ++ show o
-- | Parse a result row.
parseQueryRow :: (MonadFail m) => JSValue -> m [(JSValue, JSValue)]
parseQueryRow (JSArray arr) = mapM parseQueryField arr
parseQueryRow o =
fail $ "Invalid query row result, expected array but got " ++ show o
-- | Parse an overall query result and get the [(status, value)] list
-- for each element queried.
parseQueryResult :: (MonadFail m) => JSValue -> m [[(JSValue, JSValue)]]
parseQueryResult (JSArray arr) = mapM parseQueryRow arr
parseQueryResult o =
fail $ "Invalid query result, expected array but got " ++ show o
-- | Prepare resulting output as parsers expect it.
extractArray :: (MonadFail m) => JSValue -> m [[(JSValue, JSValue)]]
extractArray v =
getData v >>= parseQueryResult
-- | Testing result status for more verbose error message.
fromJValWithStatus :: (Text.JSON.JSON a, MonadFail m) =>
(JSValue, JSValue) -> m a
fromJValWithStatus (st, v) = do
st' <- fromJVal st
Qlang.checkRS st' v >>= fromJVal
annotateConvert :: String -> String -> String -> Result a -> Result a
annotateConvert otype oname oattr =
annotateResult $ otype ++ " '" ++ oname ++
"', error while reading attribute '" ++ oattr ++ "'"
-- | Annotate errors when converting values with owner/attribute for
-- better debugging.
genericConvert :: (Text.JSON.JSON a) =>
String -- ^ The object type
-> String -- ^ The object name
-> String -- ^ The attribute we're trying to convert
-> (JSValue, JSValue) -- ^ The value we're trying to convert
-> Result a -- ^ The annotated result
genericConvert otype oname oattr =
annotateConvert otype oname oattr . fromJValWithStatus
convertArrayMaybe :: (Text.JSON.JSON a) =>
String -- ^ The object type
-> String -- ^ The object name
-> String -- ^ The attribute we're trying to convert
-> (JSValue, JSValue) -- ^ The value we're trying to convert
-> Result [Maybe a] -- ^ The annotated result
convertArrayMaybe otype oname oattr (st, v) = do
st' <- fromJVal st
Qlang.checkRS st' v >>=
annotateConvert otype oname oattr . arrayMaybeFromJVal
-- * Data querying functionality
-- | The input data for node query.
queryNodesMsg :: L.LuxiOp
queryNodesMsg =
L.Query (Qlang.ItemTypeOpCode Qlang.QRNode)
["name", "mtotal", "mnode", "mfree", "dtotal", "dfree",
"ctotal", "cnos", "offline", "drained", "vm_capable",
"ndp/spindle_count", "group.uuid", "tags",
"ndp/exclusive_storage", "sptotal", "spfree", "ndp/cpu_speed"]
Qlang.EmptyFilter
-- | The input data for instance query.
queryInstancesMsg :: L.LuxiOp
queryInstancesMsg =
L.Query (Qlang.ItemTypeOpCode Qlang.QRInstance)
["name", "disk_usage", "be/memory", "be/vcpus",
"status", "pnode", "snodes", "tags",
"be/auto_balance", "disk_template",
"be/spindle_use", "disk.sizes", "disk.spindles",
"forthcoming"] Qlang.EmptyFilter
-- | The input data for cluster query.
queryClusterInfoMsg :: L.LuxiOp
queryClusterInfoMsg = L.QueryClusterInfo
-- | The input data for node group query.
queryGroupsMsg :: L.LuxiOp
queryGroupsMsg =
L.Query (Qlang.ItemTypeOpCode Qlang.QRGroup)
["uuid", "name", "alloc_policy", "ipolicy", "tags"]
Qlang.EmptyFilter
-- | Wraper over 'callMethod' doing node query.
queryNodes :: L.Client -> IO (Result JSValue)
queryNodes = liftM errToResult . L.callMethod queryNodesMsg
-- | Wraper over 'callMethod' doing instance query.
queryInstances :: L.Client -> IO (Result JSValue)
queryInstances = liftM errToResult . L.callMethod queryInstancesMsg
-- | Wrapper over 'callMethod' doing cluster information query.
queryClusterInfo :: L.Client -> IO (Result JSValue)
queryClusterInfo = liftM errToResult . L.callMethod queryClusterInfoMsg
-- | Wrapper over callMethod doing group query.
queryGroups :: L.Client -> IO (Result JSValue)
queryGroups = liftM errToResult . L.callMethod queryGroupsMsg
-- | Parse a instance list in JSON format.
getInstances :: NameAssoc
-> JSValue
-> Result [(String, Instance.Instance)]
getInstances ktn arr = extractArray arr >>= mapM (parseInstance ktn)
-- | Construct an instance from a JSON object.
parseInstance :: NameAssoc
-> [(JSValue, JSValue)]
-> Result (String, Instance.Instance)
parseInstance ktn [ name, disk, mem, vcpus
, status, pnode, snodes, tags
, auto_balance, disk_template, su
, dsizes, dspindles, forthcoming ] = do
xname <- annotateResult "Parsing new instance" (fromJValWithStatus name)
let convert a = genericConvert "Instance" xname a
xdisk <- convert "disk_usage" disk
xmem <- convert "be/memory" mem
xvcpus <- convert "be/vcpus" vcpus
xpnode <- convert "pnode" pnode >>= lookupNode ktn xname
xsnodes <- convert "snodes" snodes::Result [String]
snode <- case xsnodes of
[] -> return Node.noSecondary
x:_ -> lookupNode ktn xname x
xrunning <- convert "status" status
xtags <- convert "tags" tags
xauto_balance <- convert "auto_balance" auto_balance
xdt <- convert "disk_template" disk_template
xsu <- convert "be/spindle_use" su
xdsizes <- convert "disk.sizes" dsizes
xdspindles <- convertArrayMaybe "Instance" xname "disk.spindles" dspindles
xforthcoming <- convert "forthcoming" forthcoming
let disks = zipWith Instance.Disk xdsizes xdspindles
inst = Instance.create xname xmem xdisk disks
xvcpus xrunning xtags xauto_balance xpnode snode xdt xsu []
xforthcoming
return (xname, inst)
parseInstance _ v = fail ("Invalid instance query result: " ++ show v)
-- | Parse a node list in JSON format.
getNodes :: NameAssoc -> JSValue -> Result [(String, Node.Node)]
getNodes ktg arr = extractArray arr >>= mapM (parseNode ktg)
-- | Construct a node from a JSON object.
parseNode :: NameAssoc -> [(JSValue, JSValue)] -> Result (String, Node.Node)
parseNode ktg [ name, mtotal, mnode, mfree, dtotal, dfree
, ctotal, cnos, offline, drained, vm_capable, spindles, g_uuid
, tags, excl_stor, sptotal, spfree, cpu_speed ]
= do
xname <- annotateResult "Parsing new node" (fromJValWithStatus name)
let convert a = genericConvert "Node" xname a
xoffline <- convert "offline" offline
xdrained <- convert "drained" drained
xvm_capable <- convert "vm_capable" vm_capable
xgdx <- convert "group.uuid" g_uuid >>= lookupGroup ktg xname
xtags <- convert "tags" tags
xexcl_stor <- convert "exclusive_storage" excl_stor
xcpu_speed <- convert "cpu_speed" cpu_speed
let live = not xoffline && xvm_capable
lvconvert def n d = eitherLive live def $ convert n d
xsptotal <- if xexcl_stor
then lvconvert 0 "sptotal" sptotal
else convert "spindles" spindles
let xspfree = genericResult (const (0 :: Int)) id
$ lvconvert 0 "spfree" spfree
-- "spfree" might be missing, if sharedfile is the only
-- supported disk template
xmtotal <- lvconvert 0.0 "mtotal" mtotal
xmnode <- lvconvert 0 "mnode" mnode
xmfree <- lvconvert 0 "mfree" mfree
let xdtotal = genericResult (const 0.0) id
$ lvconvert 0.0 "dtotal" dtotal
xdfree = genericResult (const 0) id
$ lvconvert 0 "dfree" dfree
-- "dtotal" and "dfree" might be missing, e.g., if sharedfile
-- is the only supported disk template
xctotal <- lvconvert 0.0 "ctotal" ctotal
xcnos <- lvconvert 0 "cnos" cnos
let node = flip Node.setCpuSpeed xcpu_speed .
flip Node.setNodeTags xtags $
Node.create xname xmtotal xmnode xmfree xdtotal xdfree
xctotal xcnos (not live || xdrained) xsptotal xspfree
xgdx xexcl_stor
return (xname, node)
parseNode _ v = fail ("Invalid node query result: " ++ show v)
-- | Parses the cluster tags.
getClusterData :: JSValue -> Result ([String], IPolicy, String, Hypervisor)
getClusterData (JSObject obj) = do
let errmsg = "Parsing cluster info"
obj' = fromJSObject obj
ctags <- tryFromObj errmsg obj' "tags"
cpol <- tryFromObj errmsg obj' "ipolicy"
master <- tryFromObj errmsg obj' "master"
hypervisor <- tryFromObj errmsg obj' "default_hypervisor"
return (ctags, cpol, master, hypervisor)
getClusterData _ = Bad "Cannot parse cluster info, not a JSON record"
-- | Parses the cluster groups.
getGroups :: JSValue -> Result [(String, Group.Group)]
getGroups jsv = extractArray jsv >>= mapM parseGroup
-- | Parses a given group information.
parseGroup :: [(JSValue, JSValue)] -> Result (String, Group.Group)
parseGroup [uuid, name, apol, ipol, tags] = do
xname <- annotateResult "Parsing new group" (fromJValWithStatus name)
let convert a = genericConvert "Group" xname a
xuuid <- convert "uuid" uuid
xapol <- convert "alloc_policy" apol
xipol <- convert "ipolicy" ipol
xtags <- convert "tags" tags
-- TODO: parse networks to which this group is connected
return (xuuid, Group.create xname xuuid xapol [] xipol xtags)
parseGroup v = fail ("Invalid group query result: " ++ show v)
-- * Main loader functionality
-- | Builds the cluster data by querying a given socket name.
readData :: String -- ^ Unix socket to use as source
-> IO (Result JSValue, Result JSValue, Result JSValue, Result JSValue)
readData master =
E.bracket
(L.getLuxiClient master)
L.closeClient
(\s -> do
nodes <- queryNodes s
instances <- queryInstances s
cinfo <- queryClusterInfo s
groups <- queryGroups s
return (groups, nodes, instances, cinfo)
)
-- | Converts the output of 'readData' into the internal cluster
-- representation.
parseData :: (Result JSValue, Result JSValue, Result JSValue, Result JSValue)
-> Result ClusterData
parseData (groups, nodes, instances, cinfo) = do
group_data <- groups >>= getGroups
let (group_names, group_idx) = assignIndices group_data
node_data <- nodes >>= getNodes group_names
let (node_names, node_idx) = assignIndices node_data
inst_data <- instances >>= getInstances node_names
let (_, inst_idx) = assignIndices inst_data
(ctags, cpol, master, hypervisor) <- cinfo >>= getClusterData
node_idx' <- setMaster node_names node_idx master
let node_idx'' = Container.map (`Node.setHypervisor` hypervisor) node_idx'
return (ClusterData group_idx node_idx'' inst_idx ctags cpol)
-- | Top level function for data loading.
loadData :: String -- ^ Unix socket to use as source
-> IO (Result ClusterData)
loadData = fmap parseData . readData
| ganeti/ganeti | src/Ganeti/HTools/Backend/Luxi.hs | bsd-2-clause | 13,418 | 0 | 14 | 2,824 | 3,087 | 1,602 | 1,485 | 221 | 2 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE BangPatterns #-}
module Data.CRF.Chain2.Tiers.Model
(
-- * Model
Model (..)
, mkModel
, fromSet
, fromMap
, toMap
-- * Potential
, phi
, index
) where
import Control.Applicative ((<$>), (<*>))
import Control.Monad (guard)
import Data.Binary (Binary, get, put)
import Data.Int (Int32)
import qualified Data.Set as S
import qualified Data.Map as M
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as U
import Data.Vector.Binary ()
import qualified Data.Number.LogFloat as L
import Data.CRF.Chain2.Tiers.Dataset.Internal
import Data.CRF.Chain2.Tiers.Feature
import qualified Data.CRF.Chain2.Tiers.Array as A
-- | Dummy feature index.
dummy :: FeatIx
dummy = FeatIx (-1)
{-# INLINE dummy #-}
----------------------------------------------------
-- (Feature -> FeatIx) map
----------------------------------------------------
-- | Transition map restricted to a particular tagging layer.
-- Transitions of x form.
type T1Map = A.Array Lb FeatIx
-- | Transition map restricted to a particular tagging layer.
-- Transitions of (x, y) form.
type T2Map = A.Array (Lb, Lb) FeatIx
-- | Transition map restricted to a particular tagging layer.
-- Transitions of (x, y, z) form.
type T3Map = A.Array (Lb, Lb, Lb) FeatIx
mkT3Map :: [(Feat, FeatIx)] -> T3Map
mkT3Map xs =
let ys = [((x, y, z), ix) | (TFeat3 x y z _, ix) <- xs]
in A.mkArray dummy ys
mkT2Map :: [(Feat, FeatIx)] -> T2Map
mkT2Map xs =
let ys = [((x, y), ix) | (TFeat2 x y _, ix) <- xs]
in A.mkArray dummy ys
mkT1Map :: [(Feat, FeatIx)] -> T1Map
mkT1Map xs =
let ys = [(x, ix) | (TFeat1 x _, ix) <- xs]
in A.mkArray dummy ys
unT3Map :: Int -> T3Map -> [(Feat, FeatIx)]
unT3Map k t3 =
[ (TFeat3 x y z k, ix)
| ((x, y, z), ix) <- A.unArray t3
, ix /= dummy ]
unT2Map :: Int -> T2Map -> [(Feat, FeatIx)]
unT2Map k t2 =
[ (TFeat2 x y k, ix)
| ((x, y), ix) <- A.unArray t2
, ix /= dummy ]
unT1Map :: Int -> T1Map -> [(Feat, FeatIx)]
unT1Map k t1 =
[ (TFeat1 x k, ix)
| (x, ix) <- A.unArray t1
, ix /= dummy ]
-- | Observation map restricted to a particular tagging layer.
data OMap = OMap {
-- | Where memory ranges related to
-- individual observations begin?
oBeg :: U.Vector Int32
-- | Labels related to individual observations.
, oLb :: U.Vector Lb
-- | Feature indices related to individual (Ob, Lb) pairs.
, oIx :: U.Vector FeatIx }
instance Binary OMap where
put OMap{..} = put oBeg >> put oLb >> put oIx
get = OMap <$> get <*> get <*> get
mkOMap :: [(Feat, FeatIx)] -> OMap
mkOMap xs = OMap
{ oBeg = U.fromList $ scanl (+) 0
[ fromIntegral (M.size lbMap)
| ob <- map mkOb [0 .. maxOb]
, let lbMap = maybe M.empty id $ M.lookup ob ftMap ]
, oLb = U.fromList . concat $
[ M.keys lbMap
| lbMap <- M.elems ftMap ]
, oIx = U.fromList . concat $
[ M.elems lbMap
| lbMap <- M.elems ftMap ] }
where
-- A feature map of type Map Ob (Map Lb FeatIx).
ftMap = fmap M.fromList $ M.fromListWith (++)
[ (ob, [(x, ix)])
| (OFeat ob x _, ix) <- xs ]
-- Max observation
maxOb = unOb . fst $ M.findMax ftMap
-- | Deconstruct observation feature map given the layer identifier.
unOMap :: Int -> OMap -> [(Feat, FeatIx)]
unOMap k OMap{..} =
[ (OFeat o x k, i)
| (o, (p, q)) <- zip
(map mkOb [0..])
(pairs . map fromIntegral $ U.toList oBeg)
, (x, i) <- zip
(U.toList $ U.slice p (q - p) oLb)
(U.toList $ U.slice p (q - p) oIx) ]
where
pairs xs = zip xs (tail xs)
-- | Feature map restricted to a particular layer.
data LayerMap = LayerMap
{ t1Map :: !T1Map
, t2Map :: !T2Map
, t3Map :: !T3Map
, obMap :: !OMap }
instance Binary LayerMap where
put LayerMap{..} = put t1Map >> put t2Map >> put t3Map >> put obMap
get = LayerMap <$> get <*> get <*> get <*> get
-- | Deconstruct the layer map given the layer identifier.
unLayerMap :: Int -> LayerMap -> [(Feat, FeatIx)]
unLayerMap k LayerMap{..} = concat
[ unT1Map k t1Map
, unT2Map k t2Map
, unT3Map k t3Map
, unOMap k obMap ]
-- | Feature map is a vectro of layer maps.
type FeatMap = V.Vector LayerMap
-- | Get index of a feature.
featIndex :: Feat -> FeatMap -> Maybe FeatIx
featIndex (TFeat3 x y z k) v = do
m <- t3Map <$> (v V.!? k)
ix <- m A.!? (x, y, z)
guard (ix /= dummy)
return ix
featIndex (TFeat2 x y k) v = do
m <- t2Map <$> (v V.!? k)
ix <- m A.!? (x, y)
guard (ix /= dummy)
return ix
featIndex (TFeat1 x k) v = do
m <- t1Map <$> (v V.!? k)
ix <- m A.!? x
guard (ix /= dummy)
return ix
featIndex (OFeat ob x k) v = do
OMap{..} <- obMap <$> (v V.!? k)
p <- fromIntegral <$> oBeg U.!? (unOb ob)
q <- fromIntegral <$> oBeg U.!? (unOb ob + 1)
i <- U.findIndex (==x) (U.slice p (q - p) oLb)
ix <- oIx U.!? (p + i)
-- guard (ix /= dummy)
return ix
-- | Make feature map from a *set* of (feature, index) pairs.
mkFeatMap :: [(Feat, FeatIx)] -> FeatMap
mkFeatMap xs = V.fromList
-- TODO: We can first divide features between individual layers.
[ mkLayerMap $ filter (inLayer k . fst) xs
| k <- [0 .. maxLayerNum] ]
where
-- Make layer map.
mkLayerMap = LayerMap
<$> mkT1Map
<*> mkT2Map
<*> mkT3Map
<*> mkOMap
-- Number of layers (TODO: could be taken as mkFeatMap argument).
maxLayerNum = maximum $ map (ln.fst) xs
-- Check if feature is in a given layer.
inLayer k x | ln x == k = True
| otherwise = False
-- | Deconstruct the feature map.
unFeatMap :: FeatMap -> [(Feat, FeatIx)]
unFeatMap fm = concat
[ unLayerMap i layer
| (i, layer) <- zip [0..] (V.toList fm) ]
----------------------------------------------------
-- Internal model
----------------------------------------------------
-- | Internal model data.
data Model = Model
{ values :: U.Vector Double
, featMap :: FeatMap }
instance Binary Model where
put Model{..} = put values >> put featMap
get = Model <$> get <*> get
-- | Construct model from a feature set.
-- All values will be set to 1 in log domain.
fromSet :: S.Set Feat -> Model
fromSet ftSet = Model
{ values = U.replicate (S.size ftSet) 0.0
, featMap =
let featIxs = map FeatIx [0..]
featLst = S.toList ftSet
in mkFeatMap (zip featLst featIxs) }
-- | Construct model from a dataset given a feature selection function.
mkModel :: FeatSel -> [(Xs, Ys)] -> Model
mkModel ftSel = fromSet . S.fromList . concatMap (uncurry ftSel)
-- | Construct model from a (feature -> value) map.
fromMap :: M.Map Feat L.LogFloat -> Model
fromMap ftMap = Model
{ values = U.fromList . map L.logFromLogFloat $ M.elems ftMap
, featMap =
let featIxs = map FeatIx [0..]
featLst = M.keys ftMap
in mkFeatMap (zip featLst featIxs) }
-- | Convert model to a (feature -> value) map.
toMap :: Model -> M.Map Feat L.LogFloat
toMap Model{..} = M.fromList
[ (ft, L.logToLogFloat (values U.! unFeatIx ix))
| (ft, ix) <- unFeatMap featMap ]
----------------------------------------------------
-- Potential
----------------------------------------------------
-- | Potential assigned to the feature -- exponential of the
-- corresonding parameter.
phi :: Model -> Feat -> L.LogFloat
phi Model{..} ft = case featIndex ft featMap of
Just ix -> L.logToLogFloat (values U.! unFeatIx ix)
Nothing -> L.logToLogFloat (0 :: Double)
{-# INLINE phi #-}
-- | Index of a feature.
index :: Model -> Feat -> Maybe FeatIx
index Model{..} ft = featIndex ft featMap
{-# INLINE index #-}
| kawu/crf-chain2-tiers | src/Data/CRF/Chain2/Tiers/Model.hs | bsd-2-clause | 8,015 | 0 | 16 | 2,108 | 2,647 | 1,435 | 1,212 | 189 | 2 |
{-# Language TypeFamilies #-}
module Data.Source.ByteString.Char8.Offset where
import Data.Char
import Data.Source.Class
import qualified Data.ByteString as B
data Src
= Src
{ loc :: Int
, str :: B.ByteString
} deriving (Eq,Ord,Show,Read)
instance Source Src where
type Location Src = Int
type Element Src = Char
type Token Src = B.ByteString
type Error Src = ()
offset = loc
uncons (Src loc bs)
= Right $ B.uncons bs >>= \(w,t) ->
let ch = chr $ fromIntegral w
in return (ch, Src (loc+1) t)
view (Src loc bs) _ eh nh
= case B.uncons bs of
Nothing -> eh
Just (w,t) -> let ch = chr $ fromIntegral w
in nh ch $ Src (loc+1) t
location (Src ofs _)
= ofs
token (Src lloc lbs) (Src rloc _)
= B.take (rloc - lloc) lbs
mkSrc :: B.ByteString -> Src
mkSrc = Src 0
| permeakra/source | Data/Source/ByteString/Char8/Offset.hs | bsd-3-clause | 907 | 0 | 14 | 296 | 367 | 195 | 172 | 31 | 1 |
{-# LANGUAGE CPP #-}
#if __GLASGOW_HASKELL__ >= 701
{-# LANGUAGE Trustworthy #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Data.Binary
-- Copyright : Lennart Kolmodin
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Lennart Kolmodin <[email protected]>
-- Stability : unstable
-- Portability : portable to Hugs and GHC. Requires the FFI and some flexible instances.
--
-- Binary serialisation of Haskell values to and from lazy 'ByteString's.
-- The Binary library provides methods for encoding Haskell values as
-- streams of bytes directly in memory. The resulting 'ByteString' can
-- then be written to disk, sent over the network, or further processed
-- (for example, compressed with gzip).
--
-- The @binary@ package is notable in that it provides both pure, and
-- high performance serialisation.
--
-- Values encoded using the 'Binary' class are always encoded in network order
-- (big endian) form, and encoded data should be portable across
-- machine endianness, word size, or compiler version. For example,
-- data encoded using the 'Binary' class could be written on any machine,
-- and read back on any another.
--
-- If the specifics of the data format is not important to you, for example,
-- you are more interested in serializing and deserializing values than
-- in which format will be used, it is possible to derive 'Binary'
-- instances using the generic support. See 'GBinary'.
--
-- If you have specific requirements about the encoding format, you can use
-- the encoding and decoding primitives directly, see the modules
-- "Data.Binary.Get" and "Data.Binary.Put".
--
-----------------------------------------------------------------------------
module Data.Binary (
-- * The Binary class
Binary(..)
-- ** Example
-- $example
#ifdef GENERICS
-- * Generic support
-- $generics
, GBinary(..)
#endif
-- * The Get and Put monads
, Get
, Put
-- * Useful helpers for writing instances
, putWord8
, getWord8
-- * Binary serialisation
, encode -- :: Binary a => a -> ByteString
, decode -- :: Binary a => ByteString -> a
, decodeOrFail
-- * IO functions for serialisation
, encodeFile -- :: Binary a => FilePath -> a -> IO ()
, decodeFile -- :: Binary a => FilePath -> IO a
, decodeFileOrFail
, decodeGetFileOrFail
, module Data.Word -- useful
) where
import Data.Word
import Data.Binary.Class
import Data.Binary.Put
import Data.Binary.Get
#ifdef GENERICS
import Data.Binary.Generic ()
#endif
import qualified Data.ByteString as B ( hGet, length )
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Internal as L ( defaultChunkSize )
import System.IO ( withBinaryFile, IOMode(ReadMode) )
------------------------------------------------------------------------
-- $example
-- To serialise a custom type, an instance of Binary for that type is
-- required. For example, suppose we have a data structure:
--
-- > data Exp = IntE Int
-- > | OpE String Exp Exp
-- > deriving Show
--
-- We can encode values of this type into bytestrings using the
-- following instance, which proceeds by recursively breaking down the
-- structure to serialise:
--
-- > instance Binary Exp where
-- > put (IntE i) = do put (0 :: Word8)
-- > put i
-- > put (OpE s e1 e2) = do put (1 :: Word8)
-- > put s
-- > put e1
-- > put e2
-- >
-- > get = do t <- get :: Get Word8
-- > case t of
-- > 0 -> do i <- get
-- > return (IntE i)
-- > 1 -> do s <- get
-- > e1 <- get
-- > e2 <- get
-- > return (OpE s e1 e2)
--
-- Note how we write an initial tag byte to indicate each variant of the
-- data type.
--
-- We can simplify the writing of 'get' instances using monadic
-- combinators:
--
-- > get = do tag <- getWord8
-- > case tag of
-- > 0 -> liftM IntE get
-- > 1 -> liftM3 OpE get get get
--
-- To serialise this to a bytestring, we use 'encode', which packs the
-- data structure into a binary format, in a lazy bytestring
--
-- > > let e = OpE "*" (IntE 7) (OpE "/" (IntE 4) (IntE 2))
-- > > let v = encode e
--
-- Where 'v' is a binary encoded data structure. To reconstruct the
-- original data, we use 'decode'
--
-- > > decode v :: Exp
-- > OpE "*" (IntE 7) (OpE "/" (IntE 4) (IntE 2))
--
-- The lazy ByteString that results from 'encode' can be written to
-- disk, and read from disk using Data.ByteString.Lazy IO functions,
-- such as hPutStr or writeFile:
--
-- > > writeFile "/tmp/exp.txt" (encode e)
--
-- And read back with:
--
-- > > readFile "/tmp/exp.txt" >>= return . decode :: IO Exp
-- > OpE "*" (IntE 7) (OpE "/" (IntE 4) (IntE 2))
--
-- We can also directly serialise a value to and from a Handle, or a file:
--
-- > > v <- decodeFile "/tmp/exp.txt" :: IO Exp
-- > OpE "*" (IntE 7) (OpE "/" (IntE 4) (IntE 2))
--
-- And write a value to disk
--
-- > > encodeFile "/tmp/a.txt" v
--
------------------------------------------------------------------------
-- Wrappers to run the underlying monad
-- | Encode a value using binary serialisation to a lazy ByteString.
--
encode :: Binary a => a -> ByteString
encode = runPut . put
{-# INLINE encode #-}
-- | Decode a value from a lazy ByteString, reconstructing the original structure.
decode :: Binary a => ByteString -> a
decode = runGet get
-- | Decode a value from a lazy ByteString. Returning 'Left' on failure and
-- 'Right' on success. In both cases the unconsumed input and the number of
-- consumed bytes is returned. In case of failure, a human-readable error
-- message will be returned as well.
decodeOrFail :: Binary a => L.ByteString
-> Either (L.ByteString, ByteOffset, String)
(L.ByteString, ByteOffset, a)
decodeOrFail = runGetOrFail get
------------------------------------------------------------------------
-- Convenience IO operations
-- | Lazily serialise a value to a file.
--
-- This is just a convenience function, it's defined simply as:
--
-- > encodeFile f = B.writeFile f . encode
--
-- So for example if you wanted to compress as well, you could use:
--
-- > B.writeFile f . compress . encode
--
encodeFile :: Binary a => FilePath -> a -> IO ()
encodeFile f v = L.writeFile f (encode v)
-- | Decode a value from a file. In case of errors, 'error' will
-- be called with the error message.
decodeFile :: Binary a => FilePath -> IO a
decodeFile f = do
result <- decodeFileOrFail f
case result of
Right x -> return x
Left (_,str) -> error str
-- | Decode a value from a file. In case of success, the value will be returned
-- in 'Right'. In case of decoder errors, the error message together with
-- the byte offset will be returned.
decodeFileOrFail :: Binary a => FilePath -> IO (Either (ByteOffset, String) a)
decodeFileOrFail f = decodeGetFileOrFail get f
-- | Decode a value from a file using a 'Get' monad. In case of success, the
-- value will be returned in 'Right'. In case of decoder errors, the error
-- message together with the byte offset will be returned.
decodeGetFileOrFail :: Get a -> FilePath -> IO (Either (ByteOffset, String) a)
decodeGetFileOrFail g f =
withBinaryFile f ReadMode $ \h -> do
feed (runGetIncremental g) h
where -- TODO: put in Data.Binary.Get and name pushFromHandle?
feed (Done _ _ x) _ = return (Right x)
feed (Fail _ pos str) _ = return (Left (pos, str))
feed (Partial k) h = do
chunk <- B.hGet h L.defaultChunkSize
case B.length chunk of
0 -> feed (k Nothing) h
_ -> feed (k (Just chunk)) h
------------------------------------------------------------------------
-- $generics
--
-- Beginning with GHC 7.2, it is possible to use binary serialization
-- without writing any instance boilerplate code.
--
-- > {-# LANGUAGE DeriveGeneric #-}
-- >
-- > import Data.Binary
-- > import GHC.Generics (Generic)
-- >
-- > data Foo = Foo
-- > deriving (Generic)
-- >
-- > -- GHC will automatically fill out the instance
-- > instance Binary Foo
--
-- This mechanism makes use of GHC's efficient built-in generics
-- support.
| ezyang/binary | src/Data/Binary.hs | bsd-3-clause | 8,573 | 0 | 16 | 2,088 | 832 | 530 | 302 | 54 | 4 |
{-# language CPP #-}
-- No documentation found for Chapter "Core11"
module Vulkan.Core11 ( pattern API_VERSION_1_1
, module Vulkan.Core11.DeviceInitialization
, module Vulkan.Core11.Enums
, module Vulkan.Core11.Handles
, module Vulkan.Core11.Originally_Based_On_VK_KHR_protected_memory
, module Vulkan.Core11.Originally_Based_On_VK_KHR_subgroup
, module Vulkan.Core11.Promoted_From_VK_KHR_16bit_storage
, module Vulkan.Core11.Promoted_From_VK_KHR_bind_memory2
, module Vulkan.Core11.Promoted_From_VK_KHR_dedicated_allocation
, module Vulkan.Core11.Promoted_From_VK_KHR_descriptor_update_template
, module Vulkan.Core11.Promoted_From_VK_KHR_device_group
, module Vulkan.Core11.Promoted_From_VK_KHR_device_groupAndVK_KHR_bind_memory2
, module Vulkan.Core11.Promoted_From_VK_KHR_device_group_creation
, module Vulkan.Core11.Promoted_From_VK_KHR_external_fence
, module Vulkan.Core11.Promoted_From_VK_KHR_external_fence_capabilities
, module Vulkan.Core11.Promoted_From_VK_KHR_external_memory
, module Vulkan.Core11.Promoted_From_VK_KHR_external_memory_capabilities
, module Vulkan.Core11.Promoted_From_VK_KHR_external_semaphore
, module Vulkan.Core11.Promoted_From_VK_KHR_external_semaphore_capabilities
, module Vulkan.Core11.Promoted_From_VK_KHR_get_memory_requirements2
, module Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2
, module Vulkan.Core11.Promoted_From_VK_KHR_maintenance1
, module Vulkan.Core11.Promoted_From_VK_KHR_maintenance2
, module Vulkan.Core11.Promoted_From_VK_KHR_maintenance3
, module Vulkan.Core11.Promoted_From_VK_KHR_multiview
, module Vulkan.Core11.Promoted_From_VK_KHR_sampler_ycbcr_conversion
, module Vulkan.Core11.Promoted_From_VK_KHR_shader_draw_parameters
, module Vulkan.Core11.Promoted_From_VK_KHR_variable_pointers
) where
import Vulkan.Core11.DeviceInitialization
import Vulkan.Core11.Enums
import Vulkan.Core11.Handles
import Vulkan.Core11.Originally_Based_On_VK_KHR_protected_memory
import Vulkan.Core11.Originally_Based_On_VK_KHR_subgroup
import Vulkan.Core11.Promoted_From_VK_KHR_16bit_storage
import Vulkan.Core11.Promoted_From_VK_KHR_bind_memory2
import Vulkan.Core11.Promoted_From_VK_KHR_dedicated_allocation
import Vulkan.Core11.Promoted_From_VK_KHR_descriptor_update_template
import Vulkan.Core11.Promoted_From_VK_KHR_device_group
import Vulkan.Core11.Promoted_From_VK_KHR_device_groupAndVK_KHR_bind_memory2
import Vulkan.Core11.Promoted_From_VK_KHR_device_group_creation
import Vulkan.Core11.Promoted_From_VK_KHR_external_fence
import Vulkan.Core11.Promoted_From_VK_KHR_external_fence_capabilities
import Vulkan.Core11.Promoted_From_VK_KHR_external_memory
import Vulkan.Core11.Promoted_From_VK_KHR_external_memory_capabilities
import Vulkan.Core11.Promoted_From_VK_KHR_external_semaphore
import Vulkan.Core11.Promoted_From_VK_KHR_external_semaphore_capabilities
import Vulkan.Core11.Promoted_From_VK_KHR_get_memory_requirements2
import Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2
import Vulkan.Core11.Promoted_From_VK_KHR_maintenance1
import Vulkan.Core11.Promoted_From_VK_KHR_maintenance2
import Vulkan.Core11.Promoted_From_VK_KHR_maintenance3
import Vulkan.Core11.Promoted_From_VK_KHR_multiview
import Vulkan.Core11.Promoted_From_VK_KHR_sampler_ycbcr_conversion
import Vulkan.Core11.Promoted_From_VK_KHR_shader_draw_parameters
import Vulkan.Core11.Promoted_From_VK_KHR_variable_pointers
import Data.Word (Word32)
import Vulkan.Version (pattern MAKE_API_VERSION)
pattern API_VERSION_1_1 :: Word32
pattern API_VERSION_1_1 = MAKE_API_VERSION 1 1 0
| expipiplus1/vulkan | src/Vulkan/Core11.hs | bsd-3-clause | 4,153 | 0 | 6 | 789 | 410 | 277 | 133 | -1 | -1 |
module Haskell.Types where
import Control.Lens
import qualified Text.PrettyPrint.Leijen.Text as PP
import Data.IndexedSet (IndexKey(..), SplitKey(..))
import Core.Types
import Core.Pretty
type HsType meta = NType meta
type HsTyCon meta = NTyCon meta
type HsTyDecl meta = NTyDecl meta
data HsPat' meta = HPVar Name
-- | HPInt Integer
| HPWildCard
| HPCon Name [HsPat meta]
deriving (Show, Eq)
instance (Pretty meta) => Pretty (HsPat' meta) where
pretty (HPVar v) = pretty v
pretty HPWildCard = "_"
pretty (HPCon n ps) = PP.parens $ pretty n PP.<+> PP.hsep (map pretty ps)
type HsPat meta = Ann meta HsPat'
data HsLet' meta = LAnn Name (HsType meta)
| LBind Name [HsPat meta] (HsExpr meta)
deriving (Show, Eq)
instance (Pretty meta) => Pretty (HsLet' meta) where
pretty (LAnn n t) = pretty n PP.<+> "::" PP.<+> pretty t
pretty (LBind n [] e) = pretty n PP.<+> "=" PP.<+> pretty e
pretty (LBind n pats e) = pretty n PP.<+> PP.hsep (map pretty pats) PP.<+> "=" PP.<+> pretty e
instance IndexKey Name (HsLet' meta)
instance SplitKey Name (HsLet' meta) where
type WithoutKey Name (HsLet' meta) = Either (HsType meta) ([HsPat meta], (HsExpr meta))
splitKey = iso fwd back
where fwd (LAnn n a) = (n, Left a)
fwd (LBind n a b) = (n, Right (a, b))
back (n, Left a) = LAnn n a
back (n, Right (a, b)) = LBind n a b
type HsLet meta = Ann meta HsLet'
type HsAlts meta = [(HsPat meta, HsExpr meta)]
data HsExpr' meta = HLet [HsLet meta] (HsExpr meta)
| HCase (HsExpr meta) (HsAlts meta)
| HVar Name
| HLit Name
| HInt Integer
| HApp (HsExpr meta) (HsExpr meta)
| HTyAnn (HsType meta) (HsExpr meta)
deriving (Show, Eq)
instance (Pretty meta) => Pretty (HsExpr' meta) where
pretty (HVar v) = pretty v
pretty (HLit l) = pretty l
pretty (HInt i) = pretty i
pretty (HLet lets expr) = "let" PP.<+> PP.align (PP.vsep $ map pretty lets) PP.<$> "in" PP.<+> pretty expr
pretty (HCase e alts) = "case" PP.<+> pretty e PP.<+> "of" PP.<$> PP.nest 2 (PP.vsep $ map palt alts)
where palt (pat, exp') = pretty pat PP.<+> "->" PP.<+> pretty exp'
pretty (HApp a b) = br a PP.<+> br b
pretty (HTyAnn n t) = pretty n PP.<+> "::" PP.<+> pretty t
instance Complex (HsExpr' meta) where
complex (HVar _) = False
complex (HLit _) = False
complex (HInt _) = False
complex (HLet _ _) = True
complex (HCase _ _) = True
complex (HApp _ _) = True
complex (HTyAnn _ _) = True
type HsExpr meta = Ann meta HsExpr'
data HsTop meta = TELet (HsLet meta)
| TEData (HsTyDecl meta)
deriving (Show, Eq)
instance (Pretty meta) => Pretty (HsTop meta) where
pretty (TELet l) = pretty l
pretty (TEData d) = pretty d
type HsTopsP = [HsTop Pos]
prettyHsTop :: Pretty meta => [HsTop meta] -> Doc
prettyHsTop = PP.vsep . map pretty
makePrisms ''HsTop
makePrisms ''HsLet'
| abbradar/dnohs | src/Haskell/Types.hs | bsd-3-clause | 3,076 | 0 | 12 | 858 | 1,339 | 691 | 648 | -1 | -1 |
module Cabal2Nix.Flags ( configureCabalFlags ) where
import Distribution.Package
import Distribution.PackageDescription
configureCabalFlags :: PackageIdentifier -> FlagAssignment
configureCabalFlags (PackageIdentifier (PackageName name) _)
| name == "accelerate-examples"= [disable "opencl"]
| name == "arithmoi" = [disable "llvm"]
| name == "darcs" = [enable "library", enable "force-char8-encoding"]
| name == "diagrams-builder" = [enable "cairo", enable "svg", enable "ps", enable "rasterific"]
| name == "folds" = [disable "test-hlint"]
| name == "git-annex" = [enable "Assistant" , enable "Production"]
| name == "haskeline" = [enable "terminfo"]
| name == "haste-compiler" = [enable "portable"]
| name == "highlighting-kate" = [enable "pcre-light"]
| name == "hslua" = [enable "system-lua"]
| name == "hxt" = [enable "network-uri"]
| name == "idris" = [enable "gmp", enable "ffi"]
| name == "io-streams" = [enable "NoInteractiveTests"]
| name == "pandoc" = [enable "https"]
| name == "reactive-banana-wx" = [disable "buildExamples"]
| name == "snap-server" = [enable "openssl"]
| name == "xmobar" = [enable "all_extensions"]
| name == "xmonad-extras" = [disable "with_hlist", enable "with_split", enable "with_parsec"]
| name == "yi" = [enable "pango", enable "vty"]
| otherwise = []
enable :: String -> (FlagName,Bool)
enable name = (FlagName name, True)
disable :: String -> (FlagName,Bool)
disable name = (FlagName name, False)
| spencerjanssen/cabal2nix | src/Cabal2Nix/Flags.hs | bsd-3-clause | 1,642 | 0 | 9 | 402 | 539 | 266 | 273 | 29 | 1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE EmptyCase #-}
module Language.BCoPL.TypeLevel.MetaTheory.Nat where
import Language.BCoPL.TypeLevel.Peano
import Language.BCoPL.TypeLevel.Nat
import Language.BCoPL.TypeLevel.Equiv
import Language.BCoPL.TypeLevel.Exists
-- $setup
-- >>> :set -XGADTs
-- >>> :set -XTypeFamilies
-- >>> :set -XDataKinds
-- >>> :set -XKindSignatures
-- >>> :set -XTypeOperators
-- >>> :set -XScopedTypeVariables
-- >>> :set -XFlexibleInstances
-- >>> :set -XUndecidableInstances
-- >>> let one = S' Z'
-- >>> let two = S'(S' Z')
-- 定理 2.1 加法単位元
-- | 左単位元
--
-- >>> zeroPlus Z'
-- Z plus Z is Z by P-Zero { }
-- >>> zeroPlus (S'(S'(S' Z')))
-- Z plus S(S(S(Z))) is S(S(S(Z))) by P-Zero { }
zeroPlus :: Nat' n -> Plus Z n n
zeroPlus = PZero
-- | 右単位元
--
-- >>> plusZero Z'
-- Z plus Z is Z by P-Zero { }
-- >>> plusZero (S'(S'(S' Z')))
-- S(S(S(Z))) plus Z is S(S(S(Z))) by P-Succ { S(S(Z)) plus Z is S(S(Z)) by P-Succ { S(Z) plus Z is S(Z) by P-Succ { Z plus Z is Z by P-Zero { } } } }
plusZero :: Nat' n -> Plus n Z n
plusZero Z' = PZero Z'
plusZero (S' n) = PSucc n Z' n (plusZero n)
unitZeroPlus :: Nat' n -> (Plus Z n n, Plus n Z n)
unitZeroPlus n = (zeroPlus n, plusZero n)
eqZeroPlus :: Nat' n -> Nat' n' -> Plus Z n n' -> n :=: n'
eqZeroPlus _ _ (PZero _) = Refl
eqPlusZero :: Nat' n -> Nat' n' -> Plus n Z n' -> n :=: n'
eqPlusZero Z' n' (PZero _) = eqZeroPlus Z' n' (PZero n')
eqPlusZero Z' _ p = case p of {}
eqPlusZero (S' n) _ (PSucc _ _ n' j) = eqCong (eqPlusZero n n' j)
eqPlusZero (S' _) _ p = case p of {}
-- 定理 2.2 加法唯一性
-- | 加法唯一性
--
-- >>> plusUnique Z' (S'(S' Z')) (S'(S' Z')) (add (S' Z') (S' Z')) (PZero (S'(S' Z'))) (PZero (add (S' Z') (S' Z')))
-- Refl
plusUnique :: Nat' n1 -> Nat' n2 -> Nat' n3 -> Nat' n4
-> Plus n1 n2 n3 -> Plus n1 n2 n4
-> n3 :=: n4
plusUnique n1 n2 n3 n4 j k = case n1 of
Z' -> eqTrans (eqSym (eqZeroPlus n2 n3 j)) (eqZeroPlus n2 n4 k)
S' n1' -> case n3 of
S' n3' -> case n4 of
S' n4' -> case j of
PSucc _ _ n3' j' -> case k of
PSucc _ _ n4' k' -> eqCong (plusUnique n1' n2 n3' n4' j' k')
pat -> case pat of {}
pat -> case pat of {}
pat -> case pat of {}
pat -> case pat of {}
addUnique :: Nat' n1 -> Nat' n2 -> Nat' n3 -> Plus n1 n2 n3 -> (n3 :=: (n1 :+ n2))
addUnique n1 n2 n3 p = case n1 of
Z' -> case p of
S' n1' -> case p of
PSucc n1' n2 n4 q -> case addUnique n1' n2 n4 q of
Refl -> plusUnique (S' n1') n2 n3 (S' n4) p p
pat -> case pat of {}
addUnique' :: Nat' n1 -> Nat' n2 -> Nat' n3 -> (n3 :=: (n1 :+ n2)) -> Plus n1 n2 n3
addUnique' n1 n2 n3 Refl = case n1 of
Z' -> PZero n2
S' n1' -> case n3 of
S' n3' -> PSucc n1' n2 n3' (addUnique' n1' n2 n3' Refl)
pat -> case pat of {}
-- 定理 2.3 加法閉包性
-- | 加法閉包性
--
-- >>> plusClosure Z' (S' Z')
-- ∃ x::S(Z) . Z plus S(Z) is S(Z) by P-Zero { }
plusClosure :: Nat' n1 -> Nat' n2 -> Exists Nat' (Plus n1 n2)
plusClosure Z' n2 = ExIntro n2 (PZero n2)
plusClosure (S' n1) n2 = case plusClosure n1 n2 of
ExIntro n3 p -> ExIntro (S' n3) (PSucc n1 n2 n3 p)
instance Show (Exists Nat' (Plus n1 n2)) where
show (ExIntro n3 p) = "∃ x::"++show n3++" . "++show p
-- 定理 2.4 加法可換律
plusComm :: Nat' n1 -> Nat' n2 -> Nat' n3 -> Plus n1 n2 n3 -> Plus n2 n1 n3
plusComm n1 n2 _ p = case n1 of
Z' -> case p of
PZero _ -> plusZero n2
pat -> case pat of {}
S' n1' -> case p of
PSucc _ _ n3' p' -> plusSucc n2 n1' n3' (plusComm n1' n2 n3' p')
pat -> case pat of {}
succPlus :: Nat' n1 -> Nat' n2 -> Nat' n3 -> Plus n1 n2 n3 -> Plus (S n1) n2 (S n3)
succPlus = PSucc
plusSucc :: Nat' n1 -> Nat' n2 -> Nat' n3 -> Plus n1 n2 n3 -> Plus n1 (S n2) (S n3)
plusSucc n1 n2 n3 p = case n1 of
Z' -> case p of
PZero _ -> PZero (S' n2)
pat -> case pat of {}
S' n1' -> case n3 of
S' n3' -> case p of
PSucc _ _ _ p' -> PSucc n1' (S' n2) n3 (plusSucc n1' n2 n3' p')
pat -> case pat of {}
pat -> case pat of {}
succPlusRev :: Nat' n1 -> Nat' n2 -> Nat' n3 -> Plus (S n1) n2 (S n3) -> Plus n1 n2 n3
succPlusRev _ _ _ p = case p of
PSucc _ _ _ q -> q
pat -> case pat of {}
plusSuccRev :: Nat' n1 -> Nat' n2 -> Nat' n3 -> Plus n1 (S n2) (S n3) -> Plus n1 n2 n3
plusSuccRev n1 n2 n3 p = plusComm n2 n1 n3 (succPlusRev n2 n1 n3 (plusComm n1 (S' n2) (S' n3) p))
uniqSucc :: Nat' n1 -> Nat' n2 -> (S n1 :+ n2) :=: (n1 :+ S n2)
uniqSucc n1 n2 = case plusClosure n1 n2 of
ExIntro n3 p -> case addUnique (S' n1) n2 (S' n3) (succPlus n1 n2 n3 p) of
Refl -> case addUnique n1 (S' n2) (S' n3) (plusSucc n1 n2 n3 p) of
Refl -> Refl
-- 定理 2.5 加法結合律
newtype PlusAssocR n1 n2 n3 n5 n6 = PlusAssocR (Plus n2 n3 n6,Plus n1 n6 n5)
plusAssocR :: Nat' n1 -> Nat' n2 -> Nat' n3 -> Nat' n4 -> Nat' n5
-> Plus n1 n2 n4 -> Plus n4 n3 n5
-> Exists Nat' (PlusAssocR n1 n2 n3 n5)
plusAssocR n1 n2 n3 _ n5 j k = case n1 of
Z' -> case j of
PZero _ -> case plusClosure n2 n3 of
ExIntro n6 j' -> case plusUnique n2 n3 n5 n6 k j' of
Refl -> ExIntro n6 (PlusAssocR (j',PZero n6))
pat -> case pat of {}
S' n1' -> case j of
PSucc _ _ n4 j' -> case k of
PSucc _ n3' n5' k' -> case plusAssocR n1' n2 n3' n4 n5' j' k' of
ExIntro n6 (PlusAssocR (j'',k'')) -> ExIntro n6 (PlusAssocR (j'',PSucc n1' n6 n5' k''))
pat -> case pat of {}
pat -> case pat of {}
newtype PlusAssocL n1 n2 n3 n5 n6 = PlusAssocL (Plus n1 n2 n6,Plus n6 n3 n5)
plusAssocL :: Nat' n1 -> Nat' n2 -> Nat' n3 -> Nat' n4 -> Nat' n5
-> Plus n2 n3 n4 -> Plus n1 n4 n5
-> Exists Nat' (PlusAssocL n1 n2 n3 n5)
plusAssocL n1 n2 n3 n4 n5 p1 p2 = case plusAssocR n3 n2 n1 n4 n5 (plusComm n2 n3 n4 p1) (plusComm n1 n4 n5 p2) of
ExIntro n6 (PlusAssocR (p5,p6)) -> ExIntro n6 (PlusAssocL (plusComm n2 n1 n6 p5, plusComm n3 n6 n5 p6))
-- 定理 2.6 乗法唯一性
-- | 乗法唯一性
-- >>> timesUnique one two two (mul one two) (TSucc Z' two Z' two (TZero two) (plusZero two)) (TSucc Z' two (mul Z' two) (mul one two) (TZero two) (plusZero two))
-- Refl
timesUnique :: Nat' n1 -> Nat' n2 -> Nat' n3 -> Nat' n4
-> Times n1 n2 n3 -> Times n1 n2 n4
-> n3 :=: n4
timesUnique n1 n2 n3 n4 j k = case n1 of
Z' -> case j of
TZero _ -> case k of
TZero _ -> Refl
pat -> case pat of {}
pat -> case pat of {}
S' n1' -> case j of
TSucc _ _ n _ j' j'' -> case k of
TSucc _ _ n' _ k' k'' -> case timesUnique n1' n2 n n' j' k' of
Refl -> plusUnique n2 n n3 n4 j'' k''
pat -> case pat of {}
pat -> case pat of {}
-- 定理 2.7 乗法閉包性
-- | 乗法の閉包性
timesClosure :: Nat' n1 -> Nat' n2 -> Exists Nat' (Times n1 n2)
timesClosure Z' n2 = ExIntro Z' (TZero n2)
timesClosure (S' n1) n2
= case timesClosure n1 n2 of
ExIntro n3 t -> case plusClosure n2 n3 of
ExIntro n4 p -> ExIntro n4 (TSucc n1 n2 n3 n4 t p)
-- 定理 2.8 乗法零元
-- | 左零元
leftZero :: Nat' n -> Times Z n Z
leftZero = TZero
-- | 右零元
rightZero :: Nat' n -> Times n Z Z
rightZero Z' = TZero Z'
rightZero (S' n) = TSucc n Z' Z' Z' (rightZero n) (PZero Z')
-- 定理 2.9 乗法交換律
-- | 乗法交換律
timesComm :: Nat' n1 -> Nat' n2 -> Nat' n3 -> Times n1 n2 n3 -> Times n2 n1 n3
timesComm n1 n2 n3 j = case n1 of
Z' -> case j of
TZero _ -> rightZero n2
pat -> case pat of {}
S' n1' -> case j of
TSucc _ _ n4 _ j' k' -> timesSucc n2 n1' n4 n3 (timesComm n1' n2 n4 j') k'
pat -> case pat of {}
succTimes :: Nat' n1 -> Nat' n2 -> Nat' n3 -> Nat' n4 -> Times n1 n2 n3 -> Plus n2 n3 n4 -> Times (S n1) n2 n4
succTimes = TSucc
timesSucc :: Nat' n1 -> Nat' n2 -> Nat' n3 -> Nat' n4 -> Times n1 n2 n3 -> Plus n1 n3 n4 -> Times n1 (S n2) n4
timesSucc n1 n2 n3 n4 t p = case n1 of
Z' -> case t of
TZero _ -> case p of
PZero _ -> TZero (S' n2)
pat -> case pat of {}
pat -> case pat of {}
S' n1' -> case n4 of
S' n4' -> case t of
TSucc _ _ n5 _ t1 p1 -> case p of
PSucc _ _ _ p2 -> case plusClosure n1' n5 of
ExIntro n6 p3 -> case plusAssocL n1' n2 n5 n3 n4' p1 p2 of
ExIntro n7 (PlusAssocL (p4,p5)) -> case plusAssocR n2 n1' n5 n7 n4' (plusComm n1' n2 n7 p4) p5 of
ExIntro n8 (PlusAssocR (p7,p8)) -> case plusUnique n1' n5 n6 n8 p3 p7 of
Refl -> TSucc n1' (S' n2) n6 n4 (timesSucc n1' n2 n5 n6 t1 p3) (PSucc n2 n6 n4' p8)
pat -> case pat of {}
pat -> case pat of {}
pat -> case pat of {}
-- 定理 2.10 乗法結合律
newtype TimesAssocR n1 n2 n3 n5 n6 = TimesAssocR (Times n2 n3 n6,Times n1 n6 n5)
timesAssocR :: Nat' n1 -> Nat' n2 -> Nat' n3 -> Nat' n4 -> Nat' n5
-> Times n1 n2 n4 -> Times n4 n3 n5
-> Exists Nat' (TimesAssocR n1 n2 n3 n5)
timesAssocR n1 n2 n3 n4 n5 t t1 = case n1 of
Z' -> case t of
TZero _ -> case t1 of
TZero _ -> case timesClosure n2 n3 of
ExIntro n6 t1 -> ExIntro n6 (TimesAssocR (t1,TZero n6))
pat -> case pat of {}
pat -> case pat of {}
S' n1' -> case t of
TSucc _ _ n6 _ t2 p2 -> case timesClosure n6 n3 of
ExIntro n7 t3 -> case timesAssocR n1' n2 n3 n6 n7 t2 t3 of
ExIntro n8 (TimesAssocR (t41,t42)) -> case timesDistribL n3 n2 n6 n4 n5 p2 (timesComm n4 n3 n5 t1) of
ExIntro2 (Both (n9,n10)) (DistribL (t51,t52,p5)) -> case timesUnique n2 n3 n8 n9 t41 (timesComm n3 n2 n9 t51) of
Refl -> case timesUnique n6 n3 n7 n10 t3 (timesComm n3 n6 n10 t52) of
Refl -> ExIntro n8 (TimesAssocR (t41,TSucc n1' n8 n7 n5 t42 p5))
pat -> case pat of {}
newtype TimesAssocL n1 n2 n3 n5 n6 = TimesAssocL (Times n1 n2 n6,Times n6 n3 n5)
timesAssocL :: Nat' n1 -> Nat' n2 -> Nat' n3 -> Nat' n4 -> Nat' n5
-> Times n2 n3 n4 -> Times n1 n4 n5
-> Exists Nat' (TimesAssocL n1 n2 n3 n5)
timesAssocL n1 n2 n3 n4 n5 t1 t2 = case timesAssocR n3 n2 n1 n4 n5 (timesComm n2 n3 n4 t1) (timesComm n1 n4 n5 t2) of
ExIntro n6 (TimesAssocR (t3,t4)) -> ExIntro n6 (TimesAssocL (timesComm n2 n1 n6 t3,timesComm n3 n6 n5 t4))
-- 左分配律
newtype Both m n = Both (Nat' m, Nat' n)
newtype DistribL n1 n2 n3 n4 n5 n6 = DistribL (Times n1 n2 n5, Times n1 n3 n6, Plus n5 n6 n4)
timesDistribL :: Nat' n1 -> Nat' n2 -> Nat' n3 -> Nat' n4 -> Nat' n5
-> Plus n2 n3 n4 -> Times n1 n4 n5
-> Exists2 Both (DistribL n1 n2 n3 n5)
timesDistribL n1 n2 n3 n4 n5 p0 t0 = case n1 of
Z' -> case t0 of
TZero _ -> ExIntro2 (Both (Z',Z')) (DistribL (TZero n2, TZero n3, PZero Z'))
pat -> case pat of {}
S' n1' -> case t0 of
TSucc _ _ n6 _ t1 p1 -> case timesDistribL n1' n2 n3 n4 n6 p0 t1 of
ExIntro2 (Both (n7,n8)) (DistribL (t21,t22,p2)) -> case plusAssocL n4 n7 n8 n6 n5 p2 p1 of
ExIntro n9 (PlusAssocL (p31,p32)) -> case plusAssocR n3 n2 n7 n4 n9 (plusComm n2 n3 n4 p0) p31 of
ExIntro n10 (PlusAssocR (p41,p42)) -> case plusAssocR n10 n3 n8 n9 n5 (plusComm n3 n10 n9 p42) p32 of
ExIntro n11 (PlusAssocR (p51,p52))
-> ExIntro2 (Both (n10,n11)) (DistribL (TSucc n1' n2 n7 n10 t21 p41,TSucc n1' n3 n8 n11 t22 p51,p52))
pat -> case pat of {}
| nobsun/hs-bcopl | src/Language/BCoPL/TypeLevel/MetaTheory/Nat.hs | bsd-3-clause | 11,644 | 0 | 31 | 3,374 | 4,998 | 2,500 | 2,498 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Data.FAlgebra.Tree.Splay
( module Data.FAlgebra.Annotation
, module Data.FAlgebra.Base
, module Data.FAlgebra.Tree
, module Data.FAlgebra.Tree.Indexed
, module Data.FAlgebra.Tree.Zipper
, getIndex
, setIndex
, splayStep
, splay
, isolateInterval
, insertAt
) where
import Prelude hiding (zip)
import Data.FAlgebra.Annotation
import Data.FAlgebra.Base
import Data.FAlgebra.Tree
import Data.FAlgebra.Tree.Indexed
import Data.FAlgebra.Tree.Zipper
-- |Do one step of splaying the current node to the root. The resulting zipper is
-- focused on the same node at its new location.
splayStep :: (FAlgebra (TreeF a) t, FCoalgebra (TreeF a) t) => TreeZip a t -> TreeZip a t
splayStep z = case directions z of
[] -> z
(L:[]) -> rotate z
(R:[]) -> rotate z
(L:L:_) -> rotate . left . rotate . up $ z
(L:R:_) -> rotate . rotate $ z
(R:L:_) -> rotate . rotate $ z
(R:R:_) -> rotate . right . rotate . up $ z
-- |Splay a node all the way to the root. The resulting zipper is focused on the new root.
splay :: forall a t. (FAlgebra (TreeF a) t, FCoalgebra (TreeF a) t) => TreeZip a t -> TreeZip a t
splay z = if isRoot z
then z
else splay (splayStep z)
where
isRoot (TreeZip _ p) = case (coalg p :: TreeZipStepF a t (TreeZipSteps a t)) of
Root -> True
_ -> False
-- TODO: Decide how to split indexed splays from BST splays
-- Data.FAlgebra.Tree.Splay.(Indexed|BST)?
getIndex :: forall a t. (FAlgebra (TreeF a) t, FCoalgebra (TreeF a) t, Annotated Size t) => Int -> t -> (Maybe a, t)
getIndex i t =
let z = idx i t
v = value z
in
(v, zip . splay $ z)
setIndex :: forall a t. (FAlgebra (TreeF a) t, FCoalgebra (TreeF a) t, Annotated Size t, Show a, Show t) => Int -> a -> t -> t
setIndex i v t =
let z = idx i t
z' = setValue v z
in
zip . splay $ z'
-- |Isolate the interval [l, r) in a rooted subtree and return a zipper for that subtree
isolateInterval :: forall a t. (FAlgebra (TreeF a) t, FCoalgebra (TreeF a) t, Annotated Size t) => Int -> Int -> t -> TreeZip a t
isolateInterval l r t = if l >= r
then idxSlot l t
else let s = getSize t in
case (l <= 0, Size r >= s) of
(True, True ) -> root t
(True, False) -> isolatePrefix r t
(False, True ) -> isolateSuffix l t
(False, False) -> isolateGeneral l r t
where
isolatePrefix :: Int -> t -> TreeZip a t
isolatePrefix r = left . splay . idx r
isolateSuffix :: Int -> t -> TreeZip a t
isolateSuffix l = right . splay . idx (l-1)
isolateGeneral :: Int -> Int -> t -> TreeZip a t
isolateGeneral l r =
finalizeInterval . (idx (l-1) :: t -> TreeZip a t)
. zip . splay . (idx r :: t -> TreeZip a t)
. zip . splay . (idx (l-1) :: t -> TreeZip a t)
. zip . splay . (idx l :: t -> TreeZip a t)
finalizeInterval z@(TreeZip t p) = let TreeZip t' _ = right z in
case (coalg t' :: TreeF a t) of
Empty -> right . rotate $ z
_ -> right z
-- |Insert the specified element so that it is at the specified index
-- i.e. Inserting at index 0 moves every element one index up.
insertAt :: (FAlgebra (TreeF a) t, FCoalgebra (TreeF a) t, Annotated Size t) => Int -> a -> t -> t
insertAt i x = zip . splay . insertHere x . idxSlot i
| bhamrick/fixalgs | Data/FAlgebra/Tree/Splay.hs | bsd-3-clause | 3,449 | 0 | 20 | 950 | 1,322 | 695 | 627 | 71 | 7 |
main = return $ 1 + 2
-- putStrLn "Hello, world!"
a1 x = let y = 1
in x + y | benjijones/red | test/test_main.hs | bsd-3-clause | 86 | 0 | 8 | 32 | 38 | 19 | 19 | 3 | 1 |
{-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-}
-- The Timber compiler <timber-lang.org>
--
-- Copyright 2008-2009 Johan Nordlander <[email protected]>
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
--
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
--
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
--
-- 3. Neither the names of the copyright holder and any identified
-- contributors, nor the names of their affiliations, may be used to
-- endorse or promote products derived from this software without
-- specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR
-- ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
-- STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
-- ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- POSSIBILITY OF SUCH DAMAGE.
module PP (module PP, module Text.PrettyPrint) where
import Text.PrettyPrint hiding (TextDetails(..))
import Char(showLitChar)
class Pr a where
pr :: a -> Doc
pr x = prn 0 x
prn :: Int -> a -> Doc
prn n x = pr x
vpr :: [a] -> Doc
vpr xs = vcat (map pr xs)
hpr :: Char -> [a] -> Doc
hpr c xs = sep (punctuate (char c) (map pr xs))
dump :: a -> IO ()
dump x = putStr (render (pr x))
instance Pr Int where
pr = int
-- XXX Is this correct?
-- AJG It is needed by Main, but it looks wrong.
instance Pr (String, String) where
pr (a, b) = text a <> text b
-- used by llvm backend
instance Pr String where
pr a = text a
infixl 4 $$$
a $$$ b = a $$ text " " $$ b
vcat2 xs = vcat (map ($$ text " ") xs)
backQuotes p = char '`' <> p <> char '`'
litChar = charQuotes . text . lit
litString = doubleQuotes . text . concat . map lit
lit c = showLitChar c ""
charQuotes p = char '\'' <> p <> char '\''
curlies = braces
commasep f xs = sep (punctuate comma (map f xs))
show' :: Pr a => a -> String
show' = render . pr
vshow :: Pr a => [a] -> String
vshow = render . vpr
showlist :: Pr a => [a] -> String
showlist xs = render (text "(" <> hpr ',' xs <> text ")")
| mattias-lundell/timber-llvm | src/PP.hs | bsd-3-clause | 2,994 | 0 | 11 | 671 | 603 | 325 | 278 | 37 | 1 |
-- -----------------------------------------------------------------------------
--
-- ParseMonad.hs, part of Alex
--
-- (c) Simon Marlow 2003
--
-- ----------------------------------------------------------------------------}
module ParseMonad (
AlexInput, alexInputPrevChar, alexGetChar, alexGetByte,
AlexPosn(..), alexStartPos,
Warning(..), warnIfNullable,
P, runP, StartCode, failP, lookupSMac, lookupRMac, newSMac, newRMac,
setStartCode, getStartCode, getInput, setInput,
) where
import AbsSyn hiding ( StartCode )
import CharSet ( CharSet )
import Map ( Map )
import qualified Map hiding ( Map )
import UTF8
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative ( Applicative(..) )
#endif
import Control.Monad ( liftM, ap, when )
import Data.Word (Word8)
-- -----------------------------------------------------------------------------
-- The input type
--import Codec.Binary.UTF8.Light as UTF8
type Byte = Word8
type AlexInput = (AlexPosn, -- current position,
Char, -- previous char
[Byte],
String) -- current input string
alexInputPrevChar :: AlexInput -> Char
alexInputPrevChar (_,c,_,_) = c
alexGetChar :: AlexInput -> Maybe (Char,AlexInput)
alexGetChar (_,_,[],[]) = Nothing
alexGetChar (p,_,[],(c:s)) = let p' = alexMove p c in p' `seq`
Just (c, (p', c, [], s))
alexGetChar (_, _ ,_ : _, _) = undefined -- hide compiler warning
alexGetByte :: AlexInput -> Maybe (Byte,AlexInput)
alexGetByte (p,c,(b:bs),s) = Just (b,(p,c,bs,s))
alexGetByte (_,_,[],[]) = Nothing
alexGetByte (p,_,[],(c:s)) = let p' = alexMove p c
(b:bs) = UTF8.encode c
in p' `seq` Just (b, (p', c, bs, s))
-- -----------------------------------------------------------------------------
-- Token positions
-- `Posn' records the location of a token in the input text. It has three
-- fields: the address (number of charaters preceding the token), line number
-- and column of a token within the file. `start_pos' gives the position of the
-- start of the file and `eof_pos' a standard encoding for the end of file.
-- `move_pos' calculates the new position after traversing a given character,
-- assuming the usual eight character tab stops.
data AlexPosn = AlexPn !Int !Int !Int
deriving (Eq,Show)
alexStartPos :: AlexPosn
alexStartPos = AlexPn 0 1 1
alexMove :: AlexPosn -> Char -> AlexPosn
alexMove (AlexPn a l c) '\t' = AlexPn (a+1) l (((c+7) `div` 8)*8+1)
alexMove (AlexPn a l _) '\n' = AlexPn (a+1) (l+1) 1
alexMove (AlexPn a l c) _ = AlexPn (a+1) l (c+1)
-- -----------------------------------------------------------------------------
-- Alex lexing/parsing monad
data Warning
= WarnNullableRExp
{ _warnPos :: AlexPosn -- ^ The position of the code following the regex.
, _warnText :: String -- ^ Warning text.
}
type ParseError = (Maybe AlexPosn, String)
type StartCode = Int
data PState = PState
{ warnings :: [Warning] -- ^ Stack of warnings, top = last warning.
, smac_env :: Map String CharSet
, rmac_env :: Map String RExp
, startcode :: Int
, input :: AlexInput
}
newtype P a = P { unP :: PState -> Either ParseError (PState,a) }
instance Functor P where
fmap = liftM
instance Applicative P where
pure a = P $ \env -> Right (env,a)
(<*>) = ap
instance Monad P where
(P m) >>= k = P $ \env -> case m env of
Left err -> Left err
Right (env',ok) -> unP (k ok) env'
return = pure
-- | Run the parser on given input.
runP :: String
-- ^ Input string.
-> (Map String CharSet, Map String RExp)
-- ^ Character set and regex definitions.
-> P a
-- ^ Parsing computation.
-> Either ParseError ([Warning], a)
-- ^ List of warnings in first-to-last order, result.
runP str (senv,renv) (P p)
= case p initial_state of
Left err -> Left err
Right (s, a) -> Right (reverse (warnings s), a)
where
initial_state = PState
{ warnings = []
, smac_env = senv
, rmac_env = renv
, startcode = 0
, input = (alexStartPos, '\n', [], str)
}
failP :: String -> P a
failP str = P $ \PState{ input = (p,_,_,_) } -> Left (Just p,str)
-- Macros are expanded during parsing, to simplify the abstract
-- syntax. The parsing monad passes around two environments mapping
-- macro names to sets and regexps respectively.
lookupSMac :: (AlexPosn,String) -> P CharSet
lookupSMac (posn,smac)
= P $ \s@PState{ smac_env = senv } ->
case Map.lookup smac senv of
Just ok -> Right (s,ok)
Nothing -> Left (Just posn, "unknown set macro: $" ++ smac)
lookupRMac :: String -> P RExp
lookupRMac rmac
= P $ \s@PState{ rmac_env = renv } ->
case Map.lookup rmac renv of
Just ok -> Right (s,ok)
Nothing -> Left (Nothing, "unknown regex macro: %" ++ rmac)
newSMac :: String -> CharSet -> P ()
newSMac smac set
= P $ \s -> Right (s{smac_env = Map.insert smac set (smac_env s)}, ())
newRMac :: String -> RExp -> P ()
newRMac rmac rexp
= P $ \s -> Right (s{rmac_env = Map.insert rmac rexp (rmac_env s)}, ())
setStartCode :: StartCode -> P ()
setStartCode sc = P $ \s -> Right (s{ startcode = sc }, ())
getStartCode :: P StartCode
getStartCode = P $ \s -> Right (s, startcode s)
getInput :: P AlexInput
getInput = P $ \s -> Right (s, input s)
setInput :: AlexInput -> P ()
setInput inp = P $ \s -> Right (s{ input = inp }, ())
-- | Add a warning if given regular expression is nullable
-- unless the user wrote the regex 'Eps'.
warnIfNullable
:: RExp -- ^ Regular expression.
-> AlexPosn -- ^ Position associated to regular expression.
-> P ()
-- If the user wrote @()@, they wanted to match the empty sequence!
-- Thus, skip the warning then.
warnIfNullable Eps _ = return ()
warnIfNullable r pos = when (nullable r) $ P $ \ s ->
Right (s{ warnings = WarnNullableRExp pos w : warnings s}, ())
where
w = unwords
[ "Regular expression"
, show r
, "matches the empty string."
]
| simonmar/alex | src/ParseMonad.hs | bsd-3-clause | 6,194 | 0 | 13 | 1,523 | 1,897 | 1,070 | 827 | 122 | 2 |
{-# LANGUAGE DeriveDataTypeable,
RecordWildCards #-}
module Graphics.ThumbnailPlus
( createThumbnails
, Configuration(..)
, Size(..)
, ReencodeOriginal(..)
, FileFormat(..)
, CreatedThumbnails(..)
, Thumbnail(..)
, NoShow(..)
) where
import Control.Arrow ((***))
import Control.Monad (unless)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Either (runEitherT, left, right)
import Data.Default (Default(..))
import Data.Maybe (fromMaybe)
import qualified Control.Exception as E
import qualified Control.Monad.Trans.Resource as R
import qualified Data.Conduit as C
import qualified Data.Conduit.Binary as CB
import qualified Data.Typeable as T
import qualified Graphics.GD as GD
import qualified System.Directory as D
import qualified System.IO as IO
import qualified System.IO.Temp as T
import Graphics.ThumbnailPlus.ImageSize
-- | Configuration used when
data Configuration =
Configuration
{ maxFileSize :: !Integer
-- ^ Maximum file size in bytes. Files larger than this
-- limit are rejected. Default: 5 MiB.
, maxImageSize :: !Size
-- ^ Maximum image size in pixels. Images which exceed this
-- limit in any dimension are rejected. Default: 3000x3000px.
, reencodeOriginal :: !ReencodeOriginal
-- ^ Whether the original image should be reencoded.
-- Default: 'SameFileFormat'.
, thumbnailSizes :: [(Size, Maybe FileFormat)]
-- ^ The sizes of the thumbnails that should be created.
-- Thumbnails preserve the aspect ratio and have at least
-- one dimension equal to the given requested size. Sizes
-- larger than the original image will be disregarded. If a
-- 'FileFormat' is not provided, the same file format as
-- the original image is reused. Default: 512x512, 64x64.
, temporaryDirectory :: IO FilePath
-- ^ Temporary directory where files should be
-- saved. Default: 'D.getTemporaryDirectory'.
} deriving (T.Typeable)
instance Default Configuration where
def = Configuration
{ maxFileSize = 2 * 1024 * 1024
, maxImageSize = Size 4096 4096
, reencodeOriginal = SameFileFormat
, thumbnailSizes = [(Size 512 512, Nothing), (Size 64 64, Nothing)]
, temporaryDirectory = D.getTemporaryDirectory
}
-- | Whether the original image should be reencoded or not (cf.,
-- 'reencodeOriginal').
data ReencodeOriginal =
Never
-- ^ Do not reencode the original image.
| SameFileFormat
-- ^ Reencode the original using the same file format.
| NewFileFormat !FileFormat
-- ^ Reencode the original using the given file format.
deriving (Eq, Ord, Show, T.Typeable)
-- | cf. 'thumbnailSizes'.
calculateThumbnailSize
:: Size -- ^ Original size.
-> Size -- ^ Thumbnail max size.
-> Size -- ^ Calculated thumbnail size.
calculateThumbnailSize (Size ow oh) (Size tw th) =
let -- Assuming final height is th.
wByH = ow * th `div` oh
-- Assuming final width is tw.
hByW = oh * tw `div` ow
in if wByH > tw
then Size tw hByW
else Size wByH th
-- | Process an image and generate thumbnails for it according to
-- the given 'Configuration'.
createThumbnails
:: R.MonadResource m
=> Configuration -- ^ Configuration values (use 'def' for default values).
-> FilePath -- ^ Input image file path.
-> m CreatedThumbnails
createThumbnails conf inputFp = do
checkRet <- liftIO (checkInput conf inputFp)
case checkRet of
Left ret -> return ret
Right (size, ff) -> doCreateThumbnails conf (inputFp, size, ff)
checkInput :: Configuration -> FilePath -> IO (Either CreatedThumbnails (Size, FileFormat))
checkInput Configuration {..} inputFp =
-- No resources from the input check are needed to create the
-- thumbnails, use an inner ResourceT.
R.runResourceT $ runEitherT $ do
(_, inputH) <- lift $ R.allocate (IO.openFile inputFp IO.ReadMode) IO.hClose
fileSize <- liftIO $ IO.hFileSize inputH
unless (fileSize <= maxFileSize) $ left (FileSizeTooLarge fileSize)
minfo <- CB.sourceHandle inputH C.$$ sinkImageInfo
info@(imageSize, _) <- maybe (left ImageFormatUnrecognized) right minfo
unless (imageSize `fits` maxImageSize) $ left (ImageSizeTooLarge imageSize)
return info
fits :: Size -> Size -> Bool
Size aw ah `fits` Size bw bh = aw <= bw && ah <= bh
doCreateThumbnails
:: R.MonadResource m
=> Configuration
-> (FilePath, Size, FileFormat)
-> m CreatedThumbnails
doCreateThumbnails Configuration {..} (inputFp, inputSize, inputFf) = do
parentDir <- liftIO temporaryDirectory
(relTmpDir, tmpDir) <-
R.allocate
(T.createTempDirectory parentDir "thumbnail-plus-")
(ignoringIOErrors . D.removeDirectoryRecursive)
(relImg, img) <-
R.allocate
(($ inputFp) $ case inputFf of
GIF -> GD.loadGifFile
JPG -> GD.loadJpegFile
PNG -> GD.loadPngFile)
gdFreeImage
imgSize <- liftIO $ do
GD.alphaBlending True img
GD.imageSize img
case (imgSize, inputSize) of
((w1,h1), Size w2 h2) | w1 /= w2 || h1 /= h2 ->
-- Sanity check
return ImageFormatUnrecognized
_ -> do
let finalThumbSizes =
(case reencodeOriginal of
Never -> id
SameFileFormat -> (:) (inputSize, inputFf)
NewFileFormat ff -> (:) (inputSize, ff)) $
map (calculateThumbnailSize inputSize *** fromMaybe inputFf) $
filter (not . (inputSize `fits`) . fst) $
thumbnailSizes
thumbnails <- mapM (createThumbnail tmpDir (img, imgSize)) finalThumbSizes
R.release relImg
return (CreatedThumbnails thumbnails (NoShow relTmpDir))
createThumbnail
:: R.MonadResource m
=> FilePath
-> (GD.Image, GD.Size)
-> (Size, FileFormat)
-> m Thumbnail
createThumbnail tmpDir (inputImg, inputImgSize) (size@(Size w h), ff) = do
let template = "thumb-" ++ show w ++ "x" ++ show h ++ "-"
(relTmpFile, (tmpFp, tmpHandle)) <-
R.allocate
(T.openBinaryTempFile tmpDir template)
(\(tmpFile, tmpHandle) ->
ignoringIOErrors $ do
IO.hClose tmpHandle
D.removeFile tmpFile)
liftIO $ do
-- The @gd@ library does not support 'Handle's :'(, close it as
-- early as possible. We don't close it above on the
-- 'R.allocate' because of async exceptions, but it doesn't
-- matter since hClose-ing twice is harmless.
IO.hClose tmpHandle
GD.withImage (GD.newImage (w, h)) $ \resizedImg -> do
GD.alphaBlending False resizedImg
GD.saveAlpha True resizedImg
GD.copyRegionScaled (0, 0) inputImgSize inputImg
(0, 0) (w, h) resizedImg
(\f -> f tmpFp resizedImg) $
case ff of
GIF -> GD.saveGifFile
JPG -> GD.saveJpegFile (-1) -- TODO: Configurable JPEG quality.
PNG -> GD.savePngFile
return Thumbnail { thumbFp = tmpFp
, thumbSize = size
, thumbFormat = ff
, thumbReleaseKey = NoShow relTmpFile
}
-- | For some reason, the @gd@ library does not export
-- 'GD.freeImage'. Argh!
gdFreeImage :: GD.Image -> IO ()
gdFreeImage img = GD.withImage (return img) (const $ return ())
-- | Shamelessly copied and adapted from @temporary@ package.
ignoringIOErrors :: IO () -> IO ()
ignoringIOErrors ioe = ioe `E.catch` (\e -> const (return ()) (e :: IOError))
-- | Return value of 'createThumbnails'.
data CreatedThumbnails =
FileSizeTooLarge !Integer
-- ^ File size exceeded 'maxFileSize'.
| ImageSizeTooLarge !Size
-- ^ Image size exceeded 'maxImageSize'.
| ImageFormatUnrecognized
-- ^ Could not parse size information for the image.
-- Remember that we understand JPGs, PNGs and GIFs only.
| CreatedThumbnails ![Thumbnail] !(NoShow R.ReleaseKey)
-- ^ Thumbnails were created successfully. If
-- 'reencodeOriginal' was not 'Never', then the first item of
-- the list is going to be the reencoded image.
deriving (Eq, Show, T.Typeable)
-- | Information about a generated thumbnail. Note that if ask
-- for the original image to be reencoded, then the first
-- 'Thumbnail' will actually have the size of the original image.
data Thumbnail =
Thumbnail
{ thumbFp :: !FilePath
-- ^ The 'FilePath' where this thumbnail is stored.
, thumbSize :: !Size
-- ^ Size of the thumbnail.
, thumbFormat :: !FileFormat
, thumbReleaseKey :: !(NoShow R.ReleaseKey)
-- ^ Release key that may be used to clean up any resources
-- used by this thumbnail as soon as possible (i.e., before
-- 'R.runResourceT' finishes).
} deriving (Eq, Show, T.Typeable)
-- | Hack to allow me to derive 'Show' for data types with fields
-- that don't have 'Show' instances.
newtype NoShow a = NoShow a
instance T.Typeable a => Show (NoShow a) where
showsPrec _ ~(NoShow a) =
('<':) . T.showsTypeRep (T.typeOf a) . ('>':)
instance Eq (NoShow a) where
_ == _ = True
| prowdsponsor/thumbnail-plus | src/Graphics/ThumbnailPlus.hs | bsd-3-clause | 9,183 | 0 | 23 | 2,254 | 2,074 | 1,141 | 933 | 195 | 6 |
import qualified Data.List as List
import Data.Function (on)
import Data.Char as Char
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Geometry.Sphere as Sphere
import qualified Geometry.Cuboid as Cuboid
import qualified Geometry.Cube as Cube
intersperseMonkey = List.intersperse '.' "MONKEY"
concatFlatten = List.concat [[3,4,5],[2,3,4],[2,1,1]]
flatmap = List.concatMap (replicate 4) [1..3]
values = [-4.3, -2.4, -1.2, 0.4, 2.3, 5.9, 10.5, 29.1, 5.3, -2.4, -14.5, 2.9, 2.3]
groupBy1 = List.groupBy (\x y -> (x > 0) == (y > 0)) values
groupBy2 = List.groupBy ((==) `on` (> 0)) values
values1 = [[5,4,5,4,4],[1,2,3],[3,5,4,3],[],[2],[2,2]]
sortByEx = List.sortBy (compare `on` length) values1
digitToInt1 = map Char.digitToInt "FF85AB"
ordA = Char.ord 'a'
chr1 = Char.chr 97
encode :: Int -> String -> String
encode shift msg =
let ords = map ord msg
shifted = map (+ shift) ords
in map Char.chr shifted
decode :: Int -> String -> String
decode shift msg = encode (negate shift) msg
encodeDecode = decode 5 . encode 5 $ "This is a sentence"
phoneBook = Map.fromList [("betty","555-2938"),("bonnie","452-2928"),("lucille","205-2928")]
phoneAdd = Map.insert "foo" "phone" phoneBook
-- phoneGet = Map.lookup "foo"
text1 = "I just had an anime dream. Anime... Reality... Are they so different?"
text2 = "The old man left his garbage can out and now his trash is all over my lawn!"
set1 = Set.fromList text1
set2 = Set.fromList text2
sphereVol = Sphere.volume 4.3 | randallalexander/LYAH | src/Ch7.hs | bsd-3-clause | 1,537 | 0 | 10 | 270 | 596 | 349 | 247 | 34 | 1 |
module Options.Verbosity where
import Types
verbosityOptions :: [Flag]
verbosityOptions =
[ flag { flagName = "-v"
, flagDescription = "verbose mode (equivalent to ``-v3``)"
, flagType = DynamicFlag
}
, flag { flagName = "-v⟨n⟩"
, flagDescription = "set verbosity level"
, flagType = DynamicFlag
, flagReverse = ""
}
, flag { flagName = "-fprint-potential-instances"
, flagDescription =
"display all available instances in type error messages"
, flagType = DynamicFlag
, flagReverse = "-fno-print-potential-instances"
}
, flag { flagName = "-fprint-explicit-foralls"
, flagDescription =
"Print explicit ``forall`` quantification in types. " ++
"See also ``-XExplicitForAll``"
, flagType = DynamicFlag
, flagReverse = "-fno-print-explicit-foralls"
}
, flag { flagName = "-fprint-explicit-kinds"
, flagDescription =
"Print explicit kind foralls and kind arguments in types. " ++
"See also ``-XKindSignature``"
, flagType = DynamicFlag
, flagReverse = "-fno-print-explicit-kinds"
}
, flag { flagName = "-fprint-unicode-syntax"
, flagDescription =
"Use unicode syntax when printing expressions, types and kinds. " ++
"See also ``-XUnicodeSyntax``"
, flagType = DynamicFlag
, flagReverse = "-fno-print-unicode-syntax"
}
, flag { flagName = "-fprint-expanded-synonyms"
, flagDescription =
"In type errors, also print type-synonym-expanded types."
, flagType = DynamicFlag
, flagReverse = "-fno-print-expanded-synonyms"
}
, flag { flagName = "-fprint-typechecker-elaboration"
, flagDescription =
"Print extra information from typechecker."
, flagType = DynamicFlag
, flagReverse = "-fno-print-typechecker-elaboration"
}
, flag { flagName = "-ferror-spans"
, flagDescription = "Output full span in error messages"
, flagType = DynamicFlag
}
, flag { flagName = "-Rghc-timing"
, flagDescription =
"Summarise timing stats for GHC (same as ``+RTS -tstderr``)."
, flagType = DynamicFlag
}
]
| gridaphobe/ghc | utils/mkUserGuidePart/Options/Verbosity.hs | bsd-3-clause | 2,350 | 0 | 8 | 728 | 306 | 198 | 108 | 51 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveGeneric #-}
module Forml.Types.TypeDefinition where
import Control.Applicative
import qualified Data.List as L
import Text.Parsec hiding (State, label, many, parse, spaces,
(<|>))
import GHC.Generics
import Data.Serialize
import Forml.Parser.Utils
data TypeDefinition = TypeDefinition String [String] deriving (Generic)
instance Serialize TypeDefinition
instance Show TypeDefinition where
show (TypeDefinition name vars) = concat . L.intersperse " " $ name : vars
instance Syntax TypeDefinition where
syntax = do name <- (:) <$> upper <*> many alphaNum
vars <- try vars' <|> return []
return $ TypeDefinition name vars
where vars' = do many1 $ oneOf "\t "
let var = (:) <$> lower <*> many alphaNum
var `sepEndBy` whitespace
| texodus/forml | src/hs/lib/Forml/Types/TypeDefinition.hs | bsd-3-clause | 1,216 | 0 | 14 | 380 | 253 | 140 | 113 | 27 | 0 |
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, TypeFamilies, TypeSynonymInstances, FlexibleInstances #-}
module Web.Scotty.CRUD.Types (
CRUD(..),
Id, Table, Row, Named(..),
namedRowToRow, rowToNamedRow, lookupColumn
) where
import Control.Applicative
import Data.Aeson
import Data.HashMap.Strict (HashMap)
import Data.Text(Text)
import qualified Data.HashMap.Strict as HashMap
------------------------------------------------------------------------------------
-- | A CRUD is a OO-style database Table of typed rows, with getters and setters.
-- The default row is a JSON Object.
data CRUD row = CRUD
{ createRow :: row -> IO (Named row)
, getRow :: Id -> IO (Maybe (Named row))
, getTable :: IO (Table row)
, updateRow :: Named row -> IO ()
, deleteRow :: Id -> IO () -- alway works
}
------------------------------------------------------------------------------------
-- Basic synonyms for key structures
--
-- | Every (Named) Row must have an id field.
type Id = Text
-- | a Table is a HashMap of Ids to rows, typically 'Table Row'.
-- The elems of the Table do not contain, by default, the Id, because this
-- is how you index a row. Note that the output of a complete table,
-- via RESTful CRUD, injects the Id into the row.
type Table row = HashMap Id row
-- | The default row is a aeson JSON object.
type Row = Object
------------------------------------------------------------------------------------
-- | A pair of Name(Id) and row.
data Named row = Named Id row
deriving (Eq,Show)
instance FromJSON row => FromJSON (Named row) where
parseJSON (Object v) = Named
<$> v .: "id"
<*> (parseJSON $ Object $ HashMap.delete "id" v)
parseJSON _ = fail "row should be an object"
instance ToJSON row => ToJSON (Named row) where
toJSON = Object . namedRowToRow
namedRowToRow :: (ToJSON row) => Named row -> Row
namedRowToRow (Named key row) = case toJSON row of
Object env -> HashMap.insert "id" (String key) env
_ -> error "row should be an object"
rowToNamedRow :: FromJSON row => Row -> Named row
rowToNamedRow row = case fromJSON (Object row) of
Error msg -> error $ msg
Success a -> a
lookupColumn ::ToJSON row => Text -> row -> Maybe Value
lookupColumn nm row = case toJSON row of
Object env -> HashMap.lookup nm env
_ -> error "row should be an object"
| ku-fpg/scotty-crud | src/Web/Scotty/CRUD/Types.hs | bsd-3-clause | 2,514 | 0 | 14 | 608 | 557 | 301 | 256 | 40 | 2 |
module Sloch.Dirent
( SlochDirent(..)
, slochDirent
, slochDirents
) where
import Data.Maybe (catMaybes)
import Language
import Dirent
import LineCounter
data SlochDirent = SlochDirentFile FilePath Language Int
| SlochDirentDir FilePath [SlochDirent]
deriving Show
-- | Transform an ordinary Dirent into a SlochDirent, which is essentially the
-- same dirent, but annotated with line count information. Returns Nothing if
-- no lines could be counted, i.e. the file has an unknown file extension.
-- Directories work as expected, recursively.
slochDirent :: Dirent -> IO (Maybe SlochDirent)
slochDirent (DirentFile path) =
case language path of
Nothing -> return Nothing
Just lang -> countLines path lang >>= return . Just . SlochDirentFile path lang
slochDirent (DirentDir path children) =
fmap catMaybes (mapM slochDirent children) >>= return . Just . SlochDirentDir path
slochDirents :: [Dirent] -> IO [SlochDirent]
slochDirents = fmap catMaybes . mapM slochDirent
| mitchellwrosen/Sloch | src/sloch/Sloch/Dirent.hs | bsd-3-clause | 1,050 | 0 | 11 | 222 | 226 | 120 | 106 | 20 | 2 |
{-# LANGUAGE DataKinds,UnboxedTuples,MagicHash,TemplateHaskell,RankNTypes,TupleSections #-}
module HLearn.Data.SpaceTree.Algorithms.NearestNeighbor
(
-- * data types
Neighbor (..)
, ValidNeighbor (..)
, NeighborList (..)
, nlSingleton
, getknnL
, nlMaxDist
, Param_k
, _k
-- * functions
, findAllNeighbors
, findAllNeighbors'
, findNeighborList
, findEpsilonNeighborListWith
)
where
import qualified Prelude as P
import Data.Strict.Tuple (Pair(..))
import SubHask
import SubHask.Algebra.Container
import SubHask.Compatibility.Containers
import SubHask.Compatibility.Vector
import SubHask.Compatibility.Vector.Lebesgue
import SubHask.Monad
import SubHask.TemplateHaskell.Deriving
import HLearn.Data.SpaceTree
import Data.Params
-------------------------------------------------------------------------------
data Neighbor dp = Neighbor
{ neighbor :: !dp
, neighborDistance :: !(Scalar dp)
-- { neighbor :: {-#UNPACK#-}!(L2 UnboxedVector Float)
-- , neighborDistance :: {-#UNPACK#-}!Float
}
type instance Scalar (Neighbor dp) = Bool
type instance Logic (Neighbor dp) = Bool
type ValidNeighbor dp =
( Metric dp
, Bounded (Scalar dp)
, CanError (Scalar dp)
, Logic dp~Bool
-- , dp ~ (L2 UnboxedVector Float)
)
deriving instance (Read dp, Read (Scalar dp)) => Read (Neighbor dp)
deriving instance (Show dp, Show (Scalar dp)) => Show (Neighbor dp)
instance Eq (Scalar dp) => Eq_ (Neighbor dp) where
{-# INLINE (==) #-}
a == b = neighborDistance a == neighborDistance b
-- instance Ord (Scalar dp) => Ord (Neighbor dp) where
-- compare a b = compare (neighborDistance a) (neighborDistance b)
instance (NFData dp, NFData (Scalar dp)) => NFData (Neighbor dp) where
rnf (Neighbor _ _) = ()
-- rnf n = deepseq (neighbor n) $ rnf (neighborDistance n)
------------------------------------------------------------------------------
data NeighborList (k :: Config Nat) dp
= NL_Nil
| NL_Cons {-#UNPACK#-}!(Neighbor dp) !(NeighborList k dp)
-- | NL_Err
mkParams ''NeighborList
-- | update the distances in the NeighborList based on a new data point
resetNL :: ValidNeighbor dp => dp -> NeighborList k dp -> NeighborList k dp
resetNL p NL_Nil = NL_Nil
resetNL p (NL_Cons (Neighbor q _) nl)
= NL_Cons (Neighbor q $ distance p q) $ resetNL p nl
type instance Logic (NeighborList k dp) = Bool
deriving instance (Read dp, Read (Scalar dp)) => Read (NeighborList k dp)
deriving instance (Show dp, Show (Scalar dp)) => Show (NeighborList k dp)
instance (NFData dp, NFData (Scalar dp)) => NFData (NeighborList k dp) where
rnf NL_Nil = ()
-- rnf NL_Err = ()
rnf (NL_Cons n ns) = ()
-- rnf (NL_Cons n ns) = deepseq n $ rnf ns
instance (ValidNeighbor dp, Eq_ dp) => Eq_ (NeighborList k dp) where
(NL_Cons x xs) == (NL_Cons y ys) = x==y && xs==ys
NL_Nil == NL_Nil = True
-- NL_Err == NL_Err = True
_ == _ = False
property_orderedNeighborList :: (Logic dp~Bool, Metric dp) => NeighborList k dp -> Bool
property_orderedNeighborList NL_Nil = True
property_orderedNeighborList (NL_Cons n NL_Nil) = True
property_orderedNeighborList (NL_Cons n (NL_Cons n2 ns)) = if neighborDistance n < neighborDistance n2
then property_orderedNeighborList (NL_Cons n2 ns)
else False
{-# INLINE nlSingleton #-}
nlSingleton ::
( ValidNeighbor dp
) => Neighbor dp -> NeighborList k dp
nlSingleton !n = NL_Cons n NL_Nil
-- {-# INLINE mkNeighborList #-}
-- mkNeighborList ::
-- ( ValidNeighbor dp
-- ) => dp -> Scalar dp -> NeighborList k dp
-- mkNeighborList !dp !dist = NL_Cons (Neighbor dp dist) NL_Nil
{-# INLINE getknnL #-}
getknnL ::
( ValidNeighbor dp
) => NeighborList k dp -> [Neighbor dp]
getknnL NL_Nil = []
getknnL (NL_Cons n ns) = n:getknnL ns
-- getknnL NL_Err = error "getknnL: NL_Err"
{-# INLINE nlMaxDist #-}
nlMaxDist ::
( ValidNeighbor dp
) => NeighborList k dp -> Scalar dp
nlMaxDist !nl = go nl
where
go (NL_Cons n NL_Nil) = neighborDistance n
go (NL_Cons n ns) = go ns
go NL_Nil = maxBound
-- go NL_Err = maxBound
instance CanError (NeighborList k dp) where
{-# INLINE errorVal #-}
errorVal = NL_Nil
-- errorVal = NL_Err
{-# INLINE isError #-}
isError NL_Nil = True
-- isError NL_Err = True
isError _ = False
instance
-- ( KnownNat k
( ViewParam Param_k (NeighborList k dp)
, Metric dp
, Eq dp
, ValidNeighbor dp
) => Monoid (NeighborList k dp)
where
{-# INLINE zero #-}
zero = NL_Nil
instance
( ViewParam Param_k (NeighborList k dp)
, Metric dp
, Eq dp
, ValidNeighbor dp
) => Semigroup (NeighborList k dp)
where
{-# INLINE (+) #-}
-- nl1 + NL_Err = nl1
-- NL_Err + nl2 = nl2
nl1 + NL_Nil = nl1
NL_Nil + nl2 = nl2
nl1 + nl2 = {-# SCC notNiL #-} ret
where
ret = go nl1 nl2 (viewParam _k nl1)
go _ _ 0 = NL_Nil
go (NL_Cons n1 ns1) (NL_Cons n2 ns2) k = if neighborDistance n1 > neighborDistance n2
then NL_Cons n2 $ go (NL_Cons n1 ns1) ns2 (k-1)
else NL_Cons n1 $ go ns1 (NL_Cons n2 ns2) (k-1)
go NL_Nil (NL_Cons n2 ns2) k = NL_Cons n2 $ go NL_Nil ns2 (k-1)
go (NL_Cons n1 ns1) NL_Nil k = NL_Cons n1 $ go ns1 NL_Nil (k-1)
go NL_Nil NL_Nil k = NL_Nil
{-# INLINE nlAddNeighbor #-}
nlAddNeighbor :: forall k dp.
( ViewParam Param_k (NeighborList k dp)
, ValidNeighbor dp
) => NeighborList k dp -> Neighbor dp -> NeighborList k dp
-- nlAddNeighbor NL_Nil n' = NL_Cons n' NL_Nil
-- nlAddNeighbor (NL_Cons n NL_Nil) n' = if neighborDistance n' > neighborDistance n
-- then NL_Cons n' NL_Nil
-- else NL_Cons n NL_Nil
nlAddNeighbor !nl !n = {-# SCC nlAddNeighbor #-} nl + NL_Cons n NL_Nil
-- mappend (NeighborList (x:.xs) ) (NeighborList (y:.ys) ) = {-# SCC mappend_NeighborList #-} case k of
-- 1 -> if x < y then NeighborList (x:.Strict.Nil) else NeighborList (y:.Strict.Nil)
-- otherwise -> NeighborList $ Strict.take k $ interleave (x:.xs) (y:.ys)
-- where
-- k=fromIntegral $ natVal (Proxy :: Proxy k)
--
-- interleave !xs Strict.Nil = xs
-- interleave Strict.Nil !ys = ys
-- interleave (x:.xs) (y:.ys) = case compare x y of
-- LT -> x:.(interleave xs (y:.ys))
-- GT -> y:.(interleave (x:.xs) ys)
-- EQ -> if neighbor x == neighbor y
-- then x:.interleave xs ys
-- else x:.(y:.(interleave xs ys))
-------------------------------------------------------------------------------
-- single tree
{-# INLINABLE findNeighborList #-}
findNeighborList ::
-- ( KnownNat k
( ViewParam Param_k (NeighborList k dp)
, SpaceTree t dp
, Eq dp
, Real (Scalar dp)
, CanError (Scalar dp)
, ValidNeighbor dp
) => t dp -> dp -> NeighborList k dp
findNeighborList !t !query = findEpsilonNeighborListWith zero zero t query
{-# INLINABLE findEpsilonNeighborListWith #-}
findEpsilonNeighborListWith ::
-- ( KnownNat k
( ViewParam Param_k (NeighborList k dp)
, SpaceTree t dp
, Eq dp
, Real (Scalar dp)
, CanError (Scalar dp)
, ValidNeighbor dp
) => NeighborList k dp -> Scalar dp -> t dp -> dp -> NeighborList k dp
findEpsilonNeighborListWith !knn !epsilon !t !query =
{-# SCC findEpsilonNeighborListWith #-}
-- prunefoldC (knn_catadp smudge query) knn t
-- prunefoldB_CanError_sort query (knn_catadp smudge query) (knn_cata_dist smudge query) knn t
prunefoldB_CanError (knn_catadp smudge query) (knn_cata smudge query) knn t
-- prunefoldD (knn_catadp smudge query) (knn_cata2 smudge query) knn t
where
smudge = 1/(1+epsilon)
{-# INLINABLE knn_catadp #-}
-- {-# INLINE knn_catadp #-}
knn_catadp :: forall k dp.
-- ( KnownNat k
( ViewParam Param_k (NeighborList k dp)
, Metric dp
, Eq dp
, CanError (Scalar dp)
, ValidNeighbor dp
) => Scalar dp -> dp -> dp -> NeighborList k dp -> NeighborList k dp
knn_catadp !smudge !query !dp !knn = {-# SCC knn_catadp #-}
-- dist==0 is equivalent to query==dp,
-- but we have to calculate dist anyways so it's faster
if dist==0 || dist>bound
-- if dist==0 || isError dist
then knn
else nlAddNeighbor knn $ Neighbor dp dist
where
dist = distanceUB dp query bound
bound = smudge*nlMaxDist knn
-- dist = isFartherThanWithDistanceCanError dp query
-- $ nlMaxDist knn * smudge
-- {-# INLINABLE knn_cata #-}
{-# INLINE knn_cata #-}
knn_cata :: forall k t dp.
( ViewParam Param_k (NeighborList k dp)
, SpaceTree t dp
, Real (Scalar dp)
, Eq dp
, CanError (Scalar dp)
, ValidNeighbor dp
) => Scalar dp -> dp -> t dp -> NeighborList k dp -> NeighborList k dp
knn_cata !smudge !query !t !knn = {-# SCC knn_cata #-}
if dist==0
then if isError knn
then nlSingleton $ Neighbor (stNode t) maxBound
else knn
else if isError dist
then errorVal
else nlAddNeighbor knn $ Neighbor (stNode t) dist
where
dist = stIsMinDistanceDpFartherThanWithDistanceCanError t query
$ nlMaxDist knn * smudge
{-# INLINABLE prunefoldB_CanError_sort #-}
prunefoldB_CanError_sort ::
( SpaceTree t a
, ValidNeighbor a
, b ~ NeighborList k a
, ClassicalLogic a
, CanError (Scalar a)
, Bounded (Scalar a)
) =>
a -> (a -> b -> b) -> (Scalar a -> t a -> b -> b) -> b -> t a -> b
prunefoldB_CanError_sort !query !f1 !f2 !b !t = {-# SCC prunefoldB_CanError_sort #-}
go ( distance (stNode t) query :!: t ) b
where
go !( dist :!: t ) !b = if isError res
then b
else foldr' go b'' children'
where
res = f2 dist t b
b'' = foldr' f1 res (stLeaves t)
children'
= {-# SCC children' #-} qsortHalf (\( d1 :!: _ ) ( d2 :!: _ ) -> compare d2 d1)
$ map (\x -> ( stIsMinDistanceDpFartherThanWithDistanceCanError x query maxdist
:!: x ))
-- $ map (\x -> ( distanceUB (stNode x) query (lambda t+maxdist), x ))
-- $ map (\x -> ( distance (stNode x) query , x ))
$ toList
$ stChildren t
maxdist = nlMaxDist b''
-- | This is a version of quicksort that only descends on its lower half.
-- That is, it only "approximately" sorts a list.
-- It is modified from http://en.literateprograms.org/Quicksort_%28Haskell%29
{-# INLINABLE qsortHalf #-}
qsortHalf :: (a -> a -> Ordering) -> [a] -> [a]
qsortHalf !cmp !x = {-# SCC qsortHalf #-} go x []
where
go [] !y = y
go [x] !y = x:y
go (x:xs) !y = part xs [] [x] []
where
part [] !l !e !g = go l (e ++ g ++ y)
part (z:zs) !l !e !g = case cmp z x of
GT -> part zs l e (z:g)
LT -> part zs (z:l) e g
EQ -> part zs l (z:e) g
{-# INLINABLE knn_cata_dist #-}
knn_cata_dist :: forall k t dp.
( ViewParam Param_k (NeighborList k dp)
, SpaceTree t dp
, Real (Scalar dp)
, Eq dp
, CanError (Scalar dp)
, ValidNeighbor dp
) => Scalar dp -> dp -> Scalar dp -> t dp -> NeighborList k dp -> NeighborList k dp
knn_cata_dist !smudge !query !dist !t !knn = {-# SCC knn_cata #-}
if dist==0
then if isError knn
then nlSingleton $ Neighbor (stNode t) maxBound
else knn
-- else if dist - lambda t > nlMaxDist knn * smudge -- isError dist
else if isError dist
then errorVal
else nlAddNeighbor knn $ Neighbor (stNode t) dist
-- where
-- dist = stIsMinDistanceDpFartherThanWithDistanceCanError t query
-- $ nlMaxDist knn * smudge
---------------------------------------
{-# INLINABLE findAllNeighbors #-}
findAllNeighbors :: forall k dp t.
( ViewParam Param_k (NeighborList k dp)
, SpaceTree t dp
, NFData (Scalar dp)
, NFData dp
, Real (Scalar dp)
, CanError (Scalar dp)
, ValidNeighbor dp
) => Scalar dp -> t dp -> [dp] -> Seq (dp,NeighborList k dp)
findAllNeighbors epsilon rtree qs = reduce $ map
(\dp -> singleton (dp, findEpsilonNeighborListWith zero epsilon rtree dp))
qs
{-# INLINABLE findAllNeighbors' #-}
findAllNeighbors' :: forall k dp t.
( ViewParam Param_k (NeighborList k dp)
, SpaceTree t dp
, NFData (Scalar dp)
, NFData dp
, Real (Scalar dp)
, CanError (Scalar dp)
, ValidNeighbor dp
) => Scalar dp -> t dp -> [dp] -> Seq (Labeled' dp (NeighborList k dp))
findAllNeighbors' epsilon rtree qs = fromList $ map
(\dp -> mkLabeled' dp $ findEpsilonNeighborListWith zero epsilon rtree dp)
qs
-- findAllNeighbors' epsilon rtree qs = reduce $ map
-- (\dp -> singleton $ mkLabeled' dp $ findEpsilonNeighborListWith zero epsilon rtree dp)
-- qs
mkLabeled' :: x -> y -> Labeled' x y
mkLabeled' x y = Labeled' x y
| iamkingmaker/HLearn | src/HLearn/Data/SpaceTree/Algorithms/NearestNeighbor.hs | bsd-3-clause | 13,397 | 0 | 17 | 3,820 | 3,487 | 1,806 | 1,681 | -1 | -1 |
{-|
Module : Data.Boltzmann.Internal.Utils
Description : General utilities for boltzmann-brain.
Copyright : (c) Maciej Bendkowski, 2017-2021
License : BSD3
Maintainer : [email protected]
Stability : experimental
General utilities for boltzmann-brain.
-}
module Data.Boltzmann.Internal.Utils
( quote
, ensureLn
, closest
, bold
, italic
, underline
, boldColor
, csv
, getTime
, writeListLn
, printer
, showsList
) where
import System.IO
import System.Console.Pretty
import Text.EditDistance
import Data.Time.Clock
import Data.Time.LocalTime
import Data.Time.Format
getTime :: IO String
getTime = do
now <- getCurrentTime
timeZone <- getCurrentTimeZone
let t = utcToLocalTime timeZone now
return $ formatTime defaultTimeLocale "%d-%m-%Y %H:%M:%S" t
writeListLn :: Show a => Handle -> [a] -> IO ()
writeListLn h xs = hPutStrLn h (showsList xs)
printer :: (a -> String -> String) -> [a] -> String
printer _ [] = ""
printer f xs = foldl1 (\a b -> (a . (" " ++) . b))
(map f xs) ""
showsList :: Show a => [a]
-> String
showsList = printer shows
-- | Produces a comma separated value (csv) representation
-- of the given list of string. Note that after each comma
-- there's placed an additional whitespace character.
csv :: [String] -> String
csv [] = ""
csv xs = foldl1 (\x y -> x ++ ", " ++ y) xs
-- | Given a string, ensures that it ends with
-- a newline character, appending it if needed.
ensureLn :: String -> String
ensureLn s
| last s == '\n' = s
| otherwise = unlines [s]
-- | Single-quotes the given string.
quote :: String -> String
quote m = "'" ++ m ++ "'"
format :: (String -> String)
-> String -> IO String
format f s = do
inColor <- supportsPretty
return $ if inColor then f s
else s
-- | Given a string, outputs its bold variant
-- (assuming that the terminal supports it)
bold :: String -> IO String
bold = format (style Bold)
-- | Given a string, outputs its italic variant
-- (assuming that the terminal supports it)
italic :: String -> IO String
italic = format (style Italic)
-- | Given a string, outputs its underlined variant
-- (assuming that the terminal supports it)
underline :: String -> IO String
underline = format (style Underline)
-- | Given a string, outputs its bold, colored variant
-- (assuming that the terminal supports it)
boldColor :: Color -> String -> IO String
boldColor c = format (style Bold . color c)
-- | Given a non-empty list of distinct strings, finds the closest
-- (in terms of editing distance) string to the given one.
closest :: [String] -> String -> String
closest dic s = closest' (tail dists) (head dists)
where dists = zip dic $ map (editDist s) dic
closest' :: Ord b => [(a, b)] -> (a, b) -> a
closest' [] (m, _) = m
closest' ((x,k):xs) (m, k')
| k < k' = closest' xs (x, k)
| otherwise = closest' xs (m, k')
-- | Levenshtein distance of two strings.
editDist :: String -> String -> Int
editDist = levenshteinDistance defaultEditCosts
| maciej-bendkowski/boltzmann-brain | Data/Boltzmann/Internal/Utils.hs | bsd-3-clause | 3,129 | 0 | 11 | 739 | 829 | 443 | 386 | 67 | 2 |
{-|
Module : Idris.Docs
Description : Data structures and utilities to work with Idris Documentation.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE DeriveFunctor, PatternGuards, MultiWayIf #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module Idris.Docs (
pprintDocs
, getDocs, pprintConstDocs, pprintTypeDoc
, FunDoc, FunDoc'(..), Docs, Docs'(..)
) where
import Idris.AbsSyntax
import Idris.AbsSyntaxTree
import Idris.Delaborate
import Idris.Core.TT
import Idris.Core.Evaluate
import Idris.Docstrings (Docstring, emptyDocstring, noDocs, nullDocstring, renderDocstring, DocTerm, renderDocTerm, overview)
import Util.Pretty
import Prelude hiding ((<$>))
import Control.Arrow (first)
import Data.Maybe
import Data.List
import qualified Data.Text as T
-- TODO: Only include names with public/export accessibility
--
-- Issue #1573 on the Issue tracker.
-- https://github.com/idris-lang/Idris-dev/issues/1573
data FunDoc' d = FD Name d
[(Name, PTerm, Plicity, Maybe d)] -- args: name, ty, implicit, docs
PTerm -- function type
(Maybe Fixity)
deriving Functor
type FunDoc = FunDoc' (Docstring DocTerm)
data Docs' d = FunDoc (FunDoc' d)
| DataDoc (FunDoc' d) -- type constructor docs
[FunDoc' d] -- data constructor docs
| InterfaceDoc Name d -- interface docs
[FunDoc' d] -- method docs
[(Name, Maybe d)] -- parameters and their docstrings
[(Maybe Name, PTerm, (d, [(Name, d)]))] -- implementations: name for named implementations, the constraint term, the docs
[PTerm] -- sub interfaces
[PTerm] -- super interfaces
(Maybe (FunDoc' d)) -- explicit constructor
| RecordDoc Name d -- record docs
(FunDoc' d) -- data constructor docs
[FunDoc' d] -- projection docs
[(Name, PTerm, Maybe d)] -- parameters with type and doc
| NamedImplementationDoc Name (FunDoc' d) -- name is interface
| ModDoc [String] -- Module name
d
deriving Functor
type Docs = Docs' (Docstring DocTerm)
showDoc ist d
| nullDocstring d = empty
| otherwise = text " -- " <>
renderDocstring (renderDocTerm (pprintDelab ist) (normaliseAll (tt_ctxt ist) [])) d
pprintFD :: IState -> Bool -> Bool -> FunDoc -> Doc OutputAnnotation
pprintFD ist totalityFlag nsFlag (FD n doc args ty f) =
nest 4 (prettyName True nsFlag [] n
<+> colon
<+> pprintPTerm ppo [] [ n | (n@(UN n'),_,_,_) <- args
, not (T.isPrefixOf (T.pack "__") n') ] infixes ty
-- show doc
<$> renderDocstring (renderDocTerm (pprintDelab ist) (normaliseAll (tt_ctxt ist) [])) doc
-- show fixity
<$> maybe empty (\f -> text (show f) <> line) f
-- show arguments doc
<> let argshow = showArgs args [] in
(if not (null argshow)
then nest 4 $ text "Arguments:" <$> vsep argshow
else empty)
-- show totality status
<> let totality = getTotality in
(if totalityFlag && not (null totality)
then line <> (vsep . map (\t -> text "The function is" <+> t) $ totality)
else empty))
where
ppo = ppOptionIst ist
infixes = idris_infixes ist
-- Recurse over and show the Function's Documented arguments
showArgs ((n, ty, Exp {}, Just d):args) bnd = -- Explicitly bound.
bindingOf n False
<+> colon
<+> pprintPTerm ppo bnd [] infixes ty
<> showDoc ist d
<> line : showArgs args ((n, False):bnd)
showArgs ((n, ty, Constraint {}, Just d):args) bnd = -- Interface constraints.
text "Interface constraint"
<+> pprintPTerm ppo bnd [] infixes ty
<> showDoc ist d
<> line : showArgs args ((n, True):bnd)
showArgs ((n, ty, Imp {}, Just d):args) bnd = -- Implicit arguments.
text "(implicit)"
<+> bindingOf n True
<+> colon
<+> pprintPTerm ppo bnd [] infixes ty
<> showDoc ist d
<> line : showArgs args ((n, True):bnd)
showArgs ((n, ty, TacImp{}, Just d):args) bnd = -- Tacit implicits
text "(auto implicit)"
<+> bindingOf n True
<+> colon
<+> pprintPTerm ppo bnd [] infixes ty
<> showDoc ist d
<> line : showArgs args ((n, True):bnd)
showArgs ((n, _, _, _):args) bnd = -- Anything else
showArgs args ((n, True):bnd)
showArgs [] _ = [] -- end of arguments
getTotality = map (text . show) $ lookupTotal n (tt_ctxt ist)
pprintFDWithTotality :: IState -> Bool -> FunDoc -> Doc OutputAnnotation
pprintFDWithTotality ist = pprintFD ist True
pprintFDWithoutTotality :: IState -> Bool -> FunDoc -> Doc OutputAnnotation
pprintFDWithoutTotality ist = pprintFD ist False
pprintDocs :: IState -> Docs -> Doc OutputAnnotation
pprintDocs ist (FunDoc d) = pprintFDWithTotality ist True d
pprintDocs ist (DataDoc t args)
= text "Data type" <+> pprintFDWithoutTotality ist True t <$>
if null args then text "No constructors."
else nest 4 (text "Constructors:" <> line <>
vsep (map (pprintFDWithoutTotality ist False) args))
pprintDocs ist (InterfaceDoc n doc meths params implementations sub_interfaces super_interfaces ctor)
= nest 4 (text "Interface" <+> prettyName True (ppopt_impl ppo) [] n <>
if nullDocstring doc
then empty
else line <> renderDocstring (renderDocTerm (pprintDelab ist) (normaliseAll (tt_ctxt ist) [])) doc)
<> line <$>
nest 4 (text "Parameters:" <$> prettyParameters)
<> line <$>
nest 4 (text "Methods:" <$>
vsep (map (pprintFDWithTotality ist False) meths))
<$>
maybe empty
((<> line) . nest 4 .
(text "Implementation constructor:" <$>) .
pprintFDWithoutTotality ist False)
ctor
<>
nest 4 (text "Implementations:" <$>
vsep (if null implementations then [text "<no implementations>"]
else map pprintImplementation normalImplementations))
<>
(if null namedImplementations then empty
else line <$> nest 4 (text "Named implementations:" <$>
vsep (map pprintImplementation namedImplementations)))
<>
(if null sub_interfaces then empty
else line <$> nest 4 (text "Child interfaces:" <$>
vsep (map (dumpImplementation . prettifySubInterfaces) sub_interfaces)))
<>
(if null super_interfaces then empty
else line <$> nest 4 (text "Default parent implementations:" <$>
vsep (map dumpImplementation super_interfaces)))
where
params' = zip pNames (repeat False)
(normalImplementations, namedImplementations) = partition (\(n, _, _) -> not $ isJust n)
implementations
pNames = map fst params
ppo = ppOptionIst ist
infixes = idris_infixes ist
pprintImplementation (mname, term, (doc, argDocs)) =
nest 4 (iname mname <> dumpImplementation term <>
(if nullDocstring doc
then empty
else line <>
renderDocstring
(renderDocTerm
(pprintDelab ist)
(normaliseAll (tt_ctxt ist) []))
doc) <>
if null argDocs
then empty
else line <> vsep (map (prettyImplementationParam (map fst argDocs)) argDocs))
iname Nothing = empty
iname (Just n) = annName n <+> colon <> space
prettyImplementationParam params (name, doc) =
if nullDocstring doc
then empty
else prettyName True False (zip params (repeat False)) name <+>
showDoc ist doc
-- if any (isJust . snd) params
-- then vsep (map (\(nm,md) -> prettyName True False params' nm <+> maybe empty (showDoc ist) md) params)
-- else hsep (punctuate comma (map (prettyName True False params' . fst) params))
dumpImplementation :: PTerm -> Doc OutputAnnotation
dumpImplementation = pprintPTerm ppo params' [] infixes
prettifySubInterfaces (PPi (Constraint _ _) _ _ tm _) = prettifySubInterfaces tm
prettifySubInterfaces (PPi plcity nm fc t1 t2) = PPi plcity (safeHead nm pNames) NoFC (prettifySubInterfaces t1) (prettifySubInterfaces t2)
prettifySubInterfaces (PApp fc ref args) = PApp fc ref $ updateArgs pNames args
prettifySubInterfaces tm = tm
safeHead _ (y:_) = y
safeHead x [] = x
updateArgs (p:ps) ((PExp prty opts _ ref):as) = (PExp prty opts p (updateRef p ref)) : updateArgs ps as
updateArgs ps (a:as) = a : updateArgs ps as
updateArgs _ _ = []
updateRef nm (PRef fc _ _) = PRef fc [] nm
updateRef _ pt = pt
isSubInterface (PPi (Constraint _ _) _ _ (PApp _ _ args) (PApp _ (PRef _ _ nm) args')) = nm == n && map getTm args == map getTm args'
isSubInterface (PPi _ _ _ _ pt) = isSubInterface pt
isSubInterface _ = False
prettyParameters =
if any (isJust . snd) params
then vsep (map (\(nm,md) -> prettyName True False params' nm <+> maybe empty (showDoc ist) md) params)
else hsep (punctuate comma (map (prettyName True False params' . fst) params))
pprintDocs ist (RecordDoc n doc ctor projs params)
= nest 4 (text "Record" <+> prettyName True (ppopt_impl ppo) [] n <>
if nullDocstring doc
then empty
else line <>
renderDocstring (renderDocTerm (pprintDelab ist) (normaliseAll (tt_ctxt ist) [])) doc)
-- Parameters
<$> (if null params
then empty
else line <> nest 4 (text "Parameters:" <$> prettyParameters) <> line)
-- Constructor
<$> nest 4 (text "Constructor:" <$> pprintFDWithoutTotality ist False ctor)
-- Projections
<$> nest 4 (text "Projections:" <$> vsep (map (pprintFDWithoutTotality ist False) projs))
where
ppo = ppOptionIst ist
infixes = idris_infixes ist
pNames = [n | (n,_,_) <- params]
params' = zip pNames (repeat False)
prettyParameters =
if any isJust [d | (_,_,d) <- params]
then vsep (map (\(n,pt,d) -> prettyParam (n,pt) <+> maybe empty (showDoc ist) d) params)
else hsep (punctuate comma (map prettyParam [(n,pt) | (n,pt,_) <- params]))
prettyParam (n,pt) = prettyName True False params' n <+> text ":" <+> pprintPTerm ppo params' [] infixes pt
pprintDocs ist (NamedImplementationDoc _cls doc)
= nest 4 (text "Named implementation:" <$> pprintFDWithoutTotality ist True doc)
pprintDocs ist (ModDoc mod docs)
= nest 4 $ text "Module" <+> text (concat (intersperse "." mod)) <> colon <$>
renderDocstring (renderDocTerm (pprintDelab ist) (normaliseAll (tt_ctxt ist) [])) docs
-- | Determine a truncation function depending how much docs the user
-- wants to see
howMuch FullDocs = id
howMuch OverviewDocs = overview
-- | Given a fully-qualified, disambiguated name, construct the
-- documentation object for it
getDocs :: Name -> HowMuchDocs -> Idris Docs
getDocs n@(NS n' ns) w | n' == modDocName
= do i <- getIState
case lookupCtxtExact n (idris_moduledocs i) of
Just doc -> return . ModDoc (reverse (map T.unpack ns)) $ howMuch w doc
Nothing -> fail $ "Module docs for " ++ show (reverse (map T.unpack ns)) ++
" do not exist! This shouldn't have happened and is a bug."
getDocs n w
= do i <- getIState
docs <- if | Just ci <- lookupCtxtExact n (idris_interfaces i)
-> docInterface n ci
| Just ri <- lookupCtxtExact n (idris_records i)
-> docRecord n ri
| Just ti <- lookupCtxtExact n (idris_datatypes i)
-> docData n ti
| Just interface_ <- interfaceNameForImpl i n
-> do fd <- docFun n
return $ NamedImplementationDoc interface_ fd
| otherwise
-> do fd <- docFun n
return (FunDoc fd)
return $ fmap (howMuch w) docs
where interfaceNameForImpl :: IState -> Name -> Maybe Name
interfaceNameForImpl ist n =
listToMaybe [ cn
| (cn, ci) <- toAlist (idris_interfaces ist)
, n `elem` map fst (interface_implementations ci)
]
docData :: Name -> TypeInfo -> Idris Docs
docData n ti
= do tdoc <- docFun n
cdocs <- mapM docFun (con_names ti)
return (DataDoc tdoc cdocs)
docInterface :: Name -> InterfaceInfo -> Idris Docs
docInterface n ci
= do i <- getIState
let docStrings = listToMaybe $ lookupCtxt n $ idris_docstrings i
docstr = maybe emptyDocstring fst docStrings
params = map (\pn -> (pn, docStrings >>= (lookup pn . snd)))
(interface_params ci)
docsForImplementation impl = fromMaybe (emptyDocstring, []) .
flip lookupCtxtExact (idris_docstrings i) $
impl
implementations = map (\impl -> (namedImpl impl,
delabTy i impl,
docsForImplementation impl))
(nub (map fst (interface_implementations ci)))
(sub_interfaces, implementations') = partition (isSubInterface . (\(_,tm,_) -> tm)) implementations
super_interfaces = catMaybes $ map getDImpl (interface_default_super_interfaces ci)
mdocs <- mapM (docFun . fst) (interface_methods ci)
let ctorN = implementationCtorName ci
ctorDocs <- case basename ctorN of
SN _ -> return Nothing
_ -> fmap Just $ docFun ctorN
return $ InterfaceDoc
n docstr mdocs params
implementations' (map (\(_,tm,_) -> tm) sub_interfaces) super_interfaces
ctorDocs
where
namedImpl (NS n ns) = fmap (flip NS ns) (namedImpl n)
namedImpl n@(UN _) = Just n
namedImpl _ = Nothing
getDImpl (PImplementation _ _ _ _ _ _ _ _ _ _ _ _ t _ _) = Just t
getDImpl _ = Nothing
isSubInterface (PPi (Constraint _ _) _ _ (PApp _ _ args) (PApp _ (PRef _ _ nm) args'))
= nm == n && map getTm args == map getTm args'
isSubInterface (PPi _ _ _ _ pt)
= isSubInterface pt
isSubInterface _
= False
docRecord :: Name -> RecordInfo -> Idris Docs
docRecord n ri
= do i <- getIState
let docStrings = listToMaybe $ lookupCtxt n $ idris_docstrings i
docstr = maybe emptyDocstring fst docStrings
params = map (\(pn,pt) -> (pn, pt, docStrings >>= (lookup (nsroot pn) . snd)))
(record_parameters ri)
pdocs <- mapM docFun (record_projections ri)
ctorDocs <- docFun $ record_constructor ri
return $ RecordDoc n docstr ctorDocs pdocs params
docFun :: Name -> Idris FunDoc
docFun n
= do i <- getIState
let (docstr, argDocs) = case lookupCtxt n (idris_docstrings i) of
[d] -> d
_ -> noDocs
let ty = delabTy i n
let args = getPArgNames ty argDocs
let infixes = idris_infixes i
let fixdecls = filter (\(Fix _ x) -> x == funName n) infixes
let f = case fixdecls of
[] -> Nothing
(Fix x _:_) -> Just x
return (FD n docstr args ty f)
where funName :: Name -> String
funName (UN n) = str n
funName (NS n _) = funName n
funName n = show n
getPArgNames :: PTerm -> [(Name, Docstring DocTerm)] -> [(Name, PTerm, Plicity, Maybe (Docstring DocTerm))]
getPArgNames (PPi plicity name _ ty body) ds =
(name, ty, plicity, lookup name ds) : getPArgNames body ds
getPArgNames _ _ = []
pprintConstDocs :: IState -> Const -> String -> Doc OutputAnnotation
pprintConstDocs ist c str = text "Primitive" <+> text (if constIsType c then "type" else "value") <+>
pprintPTerm (ppOptionIst ist) [] [] [] (PConstant NoFC c) <+> colon <+>
pprintPTerm (ppOptionIst ist) [] [] [] (t c) <>
nest 4 (line <> text str)
where t (Fl _) = PConstant NoFC $ AType ATFloat
t (BI _) = PConstant NoFC $ AType (ATInt ITBig)
t (Str _) = PConstant NoFC StrType
t (Ch c) = PConstant NoFC $ AType (ATInt ITChar)
t _ = PType NoFC
pprintTypeDoc :: IState -> Doc OutputAnnotation
pprintTypeDoc ist = prettyIst ist (PType emptyFC) <+> colon <+> type1Doc <+>
nest 4 (line <> text typeDescription)
| enolan/Idris-dev | src/Idris/Docs.hs | bsd-3-clause | 17,843 | 0 | 25 | 6,174 | 5,482 | 2,778 | 2,704 | 323 | 24 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-|
Module : Yesod.Auth.Hardcoded
Description : Very simple auth plugin for hardcoded auth pairs.
Copyright : (c) Arthur Fayzrakhmanov, 2015
License : MIT
Maintainer : [email protected]
Stability : experimental
Sometimes you may want to have some hardcoded set of users (e.g. site managers)
that allowed to log in and visit some specific sections of your website without
ability to register new managers. This simple plugin is designed exactly for
this purpose.
Here is a quick usage example.
== Define hardcoded users representation
Let's assume, that we want to have some hardcoded managers with normal site
users. Let's define hardcoded user representation:
@
data SiteManager = SiteManager
{ manUserName :: Text
, manPassWord :: Text }
deriving Show
siteManagers :: [SiteManager]
siteManagers = [SiteManager "content editor" "top secret"]
@
== Describe 'YesodAuth' instance
Now we need to have some convenient 'AuthId' type representing both
cases:
@
instance YesodAuth App where
type AuthId App = Either UserId Text
@
Here, right @Text@ value will present hardcoded user name (which obviously must
be unique).
'AuthId' must have an instance of 'PathPiece' class, this is needed to store
user identifier in session (this happens in 'setCreds' and 'setCredsRedirect'
actions) and to read that identifier from session (this happens in
`dafaultMaybeAuthId` action). So we have to define it:
@
import Text.Read (readMaybe)
instance PathPiece (Either UserId Text) where
fromPathPiece = readMaybe . unpack
toPathPiece = pack . show
@
Quiet simple so far. Now let's add plugin to 'authPlugins' list, and define
'authenticate' method, it should return user identifier for given credentials,
for normal users it is usually persistent key, for hardcoded users we will
return user name again.
@
instance YesodAuth App where
-- ..
authPlugins _ = [authHardcoded]
authenticate Creds{..} =
return
(case credsPlugin of
"hardcoded" ->
case lookupUser credsIdent of
Nothing -> UserError InvalidLogin
Just m -> Authenticated (Right (manUserName m)))
@
Here @lookupUser@ is just a helper function to lookup hardcoded users by name:
@
lookupUser :: Text -> Maybe SiteManager
lookupUser username = find (\m -> manUserName m == username) siteManagers
@
== Describe an 'YesodAuthPersist' instance
Now we need to manually define 'YesodAuthPersist' instance.
> instance YesodAuthPersist App where
> type AuthEntity App = Either User SiteManager
>
> getAuthEntity (Left uid) =
> do x <- runDB (get uid)
> return (Left <$> x)
> getAuthEntity (Right username) = return (Right <$> lookupUser username)
== Define 'YesodAuthHardcoded' instance
Finally, let's define an plugin instance
@
instance YesodAuthHardcoded App where
validatePassword u = return . validPassword u
doesUserNameExist = return . isJust . lookupUser
validPassword :: Text -> Text -> Bool
validPassword u p =
case find (\m -> manUserName m == u && manPassWord m == p) siteManagers of
Just _ -> True
_ -> False
@
== Conclusion
Now we can use 'maybeAuthId', 'maybeAuthPair', 'requireAuthId', and
'requireAuthPair', moreover, the returned value makes possible to distinguish
normal users and site managers.
-}
module Yesod.Auth.Hardcoded
( YesodAuthHardcoded(..)
, authHardcoded
, loginR )
where
import Yesod.Auth (Auth, AuthPlugin (..), AuthRoute,
Creds (..), Route (..), YesodAuth,
loginErrorMessageI, setCredsRedirect)
import qualified Yesod.Auth.Message as Msg
import Yesod.Core
import Yesod.Form (ireq, runInputPost, textField)
import Control.Applicative ((<$>), (<*>))
import Data.Text (Text)
loginR :: AuthRoute
loginR = PluginR "hardcoded" ["login"]
class (YesodAuth site) => YesodAuthHardcoded site where
-- | Check whether given user name exists among hardcoded names.
doesUserNameExist :: Text -> HandlerT site IO Bool
-- | Validate given user name with given password.
validatePassword :: Text -> Text -> HandlerT site IO Bool
authHardcoded :: YesodAuthHardcoded m => AuthPlugin m
authHardcoded =
AuthPlugin "hardcoded" dispatch loginWidget
where
dispatch "POST" ["login"] = postLoginR >>= sendResponse
dispatch _ _ = notFound
loginWidget toMaster = do
request <- getRequest
[whamlet|
$newline never
<form method="post" action="@{toMaster loginR}">
$maybe t <- reqToken request
<input type=hidden name=#{defaultCsrfParamName} value=#{t}>
<table>
<tr>
<th>_{Msg.UserName}
<td>
<input type="text" name="username" required>
<tr>
<th>_{Msg.Password}
<td>
<input type="password" name="password" required>
<tr>
<td colspan="2">
<button type="submit" .btn .btn-success>_{Msg.LoginTitle}
|]
postLoginR :: (YesodAuthHardcoded master)
=> HandlerT Auth (HandlerT master IO) TypedContent
postLoginR =
do (username, password) <- lift (runInputPost
((,) <$> ireq textField "username"
<*> ireq textField "password"))
isValid <- lift (validatePassword username password)
if isValid
then lift (setCredsRedirect (Creds "hardcoded" username []))
else do isExists <- lift (doesUserNameExist username)
loginErrorMessageI LoginR
(if isExists
then Msg.InvalidUsernamePass
else Msg.IdentifierNotFound username)
| erikd/yesod | yesod-auth/Yesod/Auth/Hardcoded.hs | mit | 6,084 | 0 | 14 | 1,554 | 454 | 254 | 200 | 46 | 3 |
module Uroboro.InterpreterSpec
(
spec
) where
import Test.Hspec
import Text.Parsec (parse)
import Paths_uroboro (getDataFileName)
import Uroboro.Checker (typecheck, inferExp)
import Uroboro.CheckerSpec (prelude)
import Uroboro.Interpreter (pmatch, eval)
import Uroboro.Parser (parseDef, parseExp)
import Uroboro.Tree.Internal
import Utils (parseString)
rules :: IO Rules
rules = do
fname <- getDataFileName "samples/prelude.uro"
input <- readFile fname
case parse parseDef fname input of
Left _ -> fail "Parser"
Right defs -> case typecheck defs of
Left _ -> fail "Checker"
Right p -> return p
main :: String -> IO Exp
main input = do
pexp <- parseString parseExp input
prog <- prelude
case inferExp prog [] pexp of
Left _ -> fail "Checker"
Right texp -> return texp
spec :: Spec
spec = do
let int = Type "Int"
describe "pattern matching" $ do
it "fills variables" $ do
let name = "l"
let t = Type "ListOfInt"
let term = (ConExp t "empty" [])
pmatch term (VarPat t name) `shouldBe` Right [(name, term)]
describe "eval" $ do
it "completes" $ do
p <- rules
m <- main "add(zero(), succ(zero()))"
eval p m `shouldBe` ConExp int "succ" [ConExp int "zero" []]
it "can run add1(0)" $ do
p <- rules
m <- main "add1().apply(zero())"
r <- main "succ(zero())"
eval p m `shouldBe` r
it "can run add1(1)" $ do
p <- rules
m <- main "add1().apply(succ(zero()))"
r <- main "succ(succ(zero()))"
eval p m `shouldBe` r
it "matches manual reduction" $ do
p <- rules
m <- main "map(add1(), cons(succ(zero()), cons(zero(), empty())))"
r <- main "cons(succ(succ(zero())), cons(succ(zero()), empty()))"
eval p m `shouldBe` r
describe "prelude" $ do
it "adder works" $ do
p <- rules
m <- main "map(adder(succ(zero())), cons(succ(zero()), cons(zero(), empty())))"
r <- main "cons(succ(succ(zero())), cons(succ(zero()), empty()))"
eval p m `shouldBe` r
| tewe/uroboro | test/Uroboro/InterpreterSpec.hs | mit | 2,266 | 0 | 18 | 725 | 677 | 317 | 360 | 63 | 3 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeSynonymInstances #-}
module HERMIT.PrettyPrinter.Glyphs where
import Data.Semigroup (Semigroup(..))
import Data.Typeable
import HERMIT.Kure
import HERMIT.External
import HERMIT.PrettyPrinter.Common
import GHC.Generics
import System.Console.ANSI
-- | Glyph
data Glyph = Glyph { gText :: String
, gStyle :: Maybe SyntaxForColor
} deriving Show
-- | Glyphs
newtype Glyphs = Glyphs [Glyph] deriving (Generic, Show)
withStyle :: Maybe SyntaxForColor -> String -> IO ()
withStyle Nothing str = putStr str
withStyle (Just sty) str = do
setSGR $ styleSGR sty
putStr str
setSGR [Reset]
withNoStyle :: Maybe SyntaxForColor -> String -> IO ()
withNoStyle _ str = putStr str
styleSGR :: SyntaxForColor -> [SGR]
styleSGR KeywordColor = [simpleColor Blue]
styleSGR SyntaxColor = [simpleColor Red]
styleSGR IdColor = []
styleSGR CoercionColor = [simpleColor Yellow]
styleSGR TypeColor = [simpleColor Green]
styleSGR LitColor = [simpleColor Cyan]
styleSGR WarningColor = [SetColor Background Vivid Yellow
,SetColor Foreground Dull Black
]
simpleColor :: Color -> SGR
simpleColor = SetColor Foreground Vivid
instance RenderSpecial Glyphs where
renderSpecial sym = Glyphs [ Glyph [ch] (Just style) ]
where Unicode ch = renderSpecial sym
style =
case sym of
TypeSymbol -> TypeColor
TypeBindSymbol -> TypeColor
_ -> SyntaxColor
instance Monoid Glyphs where
mempty = Glyphs mempty
mappend = (<>)
instance Semigroup Glyphs where
Glyphs rs1 <> Glyphs rs2 =
Glyphs . flattenGlyphs . mergeGlyphs $ rs1 ++ rs2
flattenGlyphs :: [Glyph] -> [Glyph]
flattenGlyphs = go Nothing
where go :: Maybe SyntaxForColor -> [Glyph] -> [Glyph]
go _ [] = []
go s (Glyph str Nothing:r) = Glyph str s : go s r
go _ (Glyph [] s@Just{}:r) = go s r
go s (g:r) = g : go s r
mergeGlyphs :: [Glyph] -> [Glyph]
mergeGlyphs [] = []
mergeGlyphs [r] = [r]
mergeGlyphs (g:h:r) = case merge g h of
Left g' -> mergeGlyphs (g':r)
Right (g',h') -> g' : mergeGlyphs (h':r)
where merge (Glyph s1 Nothing) (Glyph s2 Nothing) =
Left $ Glyph (s1 ++ s2) Nothing
merge (Glyph [] Just{}) g2@(Glyph [] Just{}) = Left g2
merge g1 g2 = Right (g1,g2)
instance RenderCode Glyphs where
rPutStr txt = Glyphs [ Glyph txt Nothing, Glyph [] (Just IdColor) ]
rDoHighlight _ [] = mempty
rDoHighlight _ (Color col:_) = Glyphs [Glyph [] (Just col)]
rDoHighlight o (_:rest) = rDoHighlight o rest
-- External Instances
data TransformLCoreGlyphsBox = TransformLCoreGlyphsBox (TransformH LCore Glyphs) deriving Typeable
instance Extern (TransformH LCore Glyphs) where
type Box (TransformH LCore Glyphs) = TransformLCoreGlyphsBox
box = TransformLCoreGlyphsBox
unbox (TransformLCoreGlyphsBox i) = i
data TransformLCoreTCGlyphsBox = TransformLCoreTCGlyphsBox (TransformH LCoreTC Glyphs) deriving Typeable
instance Extern (TransformH LCoreTC Glyphs) where
type Box (TransformH LCoreTC Glyphs) = TransformLCoreTCGlyphsBox
box = TransformLCoreTCGlyphsBox
unbox (TransformLCoreTCGlyphsBox i) = i
| conal/hermit | src/HERMIT/PrettyPrinter/Glyphs.hs | bsd-2-clause | 3,508 | 0 | 12 | 901 | 1,142 | 591 | 551 | 82 | 4 |
{-| Executing jobs as processes
The protocol works as follows (MP = master process, FP = forked process):
* MP sets its own livelock as the livelock of the job to be executed.
* FP creates its own lock file and sends its name to the MP.
* MP updates the lock file name in the job file and confirms the FP it can
start.
* FP requests any secret parameters.
* MP sends the secret parameters, if any.
* Both MP and FP close the communication channel.
-}
{-
Copyright (C) 2014 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Query.Exec
( forkJobProcess
) where
import Control.Concurrent.Lifted (threadDelay)
import Control.Monad
import Control.Monad.Error
import qualified Data.Map as M
import Data.Maybe (mapMaybe, fromJust)
import System.Environment
import System.IO.Error (annotateIOError, modifyIOError)
import System.IO
import System.Process
import System.Posix.Process
import System.Posix.Signals (sigABRT, sigKILL, sigTERM, signalProcess)
import System.Posix.Types (ProcessID)
import Text.JSON
import qualified AutoConf as AC
import Ganeti.BasicTypes
import Ganeti.JQueue.Objects
import Ganeti.JSON (MaybeForJSON(..))
import Ganeti.Logging
import Ganeti.Logging.WriterLog
import Ganeti.OpCodes
import qualified Ganeti.Path as P
import Ganeti.Types
import Ganeti.UDSServer
import Ganeti.Compat (getPid')
connectConfig :: ConnectConfig
connectConfig = ConnectConfig { recvTmo = 30
, sendTmo = 30
}
-- | Catches a potential `IOError` and sets its description via
-- `annotateIOError`. This makes exceptions more informative when they
-- are thrown from an unnamed `Handle`.
rethrowAnnotateIOError :: String -> IO a -> IO a
rethrowAnnotateIOError desc =
modifyIOError (\e -> annotateIOError e desc Nothing Nothing)
-- | Spawn a subprocess to execute a Job's actual code in the Python
-- interpreter. The subprocess will have its standard input and output
-- connected to a pair of pipes wrapped in a Client instance. Standard error
-- will be inherited from the current process and can be used for early
-- logging, before the executor sets up its own logging.
spawnJobProcess :: JobId -> IO (ProcessID, Client)
spawnJobProcess jid = withErrorLogAt CRITICAL (show jid) $
do
use_debug <- isDebugMode
env_ <- (M.toList . M.insert "GNT_DEBUG" (if use_debug then "1" else "0")
. M.insert "PYTHONPATH" AC.versionedsharedir
. M.fromList)
`liftM` getEnvironment
execPy <- P.jqueueExecutorPy
logDebug $ "Executing " ++ AC.pythonPath ++ " " ++ execPy
++ " with PYTHONPATH=" ++ AC.versionedsharedir
(master, child) <- pipeClient connectConfig
let (rh, wh) = clientToHandle child
let jobProc = (proc AC.pythonPath [execPy, show (fromJobId jid)]){
std_in = UseHandle rh,
std_out = UseHandle wh,
std_err = Inherit,
env = Just env_,
close_fds = True}
(_, _, _, hchild) <- createProcess jobProc
pid <- getPid' hchild
return (fromJust pid, master)
filterSecretParameters :: [QueuedOpCode] -> [MaybeForJSON (JSObject
(Private JSValue))]
filterSecretParameters =
map (MaybeForJSON . fmap revealValInJSObject
. getSecretParams) . mapMaybe (transformOpCode . qoInput)
where
transformOpCode :: InputOpCode -> Maybe OpCode
transformOpCode inputCode =
case inputCode of
ValidOpCode moc -> Just (metaOpCode moc)
_ -> Nothing
getSecretParams :: OpCode -> Maybe (JSObject (Secret JSValue))
getSecretParams opcode =
case opcode of
(OpInstanceCreate {opOsparamsSecret = x}) -> x
(OpInstanceReinstall {opOsparamsSecret = x}) -> x
(OpTestOsParams {opOsparamsSecret = x}) -> x
_ -> Nothing
-- | Forks the job process and starts processing of the given job.
-- Returns the livelock of the job and its process ID.
forkJobProcess :: (Error e, Show e)
=> QueuedJob -- ^ a job to process
-> FilePath -- ^ the daemons own livelock file
-> (FilePath -> ResultT e IO ())
-- ^ a callback function to update the livelock file
-- and process id in the job file
-> ResultT e IO (FilePath, ProcessID)
forkJobProcess job luxiLivelock update = do
let jidStr = show . fromJobId . qjId $ job
-- Retrieve secret parameters if present
let secretParams = encodeStrict . filterSecretParameters . qjOps $ job
logDebug $ "Setting the lockfile temporarily to " ++ luxiLivelock
++ " for job " ++ jidStr
update luxiLivelock
ResultT . execWriterLogT . runResultT $ do
(pid, master) <- liftIO $ spawnJobProcess (qjId job)
let jobLogPrefix = "[start:job-" ++ jidStr ++ ",pid=" ++ show pid ++ "] "
logDebugJob = logDebug . (jobLogPrefix ++)
logDebugJob "Forked a new process"
let killIfAlive [] = return ()
killIfAlive (sig : sigs) = do
logDebugJob "Getting the status of the process"
status <- tryError . liftIO $ getProcessStatus False True pid
case status of
Left e -> logDebugJob $ "Job process already gone: " ++ show e
Right (Just s) -> logDebugJob $ "Child process status: " ++ show s
Right Nothing -> do
logDebugJob $ "Child process running, killing by " ++ show sig
liftIO $ signalProcess sig pid
unless (null sigs) $ do
threadDelay 100000 -- wait for 0.1s and check again
killIfAlive sigs
let onError = do
logDebugJob "Closing the pipe to the client"
withErrorLogAt WARNING "Closing the communication pipe failed"
(liftIO (closeClient master)) `orElse` return ()
killIfAlive [sigTERM, sigABRT, sigKILL]
flip catchError (\e -> onError >> throwError e)
$ do
let annotatedIO msg k = do
logDebugJob msg
liftIO $ rethrowAnnotateIOError (jobLogPrefix ++ msg) k
let recv msg = annotatedIO msg (recvMsg master)
send msg x = annotatedIO msg (sendMsg master x)
lockfile <- recv "Getting the lockfile of the client"
logDebugJob $ "Setting the lockfile to the final " ++ lockfile
toErrorBase $ update lockfile
send "Confirming the client it can start" ""
_ <- recv "Waiting for the job to ask for secret parameters"
send "Writing secret parameters to the client" secretParams
liftIO $ closeClient master
return (lockfile, pid)
| ganeti/ganeti | src/Ganeti/Query/Exec.hs | bsd-2-clause | 7,850 | 0 | 23 | 1,919 | 1,466 | 754 | 712 | 120 | 5 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : Csg.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:42
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qt.Glome.Csg (difference, intersection) where
import Qt.Glome.Vec
import Qt.Glome.Solid
import Qt.Glome.Sphere
import Qt.Glome.SolidTexture
import Qt.Glome.Clr
import Data.List
data Difference = Difference SolidItem SolidItem deriving Show
data Intersection = Intersection [SolidItem] deriving Show
difference :: SolidItem -> SolidItem -> SolidItem
difference a b = SolidItem $ Difference a b
rayint_difference2 :: Difference -> Ray -> Flt -> Texture -> Rayint
rayint_difference2 dif r d t =
let Difference sa sb = dif
Ray orig dir = r
ria = rayint sa r d t
my_ria = my_rayint sa r d t
in
if (inside sa orig)
then
if (inside sb orig)
then
case my_rayint sb r d t of
RayMiss -> RayMiss
RayHit bd bp bn bt ->
if (inside sa bp)
then RayHit bd bp (vinvert bn) bt
else RayMiss
else
RayMiss
{-
case rayint sb r d t of
RayHit bd bp bn bt -> RayHit bd bp bn bt
RayMiss ->
case my_ria of
RayMiss -> RayMiss
RayHit ad ap an at -> RayHit ad ap (vinvert an) at
-}
else
if (inside sb orig)
then
case my_rayint sb r d t of
RayMiss -> RayMiss
RayHit bd bp bn bt ->
if (inside sa bp)
then RayHit bd bp (vinvert bn) bt
else RayMiss
else
case rayint sa r d t of
RayMiss -> RayMiss
RayHit ad ap an at ->
if (inside sb ap)
then
let ir = ray_move (Ray ap dir) delta
in
case my_rayint sb ir d t of
RayMiss -> RayHit ad ap an at
RayHit bd bp bn bt ->
if inside sa bp
then RayHit (ad + bd + delta) bp (vinvert bn) bt
else RayMiss
else
RayHit ad ap an at
rayint_difference :: Difference -> Ray -> Flt -> Texture -> Rayint
rayint_difference dif r d t =
let Difference sa sb = dif
Ray orig dir = r
ria = rayint sa r d t
in
case ria of
RayMiss -> RayMiss
RayHit ad ap an at ->
if (inside sb orig)
then
case my_rayint sb r d t of
RayMiss -> RayHit ad ap an at
RayHit bd bp bn bt ->
if inside sa bp
then RayHit bd bp (vinvert bn) bt
else
if (bd >= ad)
then RayMiss
else RayHit ad ap an at
else
if (inside sb ap)
then
let ir = Ray ap dir
in
case my_rayint sb ir d t of
RayMiss -> RayHit ad ap an at
RayHit bd bp bn bt ->
if inside sa bp
then RayHit (ad + bd) bp (vinvert bn) bt
else RayMiss
else RayHit ad ap an at
t_matte c =
(\ri -> (Material c 0 0 0 1 2))
intersection :: [SolidItem] -> SolidItem
intersection slds = SolidItem $ Intersection slds
rayint_intersection :: Intersection -> Ray -> Flt -> Texture -> Rayint
rayint_intersection (Intersection slds) r d t =
let (Ray orig dir) = r
in
if null slds || d < 0
then RayMiss
else
let s = head slds
in case tail slds of
[] -> rayint s r d t
ss -> if inside s orig
then case rayint s r d t of
RayMiss -> rayint (Intersection ss) r d t
RayHit sd sp sn st ->
case rayint (Intersection ss) r sd t of
RayMiss -> rayint_advance (SolidItem (Intersection slds))
r d t sd
hit -> hit
else case rayint s r d t of
RayMiss -> RayMiss
RayHit sd sp sn st ->
if inside (Intersection ss) sp
then RayHit sd sp sn st
else rayint_advance (SolidItem (Intersection slds))
r d t sd
{-
my_rayint_si :: SolidItem -> Ray -> Flt -> Texture -> Rayint
my_rayint_si (SolidItem s) r d t = my_rayint s r d t
class Tc s where
my_rayint :: s -> Ray -> Flt -> Texture -> Rayint
instance Tc Sphere where
my_rayint s r d t = my_rayint_sphere s r d t
-}
inside_difference :: Difference -> Vec -> Bool
inside_difference (Difference sa sb) pt = False
inside_intersection :: Intersection -> Vec -> Bool
inside_intersection (Intersection slds) pt =
foldl' (&&) True (map (\x -> inside x pt) slds)
bound_difference :: Difference -> Bbox
bound_difference (Difference sa sb) = bound sa
bound_intersection :: Intersection -> Bbox
bound_intersection (Intersection slds) =
if null slds
then empty_bbox
else foldl' bboverlap everything_bbox (map bound slds)
primcount_difference :: Difference -> Pcount
primcount_difference (Difference sa sb) = pcadd (primcount sa) (primcount sb)
primcount_intersection :: Intersection -> Pcount
primcount_intersection (Intersection slds) = foldl (pcadd) pcnone (map primcount slds)
instance Solid Difference where
rayint = rayint_difference
inside = inside_difference
bound = bound_difference
primcount = primcount_difference
instance Solid Intersection where
rayint = rayint_intersection
inside = inside_intersection
bound = bound_intersection
primcount = primcount_intersection
| uduki/hsQt | extra-pkgs/Glome/Qt/Glome/Csg.hs | bsd-2-clause | 5,564 | 0 | 24 | 1,816 | 1,573 | 798 | 775 | 125 | 12 |
-- -----------------------------------------------------------------------------
--
-- Output.hs, part of Alex
--
-- (c) Simon Marlow 2003
--
-- Code-outputing and table-generation routines
--
-- ----------------------------------------------------------------------------}
module Output (outputDFA) where
import AbsSyn
import CharSet
import Util
import qualified Map
import qualified Data.IntMap as IntMap
import Control.Monad.ST ( ST, runST )
import Data.Array ( Array )
import Data.Array.Base ( unsafeRead )
import Data.Array.ST ( STUArray, newArray, readArray, writeArray, freeze )
import Data.Array.Unboxed ( UArray, elems, (!), array, listArray )
import Data.Bits
import Data.Char ( ord, chr )
import Data.List ( maximumBy, sortBy, groupBy )
-- -----------------------------------------------------------------------------
-- Printing the output
outputDFA :: Target -> Int -> String -> DFA SNum Code -> ShowS
outputDFA target _ _ dfa
= interleave_shows nl
[outputBase, outputTable, outputCheck, outputDefault, outputAccept]
where
(base, table, check, deflt, accept) = mkTables dfa
table_size = length table - 1
n_states = length base - 1
base_nm = "alex_base"
table_nm = "alex_table"
check_nm = "alex_check"
deflt_nm = "alex_deflt"
accept_nm = "alex_accept"
outputBase = do_array hexChars32 base_nm n_states base
outputTable = do_array hexChars16 table_nm table_size table
outputCheck = do_array hexChars16 check_nm table_size check
outputDefault = do_array hexChars16 deflt_nm n_states deflt
do_array hex_chars nm upper_bound ints = -- trace ("do_array: " ++ nm) $
case target of
GhcTarget ->
str nm . str " :: AlexAddr\n"
. str nm . str " = AlexA# \""
. str (hex_chars ints)
. str "\"#\n"
_ ->
str nm . str " :: Array Int Int\n"
. str nm . str " = listArray (0," . shows upper_bound
. str ") [" . interleave_shows (char ',') (map shows ints)
. str "]\n"
outputAccept
= -- No type signature: we don't know what the type of the actions is.
-- str accept_nm . str " :: Array Int (Accept Code)\n"
str accept_nm . str " = listArray (0::Int," . shows n_states
. str ") [" . interleave_shows (char ',') (map outputAccs accept)
. str "]\n"
outputAccs :: [Accept Code] -> ShowS
outputAccs accs
= brack (interleave_shows (char ',') (map (paren.outputAcc) accs))
outputAcc (Acc _ Nothing Nothing NoRightContext)
= str "AlexAccSkip"
outputAcc (Acc _ (Just act) Nothing NoRightContext)
= str "AlexAcc " . paren (str act)
outputAcc (Acc _ Nothing lctx rctx)
= str "AlexAccSkipPred " . space
. paren (outputPred lctx rctx)
outputAcc (Acc _ (Just act) lctx rctx)
= str "AlexAccPred " . space
. paren (str act) . space
. paren (outputPred lctx rctx)
outputPred (Just set) NoRightContext
= outputLCtx set
outputPred Nothing rctx
= outputRCtx rctx
outputPred (Just set) rctx
= outputLCtx set
. str " `alexAndPred` "
. outputRCtx rctx
outputLCtx set = str "alexPrevCharMatches" . str (charSetQuote set)
outputRCtx NoRightContext = id
outputRCtx (RightContextRExp sn)
= str "alexRightContext " . shows sn
outputRCtx (RightContextCode code)
= str code
-- outputArr arr
-- = str "array " . shows (bounds arr) . space
-- . shows (assocs arr)
-- -----------------------------------------------------------------------------
-- Generating arrays.
-- Here we use the table-compression algorithm described in section
-- 3.9 of the dragon book, which is a common technique used by lexical
-- analyser generators.
-- We want to generate:
--
-- base :: Array SNum Int
-- maps the current state to an offset in the main table
--
-- table :: Array Int SNum
-- maps (base!state + char) to the next state
--
-- check :: Array Int SNum
-- maps (base!state + char) to state if table entry is valid,
-- otherwise we use the default for this state
--
-- default :: Array SNum SNum
-- default production for this state
--
-- accept :: Array SNum [Accept Code]
-- maps state to list of accept codes for this state
--
-- For each state, we decide what will be the default symbol (pick the
-- most common). We now have a mapping Char -> SNum, with one special
-- state reserved as the default.
mkTables :: DFA SNum Code
-> (
[Int], -- base
[Int], -- table
[Int], -- check
[Int], -- default
[[Accept Code]] -- accept
)
mkTables dfa = -- trace (show (defaults)) $
-- trace (show (fmap (length . snd) dfa_no_defaults)) $
( elems base_offs,
take max_off (elems table),
take max_off (elems check),
elems defaults,
accept
)
where
accept = [ as | State as _ <- elems dfa_arr ]
state_assocs = Map.toAscList (dfa_states dfa)
n_states = length state_assocs
top_state = n_states - 1
dfa_arr :: Array SNum (State SNum Code)
dfa_arr = array (0,top_state) state_assocs
-- fill in all the error productions
expand_states =
[ expand (dfa_arr!state) | state <- [0..top_state] ]
expand (State _ out) =
[(i, lookup' out i) | i <- [0..0xff]]
where lookup' out' i = case IntMap.lookup i out' of
Nothing -> -1
Just s -> s
defaults :: UArray SNum SNum
defaults = listArray (0,top_state) (map best_default expand_states)
-- find the most common destination state in a given state, and
-- make it the default.
best_default :: [(Int,SNum)] -> SNum
best_default prod_list
| null sorted = -1
| otherwise = snd (head (maximumBy lengths eq))
where sorted = sortBy compareSnds prod_list
compareSnds (_,a) (_,b) = compare a b
eq = groupBy (\(_,a) (_,b) -> a == b) sorted
lengths a b = length a `compare` length b
-- remove all the default productions from the DFA
dfa_no_defaults =
[ (s, prods_without_defaults s out)
| (s, out) <- zip [0..] expand_states
]
prods_without_defaults s out
= [ (fromIntegral c, dest) | (c,dest) <- out, dest /= defaults!s ]
(base_offs, table, check, max_off)
= runST (genTables n_states 255 dfa_no_defaults)
genTables
:: Int -- number of states
-> Int -- maximum token no.
-> [(SNum,[(Int,SNum)])] -- entries for the table
-> ST s (UArray Int Int, -- base
UArray Int Int, -- table
UArray Int Int, -- check
Int -- highest offset in table
)
genTables n_states max_token entries = do
base <- newArray (0, n_states-1) 0
table <- newArray (0, mAX_TABLE_SIZE) 0
check <- newArray (0, mAX_TABLE_SIZE) (-1)
off_arr <- newArray (-max_token, mAX_TABLE_SIZE) 0
max_off <- genTables' base table check off_arr entries max_token
base' <- freeze base
table' <- freeze table
check' <- freeze check
return (base', table',check',max_off+1)
where mAX_TABLE_SIZE = n_states * (max_token + 1)
genTables'
:: STUArray s Int Int -- base
-> STUArray s Int Int -- table
-> STUArray s Int Int -- check
-> STUArray s Int Int -- offset array
-> [(SNum,[(Int,SNum)])] -- entries for the table
-> Int -- maximum token no.
-> ST s Int -- highest offset in table
genTables' base table check off_arr entries max_token
= fit_all entries 0 1
where
fit_all [] max_off _ = return max_off
fit_all (s:ss) max_off fst_zero = do
(off, new_max_off, new_fst_zero) <- fit s max_off fst_zero
writeArray off_arr off 1
fit_all ss new_max_off new_fst_zero
-- fit a vector into the table. Return the offset of the vector,
-- the maximum offset used in the table, and the offset of the first
-- entry in the table (used to speed up the lookups a bit).
fit (_,[]) max_off fst_zero = return (0,max_off,fst_zero)
fit (state_no, state@((t,_):_)) max_off fst_zero = do
-- start at offset 1 in the table: all the empty states
-- (states with just a default reduction) are mapped to
-- offset zero.
off <- findFreeOffset (-t + fst_zero) check off_arr state
let new_max_off | furthest_right > max_off = furthest_right
| otherwise = max_off
furthest_right = off + max_token
--trace ("fit: state " ++ show state_no ++ ", off " ++ show off ++ ", elems " ++ show state) $ do
writeArray base state_no off
addState off table check state
new_fst_zero <- findFstFreeSlot check fst_zero
return (off, new_max_off, new_fst_zero)
-- Find a valid offset in the table for this state.
findFreeOffset :: Int
-> STUArray s Int Int
-> STUArray s Int Int
-> [(Int, Int)]
-> ST s Int
findFreeOffset off check off_arr state = do
-- offset 0 isn't allowed
if off == 0 then try_next else do
-- don't use an offset we've used before
b <- readArray off_arr off
if b /= 0 then try_next else do
-- check whether the actions for this state fit in the table
ok <- fits off state check
if ok then return off else try_next
where
try_next = findFreeOffset (off+1) check off_arr state
-- This is an inner loop, so we use some strictness hacks, and avoid
-- array bounds checks (unsafeRead instead of readArray) to speed
-- things up a bit.
fits :: Int -> [(Int,Int)] -> STUArray s Int Int -> ST s Bool
fits off [] check = off `seq` check `seq` return True -- strictness hacks
fits off ((t,_):rest) check = do
i <- unsafeRead check (off+t)
if i /= -1 then return False
else fits off rest check
addState :: Int -> STUArray s Int Int -> STUArray s Int Int -> [(Int, Int)]
-> ST s ()
addState _ _ _ [] = return ()
addState off table check ((t,val):state) = do
writeArray table (off+t) val
writeArray check (off+t) t
addState off table check state
findFstFreeSlot :: STUArray s Int Int -> Int -> ST s Int
findFstFreeSlot table n = do
i <- readArray table n
if i == -1 then return n
else findFstFreeSlot table (n+1)
-----------------------------------------------------------------------------
-- Convert an integer to a 16-bit number encoded in \xNN\xNN format suitable
-- for placing in a string (copied from Happy's ProduceCode.lhs)
hexChars16 :: [Int] -> String
hexChars16 acts = concat (map conv16 acts)
where
conv16 i | i > 0x7fff || i < -0x8000
= error ("Internal error: hexChars16: out of range: " ++ show i)
| otherwise
= hexChar16 i
hexChars32 :: [Int] -> String
hexChars32 acts = concat (map conv32 acts)
where
conv32 i = hexChar16 (i .&. 0xffff) ++
hexChar16 ((i `shiftR` 16) .&. 0xffff)
hexChar16 :: Int -> String
hexChar16 i = toHex (i .&. 0xff)
++ toHex ((i `shiftR` 8) .&. 0xff) -- force little-endian
toHex :: Int -> String
toHex i = ['\\','x', hexDig (i `div` 16), hexDig (i `mod` 16)]
hexDig :: Int -> Char
hexDig i | i <= 9 = chr (i + ord '0')
| otherwise = chr (i - 10 + ord 'a')
| beni55/alex | src/Output.hs | bsd-3-clause | 10,844 | 192 | 15 | 2,561 | 2,095 | 1,353 | 742 | -1 | -1 |
{-# LANGUAGE ParallelArrays #-}
{-# OPTIONS -fvectorise #-}
module Vectorised (test) where
import Data.Array.Parallel hiding (Bool, True, False, not, fromBool, toBool)
import Data.Array.Parallel.Prelude hiding (Bool, True, False, not, fromBool, toBool)
import Data.Array.Parallel.Prelude.Int as I
import qualified Prelude as P
data Bool = True | False
toBool :: Int -> Bool
toBool n
| n I.== 0 = False
| otherwise = True
fromBool :: Bool -> Int
fromBool False = 0
fromBool True = 1
not :: Bool -> Bool
not False = True
not True = False
{-# NOINLINE test #-}
test :: PArray Int -> PArray Int
test xs = toPArrayP (mapP test' (fromPArrayP xs))
test' x = fromBool (not (toBool x))
| mainland/dph | dph-examples/examples/smoke/data/Bool/Vectorised.hs | bsd-3-clause | 742 | 0 | 9 | 179 | 244 | 139 | 105 | 22 | 1 |
{-# LANGUAGE CPP, TupleSections #-}
-- |Vectorisation of expressions.
module Vectorise.Exp
( -- * Vectorise right-hand sides of toplevel bindings
vectTopExpr
, vectTopExprs
, vectScalarFun
, vectScalarDFun
)
where
#include "HsVersions.h"
import Vectorise.Type.Type
import Vectorise.Var
import Vectorise.Convert
import Vectorise.Vect
import Vectorise.Env
import Vectorise.Monad
import Vectorise.Builtins
import Vectorise.Utils
import CoreUtils
import MkCore
import CoreSyn
import CoreFVs
import Class
import DataCon
import TyCon
import TcType
import Type
import TyCoRep
import Var
import VarEnv
import VarSet
import NameSet
import Id
import BasicTypes( isStrongLoopBreaker )
import Literal
import TysPrim
import Outputable
import FastString
import DynFlags
import Util
import Control.Monad
import Data.Maybe
import Data.List
-- Main entry point to vectorise expressions -----------------------------------
-- |Vectorise a polymorphic expression that forms a *non-recursive* binding.
--
-- Return 'Nothing' if the expression is scalar; otherwise, the first component of the result
-- (which is of type 'Bool') indicates whether the expression is parallel (i.e., whether it is
-- tagged as 'VIParr').
--
-- We have got the non-recursive case as a special case as it doesn't require to compute
-- vectorisation information twice.
--
vectTopExpr :: Var -> CoreExpr -> VM (Maybe (Bool, Inline, CoreExpr))
vectTopExpr var expr
= do
{ exprVI <- encapsulateScalars <=< vectAvoidInfo emptyVarSet . freeVars $ expr
; if isVIEncaps exprVI
then
return Nothing
else do
{ vExpr <- closedV $
inBind var $
vectAnnPolyExpr False exprVI
; inline <- computeInline exprVI
; return $ Just (isVIParr exprVI, inline, vectorised vExpr)
}
}
-- Compute the inlining hint for the right-hand side of a top-level binding.
--
computeInline :: CoreExprWithVectInfo -> VM Inline
computeInline ((_, VIDict), _) = return $ DontInline
computeInline (_, AnnTick _ expr) = computeInline expr
computeInline expr@(_, AnnLam _ _) = Inline <$> polyArity tvs
where
(tvs, _) = collectAnnTypeBinders expr
computeInline _expr = return $ DontInline
-- |Vectorise a recursive group of top-level polymorphic expressions.
--
-- Return 'Nothing' if the expression group is scalar; otherwise, the first component of the result
-- (which is of type 'Bool') indicates whether the expressions are parallel (i.e., whether they are
-- tagged as 'VIParr').
--
vectTopExprs :: [(Var, CoreExpr)] -> VM (Maybe (Bool, [(Inline, CoreExpr)]))
vectTopExprs binds
= do
{ exprVIs <- mapM (vectAvoidAndEncapsulate emptyVarSet) exprs
; if all isVIEncaps exprVIs
-- if all bindings are scalar => don't vectorise this group of bindings
then return Nothing
else do
{ -- non-scalar bindings need to be vectorised
; let areVIParr = any isVIParr exprVIs
; revised_exprVIs <- if not areVIParr
-- if no binding is parallel => 'exprVIs' is ready for vectorisation
then return exprVIs
-- if any binding is parallel => recompute the vectorisation info
else mapM (vectAvoidAndEncapsulate (mkVarSet vars)) exprs
; vExprs <- zipWithM vect vars revised_exprVIs
; return $ Just (areVIParr, vExprs)
}
}
where
(vars, exprs) = unzip binds
vectAvoidAndEncapsulate pvs = encapsulateScalars <=< vectAvoidInfo pvs . freeVars
vect var exprVI
= do
{ vExpr <- closedV $
inBind var $
vectAnnPolyExpr (isStrongLoopBreaker $ idOccInfo var) exprVI
; inline <- computeInline exprVI
; return (inline, vectorised vExpr)
}
-- |Vectorise a polymorphic expression annotated with vectorisation information.
--
-- The special case of dictionary functions is currently handled separately. (Would be neater to
-- integrate them, though!)
--
vectAnnPolyExpr :: Bool -> CoreExprWithVectInfo -> VM VExpr
vectAnnPolyExpr loop_breaker (_, AnnTick tickish expr)
-- traverse through ticks
= vTick tickish <$> vectAnnPolyExpr loop_breaker expr
vectAnnPolyExpr loop_breaker expr
| isVIDict expr
-- special case the right-hand side of dictionary functions
= (, undefined) <$> vectDictExpr (deAnnotate expr)
| otherwise
-- collect and vectorise type abstractions; then, descent into the body
= polyAbstract tvs $ \args ->
mapVect (mkLams $ tvs ++ args) <$> vectFnExpr False loop_breaker mono
where
(tvs, mono) = collectAnnTypeBinders expr
-- Encapsulate every purely sequential subexpression of a (potentially) parallel expression into a
-- lambda abstraction over all its free variables followed by the corresponding application to those
-- variables. We can, then, avoid the vectorisation of the ensapsulated subexpressions.
--
-- Preconditions:
--
-- * All free variables and the result type must be /simple/ types.
-- * The expression is sufficiently complex (to warrant special treatment). For now, that is
-- every expression that is not constant and contains at least one operation.
--
--
-- The user has an option to choose between aggressive and minimal vectorisation avoidance. With
-- minimal vectorisation avoidance, we only encapsulate individual scalar operations. With
-- aggressive vectorisation avoidance, we encapsulate subexpression that are as big as possible.
--
encapsulateScalars :: CoreExprWithVectInfo -> VM CoreExprWithVectInfo
encapsulateScalars ce@(_, AnnType _ty)
= return ce
encapsulateScalars ce@((_, VISimple), AnnVar _v)
-- NB: diverts from the paper: encapsulate scalar variables (including functions)
= liftSimpleAndCase ce
encapsulateScalars ce@(_, AnnVar _v)
= return ce
encapsulateScalars ce@(_, AnnLit _)
= return ce
encapsulateScalars ((fvs, vi), AnnTick tck expr)
= do
{ encExpr <- encapsulateScalars expr
; return ((fvs, vi), AnnTick tck encExpr)
}
encapsulateScalars ce@((fvs, vi), AnnLam bndr expr)
= do
{ vectAvoid <- isVectAvoidanceAggressive
; varsS <- allScalarVarTypeSet fvs
-- NB: diverts from the paper: we need to check the scalarness of bound variables as well,
-- as 'vectScalarFun' will handle them just the same as those introduced for the 'fvs'
-- by encapsulation.
; bndrsS <- allScalarVarType bndrs
; case (vi, vectAvoid && varsS && bndrsS) of
(VISimple, True) -> liftSimpleAndCase ce
_ -> do
{ encExpr <- encapsulateScalars expr
; return ((fvs, vi), AnnLam bndr encExpr)
}
}
where
(bndrs, _) = collectAnnBndrs ce
encapsulateScalars ce@((fvs, vi), AnnApp ce1 ce2)
= do
{ vectAvoid <- isVectAvoidanceAggressive
; varsS <- allScalarVarTypeSet fvs
; case (vi, (vectAvoid || isSimpleApplication ce) && varsS) of
(VISimple, True) -> liftSimpleAndCase ce
_ -> do
{ encCe1 <- encapsulateScalars ce1
; encCe2 <- encapsulateScalars ce2
; return ((fvs, vi), AnnApp encCe1 encCe2)
}
}
where
isSimpleApplication :: CoreExprWithVectInfo -> Bool
isSimpleApplication (_, AnnTick _ ce) = isSimpleApplication ce
isSimpleApplication (_, AnnCast ce _) = isSimpleApplication ce
isSimpleApplication ce | isSimple ce = True
isSimpleApplication (_, AnnApp ce1 ce2) = isSimple ce1 && isSimpleApplication ce2
isSimpleApplication _ = False
--
isSimple :: CoreExprWithVectInfo -> Bool
isSimple (_, AnnType {}) = True
isSimple (_, AnnVar {}) = True
isSimple (_, AnnLit {}) = True
isSimple (_, AnnTick _ ce) = isSimple ce
isSimple (_, AnnCast ce _) = isSimple ce
isSimple _ = False
encapsulateScalars ce@((fvs, vi), AnnCase scrut bndr ty alts)
= do
{ vectAvoid <- isVectAvoidanceAggressive
; varsS <- allScalarVarTypeSet fvs
; case (vi, vectAvoid && varsS) of
(VISimple, True) -> liftSimpleAndCase ce
_ -> do
{ encScrut <- encapsulateScalars scrut
; encAlts <- mapM encAlt alts
; return ((fvs, vi), AnnCase encScrut bndr ty encAlts)
}
}
where
encAlt (con, bndrs, expr) = (con, bndrs,) <$> encapsulateScalars expr
encapsulateScalars ce@((fvs, vi), AnnLet (AnnNonRec bndr expr1) expr2)
= do
{ vectAvoid <- isVectAvoidanceAggressive
; varsS <- allScalarVarTypeSet fvs
; case (vi, vectAvoid && varsS) of
(VISimple, True) -> liftSimpleAndCase ce
_ -> do
{ encExpr1 <- encapsulateScalars expr1
; encExpr2 <- encapsulateScalars expr2
; return ((fvs, vi), AnnLet (AnnNonRec bndr encExpr1) encExpr2)
}
}
encapsulateScalars ce@((fvs, vi), AnnLet (AnnRec binds) expr)
= do
{ vectAvoid <- isVectAvoidanceAggressive
; varsS <- allScalarVarTypeSet fvs
; case (vi, vectAvoid && varsS) of
(VISimple, True) -> liftSimpleAndCase ce
_ -> do
{ encBinds <- mapM encBind binds
; encExpr <- encapsulateScalars expr
; return ((fvs, vi), AnnLet (AnnRec encBinds) encExpr)
}
}
where
encBind (bndr, expr) = (bndr,) <$> encapsulateScalars expr
encapsulateScalars ((fvs, vi), AnnCast expr coercion)
= do
{ encExpr <- encapsulateScalars expr
; return ((fvs, vi), AnnCast encExpr coercion)
}
encapsulateScalars _
= panic "Vectorise.Exp.encapsulateScalars: unknown constructor"
-- Lambda-lift the given simple expression and apply it to the abstracted free variables.
--
-- If the expression is a case expression scrutinising anything, but a scalar type, then lift
-- each alternative individually.
--
liftSimpleAndCase :: CoreExprWithVectInfo -> VM CoreExprWithVectInfo
liftSimpleAndCase aexpr@((fvs, _vi), AnnCase expr bndr t alts)
= do
{ vi <- vectAvoidInfoTypeOf expr
; if (vi == VISimple)
then
liftSimple aexpr -- if the scrutinee is scalar, we need no special treatment
else do
{ alts' <- mapM (\(ac, bndrs, aexpr) -> (ac, bndrs,) <$> liftSimpleAndCase aexpr) alts
; return ((fvs, vi), AnnCase expr bndr t alts')
}
}
liftSimpleAndCase aexpr = liftSimple aexpr
liftSimple :: CoreExprWithVectInfo -> VM CoreExprWithVectInfo
liftSimple ((fvs, vi), AnnVar v)
| v `elemDVarSet` fvs -- special case to avoid producing: (\v -> v) v
&& not (isToplevel v) -- NB: if 'v' not free or is toplevel, we must get the 'VIEncaps'
= return $ ((fvs, vi), AnnVar v)
liftSimple aexpr@((fvs_orig, VISimple), expr)
= do
{ let liftedExpr = mkAnnApps (mkAnnLams (reverse vars) fvs expr) vars
; traceVt "encapsulate:" $ ppr (deAnnotate aexpr) $$ text "==>" $$ ppr (deAnnotate liftedExpr)
; return $ liftedExpr
}
where
vars = dVarSetElems fvs
fvs = filterDVarSet (not . isToplevel) fvs_orig -- only include 'Id's that are not toplevel
mkAnnLams :: [Var] -> DVarSet -> AnnExpr' Var (DVarSet, VectAvoidInfo) -> CoreExprWithVectInfo
mkAnnLams [] fvs expr = ASSERT(isEmptyDVarSet fvs)
((emptyDVarSet, VIEncaps), expr)
mkAnnLams (v:vs) fvs expr = mkAnnLams vs (fvs `delDVarSet` v) (AnnLam v ((fvs, VIEncaps), expr))
mkAnnApps :: CoreExprWithVectInfo -> [Var] -> CoreExprWithVectInfo
mkAnnApps aexpr [] = aexpr
mkAnnApps aexpr (v:vs) = mkAnnApps (mkAnnApp aexpr v) vs
mkAnnApp :: CoreExprWithVectInfo -> Var -> CoreExprWithVectInfo
mkAnnApp aexpr@((fvs, _vi), _expr) v
= ((fvs `extendDVarSet` v, VISimple), AnnApp aexpr ((unitDVarSet v, VISimple), AnnVar v))
liftSimple aexpr
= pprPanic "Vectorise.Exp.liftSimple: not simple" $ ppr (deAnnotate aexpr)
isToplevel :: Var -> Bool
isToplevel v | isId v = case realIdUnfolding v of
NoUnfolding -> False
OtherCon {} -> True
DFunUnfolding {} -> True
CoreUnfolding {uf_is_top = top} -> top
| otherwise = False
-- |Vectorise an expression.
--
vectExpr :: CoreExprWithVectInfo -> VM VExpr
vectExpr aexpr
-- encapsulated expression of functional type => try to vectorise as a scalar subcomputation
| (isFunTy . annExprType $ aexpr) && isVIEncaps aexpr
= vectFnExpr True False aexpr
-- encapsulated constant => vectorise as a scalar constant
| isVIEncaps aexpr
= traceVt "vectExpr (encapsulated constant):" (ppr . deAnnotate $ aexpr) >>
vectConst (deAnnotate aexpr)
vectExpr (_, AnnVar v)
= vectVar v
vectExpr (_, AnnLit lit)
= vectConst $ Lit lit
vectExpr aexpr@(_, AnnLam _ _)
= traceVt "vectExpr [AnnLam]:" (ppr . deAnnotate $ aexpr) >>
vectFnExpr True False aexpr
-- SPECIAL CASE: Vectorise/lift 'patError @ ty err' by only vectorising/lifting the type 'ty';
-- its only purpose is to abort the program, but we need to adjust the type to keep CoreLint
-- happy.
-- FIXME: can't be do this with a VECTORISE pragma on 'pAT_ERROR_ID' now?
vectExpr (_, AnnApp (_, AnnApp (_, AnnVar v) (_, AnnType ty)) err)
| v == pAT_ERROR_ID
= do
{ (vty, lty) <- vectAndLiftType ty
; return (mkCoreApps (Var v) [Type (getRuntimeRep "vectExpr" vty), Type vty, err'], mkCoreApps (Var v) [Type lty, err'])
}
where
err' = deAnnotate err
-- type application (handle multiple consecutive type applications simultaneously to ensure the
-- PA dictionaries are put at the right places)
vectExpr e@(_, AnnApp _ arg)
| isAnnTypeArg arg
= vectPolyApp e
-- Lifted literal
vectExpr (_, AnnApp (_, AnnVar v) (_, AnnLit lit))
| Just _con <- isDataConId_maybe v
= do
{ let vexpr = App (Var v) (Lit lit)
; lexpr <- liftPD vexpr
; return (vexpr, lexpr)
}
-- value application (dictionary or user value)
vectExpr e@(_, AnnApp fn arg)
| isPredTy arg_ty -- dictionary application (whose result is not a dictionary)
= vectPolyApp e
| otherwise -- user value
= do
{ -- vectorise the types
; varg_ty <- vectType arg_ty
; vres_ty <- vectType res_ty
-- vectorise the function and argument expression
; vfn <- vectExpr fn
; varg <- vectExpr arg
-- the vectorised function is a closure; apply it to the vectorised argument
; mkClosureApp varg_ty vres_ty vfn varg
}
where
(arg_ty, res_ty) = splitFunTy . exprType $ deAnnotate fn
vectExpr (_, AnnCase scrut bndr ty alts)
| Just (tycon, ty_args) <- splitTyConApp_maybe scrut_ty
, isAlgTyCon tycon
= vectAlgCase tycon ty_args scrut bndr ty alts
| otherwise
= do
{ dflags <- getDynFlags
; cantVectorise dflags "Can't vectorise expression (no algebraic type constructor)" $
ppr scrut_ty
}
where
scrut_ty = exprType (deAnnotate scrut)
vectExpr (_, AnnLet (AnnNonRec bndr rhs) body)
= do
{ traceVt "let binding (non-recursive)" Outputable.empty
; vrhs <- localV $
inBind bndr $
vectAnnPolyExpr False rhs
; traceVt "let body (non-recursive)" Outputable.empty
; (vbndr, vbody) <- vectBndrIn bndr (vectExpr body)
; return $ vLet (vNonRec vbndr vrhs) vbody
}
vectExpr (_, AnnLet (AnnRec bs) body)
= do
{ (vbndrs, (vrhss, vbody)) <- vectBndrsIn bndrs $ do
{ traceVt "let bindings (recursive)" Outputable.empty
; vrhss <- zipWithM vect_rhs bndrs rhss
; traceVt "let body (recursive)" Outputable.empty
; vbody <- vectExpr body
; return (vrhss, vbody)
}
; return $ vLet (vRec vbndrs vrhss) vbody
}
where
(bndrs, rhss) = unzip bs
vect_rhs bndr rhs = localV $
inBind bndr $
vectAnnPolyExpr (isStrongLoopBreaker $ idOccInfo bndr) rhs
vectExpr (_, AnnTick tickish expr)
= vTick tickish <$> vectExpr expr
vectExpr (_, AnnType ty)
= vType <$> vectType ty
vectExpr e
= do
{ dflags <- getDynFlags
; cantVectorise dflags "Can't vectorise expression (vectExpr)" $ ppr (deAnnotate e)
}
-- |Vectorise an expression that *may* have an outer lambda abstraction. If the expression is marked
-- as encapsulated ('VIEncaps'), vectorise it as a scalar computation (using a generalised scalar
-- zip).
--
-- We do not handle type variables at this point, as they will already have been stripped off by
-- 'vectPolyExpr'. We also only have to worry about one set of dictionary arguments as we (1) only
-- deal with Haskell 2011 and (2) class selectors are vectorised elsewhere.
--
vectFnExpr :: Bool -- ^If we process the RHS of a binding, whether that binding
-- should be inlined
-> Bool -- ^Whether the binding is a loop breaker
-> CoreExprWithVectInfo -- ^Expression to vectorise; must have an outer `AnnLam`
-> VM VExpr
vectFnExpr inline loop_breaker aexpr@(_ann, AnnLam bndr body)
-- predicate abstraction: leave as a normal abstraction, but vectorise the predicate type
| isId bndr
&& isPredTy (idType bndr)
= do
{ vBndr <- vectBndr bndr
; vbody <- vectFnExpr inline loop_breaker body
; return $ mapVect (mkLams [vectorised vBndr]) vbody
}
-- encapsulated non-predicate abstraction: vectorise as a scalar computation
| isId bndr && isVIEncaps aexpr
= vectScalarFun . deAnnotate $ aexpr
-- non-predicate abstraction: vectorise as a non-scalar computation
| isId bndr
= vectLam inline loop_breaker aexpr
| otherwise
= do
{ dflags <- getDynFlags
; cantVectorise dflags "Vectorise.Exp.vectFnExpr: Unexpected type lambda" $
ppr (deAnnotate aexpr)
}
vectFnExpr _ _ aexpr
-- encapsulated function: vectorise as a scalar computation
| (isFunTy . annExprType $ aexpr) && isVIEncaps aexpr
= vectScalarFun . deAnnotate $ aexpr
| otherwise
-- not an abstraction: vectorise as a non-scalar vanilla expression
-- NB: we can get here due to the recursion in the first case above and from 'vectAnnPolyExpr'
= vectExpr aexpr
-- |Vectorise type and dictionary applications.
--
-- These are always headed by a variable (as we don't support higher-rank polymorphism), but may
-- involve two sets of type variables and dictionaries. Consider,
--
-- > class C a where
-- > m :: D b => b -> a
--
-- The type of 'm' is 'm :: forall a. C a => forall b. D b => b -> a'.
--
vectPolyApp :: CoreExprWithVectInfo -> VM VExpr
vectPolyApp e0
= case e4 of
(_, AnnVar var)
-> do { -- get the vectorised form of the variable
; vVar <- lookupVar var
; traceVt "vectPolyApp of" (ppr var)
-- vectorise type and dictionary arguments
; vDictsOuter <- mapM vectDictExpr (map deAnnotate dictsOuter)
; vDictsInner <- mapM vectDictExpr (map deAnnotate dictsInner)
; vTysOuter <- mapM vectType tysOuter
; vTysInner <- mapM vectType tysInner
; let reconstructOuter v = (`mkApps` vDictsOuter) <$> polyApply v vTysOuter
; case vVar of
Local (vv, lv)
-> do { MASSERT( null dictsInner ) -- local vars cannot be class selectors
; traceVt " LOCAL" (text "")
; (,) <$> reconstructOuter (Var vv) <*> reconstructOuter (Var lv)
}
Global vv
| isDictComp var -- dictionary computation
-> do { -- in a dictionary computation, the innermost, non-empty set of
-- arguments are non-vectorised arguments, where no 'PA'dictionaries
-- are needed for the type variables
; ve <- if null dictsInner
then
return $ Var vv `mkTyApps` vTysOuter `mkApps` vDictsOuter
else
reconstructOuter
(Var vv `mkTyApps` vTysInner `mkApps` vDictsInner)
; traceVt " GLOBAL (dict):" (ppr ve)
; vectConst ve
}
| otherwise -- non-dictionary computation
-> do { MASSERT( null dictsInner )
; ve <- reconstructOuter (Var vv)
; traceVt " GLOBAL (non-dict):" (ppr ve)
; vectConst ve
}
}
_ -> pprSorry "Cannot vectorise programs with higher-rank types:" (ppr . deAnnotate $ e0)
where
-- if there is only one set of variables or dictionaries, it will be the outer set
(e1, dictsOuter) = collectAnnDictArgs e0
(e2, tysOuter) = collectAnnTypeArgs e1
(e3, dictsInner) = collectAnnDictArgs e2
(e4, tysInner) = collectAnnTypeArgs e3
--
isDictComp var = (isJust . isClassOpId_maybe $ var) || isDFunId var
-- |Vectorise the body of a dfun.
--
-- Dictionary computations are special for the following reasons. The application of dictionary
-- functions are always saturated, so there is no need to create closures. Dictionary computations
-- don't depend on array values, so they are always scalar computations whose result we can
-- replicate (instead of executing them in parallel).
--
-- NB: To keep things simple, we are not rewriting any of the bindings introduced in a dictionary
-- computation. Consequently, the variable case needs to deal with cases where binders are
-- in the vectoriser environments and where that is not the case.
--
vectDictExpr :: CoreExpr -> VM CoreExpr
vectDictExpr (Var var)
= do { mb_scope <- lookupVar_maybe var
; case mb_scope of
Nothing -> return $ Var var -- binder from within the dict. computation
Just (Local (vVar, _)) -> return $ Var vVar -- local vectorised variable
Just (Global vVar) -> return $ Var vVar -- global vectorised variable
}
vectDictExpr (Lit lit)
= pprPanic "Vectorise.Exp.vectDictExpr: literal in dictionary computation" (ppr lit)
vectDictExpr (Lam bndr e)
= Lam bndr <$> vectDictExpr e
vectDictExpr (App fn arg)
= App <$> vectDictExpr fn <*> vectDictExpr arg
vectDictExpr (Case e bndr ty alts)
= Case <$> vectDictExpr e <*> pure bndr <*> vectType ty <*> mapM vectDictAlt alts
where
vectDictAlt (con, bs, e) = (,,) <$> vectDictAltCon con <*> pure bs <*> vectDictExpr e
--
vectDictAltCon (DataAlt datacon) = DataAlt <$> maybeV dataConErr (lookupDataCon datacon)
where
dataConErr = text "Cannot vectorise data constructor:" <+> ppr datacon
vectDictAltCon (LitAlt lit) = return $ LitAlt lit
vectDictAltCon DEFAULT = return DEFAULT
vectDictExpr (Let bnd body)
= Let <$> vectDictBind bnd <*> vectDictExpr body
where
vectDictBind (NonRec bndr e) = NonRec bndr <$> vectDictExpr e
vectDictBind (Rec bnds) = Rec <$> mapM (\(bndr, e) -> (bndr,) <$> vectDictExpr e) bnds
vectDictExpr e@(Cast _e _coe)
= pprSorry "Vectorise.Exp.vectDictExpr: cast" (ppr e)
vectDictExpr (Tick tickish e)
= Tick tickish <$> vectDictExpr e
vectDictExpr (Type ty)
= Type <$> vectType ty
vectDictExpr (Coercion coe)
= pprSorry "Vectorise.Exp.vectDictExpr: coercion" (ppr coe)
-- |Vectorise an expression of functional type, where all arguments and the result are of primitive
-- types (i.e., 'Int', 'Float', 'Double' etc., which have instances of the 'Scalar' type class) and
-- which does not contain any subcomputations that involve parallel arrays. Such functionals do not
-- require the full blown vectorisation transformation; instead, they can be lifted by application
-- of a member of the zipWith family (i.e., 'map', 'zipWith', zipWith3', etc.)
--
-- Dictionary functions are also scalar functions (as dictionaries themselves are not vectorised,
-- instead they become dictionaries of vectorised methods). We treat them differently, though see
-- "Note [Scalar dfuns]" in 'Vectorise'.
--
vectScalarFun :: CoreExpr -> VM VExpr
vectScalarFun expr
= do
{ traceVt "vectScalarFun:" (ppr expr)
; let (arg_tys, res_ty) = splitFunTys (exprType expr)
; mkScalarFun arg_tys res_ty expr
}
-- Generate code for a scalar function by generating a scalar closure. If the function is a
-- dictionary function, vectorise it as dictionary code.
--
mkScalarFun :: [Type] -> Type -> CoreExpr -> VM VExpr
mkScalarFun arg_tys res_ty expr
| isPredTy res_ty
= do { vExpr <- vectDictExpr expr
; return (vExpr, unused)
}
| otherwise
= do { traceVt "mkScalarFun: " $ ppr expr $$ text " ::" <+>
ppr (mkFunTys arg_tys res_ty)
; fn_var <- hoistExpr (fsLit "fn") expr DontInline
; zipf <- zipScalars arg_tys res_ty
; clo <- scalarClosure arg_tys res_ty (Var fn_var) (zipf `App` Var fn_var)
; clo_var <- hoistExpr (fsLit "clo") clo DontInline
; lclo <- liftPD (Var clo_var)
; return (Var clo_var, lclo)
}
where
unused = error "Vectorise.Exp.mkScalarFun: we don't lift dictionary expressions"
-- |Vectorise a dictionary function that has a 'VECTORISE SCALAR instance' pragma.
--
-- In other words, all methods in that dictionary are scalar functions — to be vectorised with
-- 'vectScalarFun'. The dictionary "function" itself may be a constant, though.
--
-- NB: You may think that we could implement this function guided by the struture of the Core
-- expression of the right-hand side of the dictionary function. We cannot proceed like this as
-- 'vectScalarDFun' must also work for *imported* dfuns, where we don't necessarily have access
-- to the Core code of the unvectorised dfun.
--
-- Here an example — assume,
--
-- > class Eq a where { (==) :: a -> a -> Bool }
-- > instance (Eq a, Eq b) => Eq (a, b) where { (==) = ... }
-- > {-# VECTORISE SCALAR instance Eq (a, b) }
--
-- The unvectorised dfun for the above instance has the following signature:
--
-- > $dEqPair :: forall a b. Eq a -> Eq b -> Eq (a, b)
--
-- We generate the following (scalar) vectorised dfun (liberally using TH notation):
--
-- > $v$dEqPair :: forall a b. V:Eq a -> V:Eq b -> V:Eq (a, b)
-- > $v$dEqPair = /\a b -> \dEqa :: V:Eq a -> \dEqb :: V:Eq b ->
-- > D:V:Eq $(vectScalarFun True recFns
-- > [| (==) @(a, b) ($dEqPair @a @b $(unVect dEqa) $(unVect dEqb)) |])
--
-- NB:
-- * '(,)' vectorises to '(,)' — hence, the type constructor in the result type remains the same.
-- * We share the '$(unVect di)' sub-expressions between the different selectors, but duplicate
-- the application of the unvectorised dfun, to enable the dictionary selection rules to fire.
--
vectScalarDFun :: Var -- ^ Original dfun
-> VM CoreExpr
vectScalarDFun var
= do { -- bring the type variables into scope
; mapM_ defLocalTyVar tvs
-- vectorise dictionary argument types and generate variables for them
; vTheta <- mapM vectType theta
; vThetaBndr <- mapM (newLocalVar (fsLit "vd")) vTheta
; let vThetaVars = varsToCoreExprs vThetaBndr
-- vectorise superclass dictionaries and methods as scalar expressions
; thetaVars <- mapM (newLocalVar (fsLit "d")) theta
; thetaExprs <- zipWithM unVectDict theta vThetaVars
; let thetaDictBinds = zipWith NonRec thetaVars thetaExprs
dict = Var var `mkTyApps` (mkTyVarTys tvs) `mkVarApps` thetaVars
scsOps = map (\selId -> varToCoreExpr selId `mkTyApps` tys `mkApps` [dict])
selIds
; vScsOps <- mapM (\e -> vectorised <$> vectScalarFun e) scsOps
-- vectorised applications of the class-dictionary data constructor
; Just vDataCon <- lookupDataCon dataCon
; vTys <- mapM vectType tys
; let vBody = thetaDictBinds `mkLets` mkCoreConApps vDataCon (map Type vTys ++ vScsOps)
; return $ mkLams (tvs ++ vThetaBndr) vBody
}
where
ty = varType var
(tvs, theta, pty) = tcSplitSigmaTy ty -- 'theta' is the instance context
(cls, tys) = tcSplitDFunHead pty -- 'pty' is the instance head
selIds = classAllSelIds cls
dataCon = classDataCon cls
-- Build a value of the dictionary before vectorisation from original, unvectorised type and an
-- expression computing the vectorised dictionary.
--
-- Given the vectorised version of a dictionary 'vd :: V:C vt1..vtn', generate code that computes
-- the unvectorised version, thus:
--
-- > D:C op1 .. opm
-- > where
-- > opi = $(fromVect opTyi [| vSeli @vt1..vtk vd |])
--
-- where 'opTyi' is the type of the i-th superclass or op of the unvectorised dictionary.
--
unVectDict :: Type -> CoreExpr -> VM CoreExpr
unVectDict ty e
= do { vTys <- mapM vectType tys
; let meths = map (\sel -> Var sel `mkTyApps` vTys `mkApps` [e]) selIds
; scOps <- zipWithM fromVect methTys meths
; return $ mkCoreConApps dataCon (map Type tys ++ scOps)
}
where
(tycon, tys) = splitTyConApp ty
Just dataCon = isDataProductTyCon_maybe tycon
Just cls = tyConClass_maybe tycon
methTys = dataConInstArgTys dataCon tys
selIds = classAllSelIds cls
-- Vectorise an 'n'-ary lambda abstraction by building a set of 'n' explicit closures.
--
-- All non-dictionary free variables go into the closure's environment, whereas the dictionary
-- variables are passed explicit (as conventional arguments) into the body during closure
-- construction.
--
vectLam :: Bool -- ^ Should the RHS of a binding be inlined?
-> Bool -- ^ Whether the binding is a loop breaker.
-> CoreExprWithVectInfo -- ^ Body of abstraction.
-> VM VExpr
vectLam inline loop_breaker expr@((fvs, _vi), AnnLam _ _)
= do { traceVt "fully vectorise a lambda expression" (ppr . deAnnotate $ expr)
; let (bndrs, body) = collectAnnValBinders expr
-- grab the in-scope type variables
; tyvars <- localTyVars
-- collect and vectorise all /local/ free variables
; vfvs <- readLEnv $ \env ->
[ (var, fromJust mb_vv)
| var <- dVarSetElems fvs
, let mb_vv = lookupVarEnv (local_vars env) var
, isJust mb_vv -- its local == is in local var env
]
-- separate dictionary from non-dictionary variables in the free variable set
; let (vvs_dict, vvs_nondict) = partition (isPredTy . varType . fst) vfvs
(_fvs_dict, vfvs_dict) = unzip vvs_dict
(fvs_nondict, vfvs_nondict) = unzip vvs_nondict
-- compute the type of the vectorised closure
; arg_tys <- mapM (vectType . idType) bndrs
; res_ty <- vectType (exprType $ deAnnotate body)
; let arity = length fvs_nondict + length bndrs
vfvs_dict' = map vectorised vfvs_dict
; buildClosures tyvars vfvs_dict' vfvs_nondict arg_tys res_ty
. hoistPolyVExpr tyvars vfvs_dict' (maybe_inline arity)
$ do { -- generate the vectorised body of the lambda abstraction
; lc <- builtin liftingContext
; (vbndrs, vbody) <- vectBndrsIn (fvs_nondict ++ bndrs) $ vectExpr body
; vbody' <- break_loop lc res_ty vbody
; return $ vLams lc vbndrs vbody'
}
}
where
maybe_inline n | inline = Inline n
| otherwise = DontInline
-- If this is the body of a binding marked as a loop breaker, add a recursion termination test
-- to the /lifted/ version of the function body. The termination tests checks if the lifting
-- context is empty. If so, it returns an empty array of the (lifted) result type instead of
-- executing the function body. This is the test from the last line (defining \mathcal{L}')
-- in Figure 6 of HtM.
break_loop lc ty (ve, le)
| loop_breaker
= do { dflags <- getDynFlags
; empty <- emptyPD ty
; lty <- mkPDataType ty
; return (ve, mkWildCase (Var lc) intPrimTy lty
[(DEFAULT, [], le),
(LitAlt (mkMachInt dflags 0), [], empty)])
}
| otherwise = return (ve, le)
vectLam _ _ _ = panic "Vectorise.Exp.vectLam: not a lambda"
-- Vectorise an algebraic case expression.
--
-- We convert
--
-- case e :: t of v { ... }
--
-- to
--
-- V: let v' = e in case v' of _ { ... }
-- L: let v' = e in case v' `cast` ... of _ { ... }
--
-- When lifting, we have to do it this way because v must have the type
-- [:V(T):] but the scrutinee must be cast to the representation type. We also
-- have to handle the case where v is a wild var correctly.
--
-- FIXME: this is too lazy...is it?
vectAlgCase :: TyCon -> [Type] -> CoreExprWithVectInfo -> Var -> Type
-> [(AltCon, [Var], CoreExprWithVectInfo)]
-> VM VExpr
vectAlgCase _tycon _ty_args scrut bndr ty [(DEFAULT, [], body)]
= do
{ traceVt "scrutinee (DEFAULT only)" Outputable.empty
; vscrut <- vectExpr scrut
; (vty, lty) <- vectAndLiftType ty
; traceVt "alternative body (DEFAULT only)" Outputable.empty
; (vbndr, vbody) <- vectBndrIn bndr (vectExpr body)
; return $ vCaseDEFAULT vscrut vbndr vty lty vbody
}
vectAlgCase _tycon _ty_args scrut bndr ty [(DataAlt _, [], body)]
= do
{ traceVt "scrutinee (one shot w/o binders)" Outputable.empty
; vscrut <- vectExpr scrut
; (vty, lty) <- vectAndLiftType ty
; traceVt "alternative body (one shot w/o binders)" Outputable.empty
; (vbndr, vbody) <- vectBndrIn bndr (vectExpr body)
; return $ vCaseDEFAULT vscrut vbndr vty lty vbody
}
vectAlgCase _tycon _ty_args scrut bndr ty [(DataAlt dc, bndrs, body)]
= do
{ traceVt "scrutinee (one shot w/ binders)" Outputable.empty
; vexpr <- vectExpr scrut
; (vty, lty) <- vectAndLiftType ty
; traceVt "alternative body (one shot w/ binders)" Outputable.empty
; (vbndr, (vbndrs, (vect_body, lift_body)))
<- vect_scrut_bndr
. vectBndrsIn bndrs
$ vectExpr body
; let (vect_bndrs, lift_bndrs) = unzip vbndrs
; (vscrut, lscrut, pdata_dc) <- pdataUnwrapScrut (vVar vbndr)
; vect_dc <- maybeV dataConErr (lookupDataCon dc)
; let vcase = mk_wild_case vscrut vty vect_dc vect_bndrs vect_body
lcase = mk_wild_case lscrut lty pdata_dc lift_bndrs lift_body
; return $ vLet (vNonRec vbndr vexpr) (vcase, lcase)
}
where
vect_scrut_bndr | isDeadBinder bndr = vectBndrNewIn bndr (fsLit "scrut")
| otherwise = vectBndrIn bndr
mk_wild_case expr ty dc bndrs body
= mkWildCase expr (exprType expr) ty [(DataAlt dc, bndrs, body)]
dataConErr = (text "vectAlgCase: data constructor not vectorised" <+> ppr dc)
vectAlgCase tycon _ty_args scrut bndr ty alts
= do
{ traceVt "scrutinee (general case)" Outputable.empty
; vexpr <- vectExpr scrut
; vect_tc <- vectTyCon tycon
; (vty, lty) <- vectAndLiftType ty
; let arity = length (tyConDataCons vect_tc)
; sel_ty <- builtin (selTy arity)
; sel_bndr <- newLocalVar (fsLit "sel") sel_ty
; let sel = Var sel_bndr
; traceVt "alternatives' body (general case)" Outputable.empty
; (vbndr, valts) <- vect_scrut_bndr
$ mapM (proc_alt arity sel vty lty) alts'
; let (vect_dcs, vect_bndrss, lift_bndrss, vbodies) = unzip4 valts
; (vect_scrut, lift_scrut, pdata_dc) <- pdataUnwrapScrut (vVar vbndr)
; let (vect_bodies, lift_bodies) = unzip vbodies
; vdummy <- newDummyVar (exprType vect_scrut)
; ldummy <- newDummyVar (exprType lift_scrut)
; let vect_case = Case vect_scrut vdummy vty
(zipWith3 mk_vect_alt vect_dcs vect_bndrss vect_bodies)
; lc <- builtin liftingContext
; lbody <- combinePD vty (Var lc) sel lift_bodies
; let lift_case = Case lift_scrut ldummy lty
[(DataAlt pdata_dc, sel_bndr : concat lift_bndrss,
lbody)]
; return . vLet (vNonRec vbndr vexpr)
$ (vect_case, lift_case)
}
where
vect_scrut_bndr | isDeadBinder bndr = vectBndrNewIn bndr (fsLit "scrut")
| otherwise = vectBndrIn bndr
alts' = sortBy (\(alt1, _, _) (alt2, _, _) -> cmp alt1 alt2) alts
cmp (DataAlt dc1) (DataAlt dc2) = dataConTag dc1 `compare` dataConTag dc2
cmp DEFAULT DEFAULT = EQ
cmp DEFAULT _ = LT
cmp _ DEFAULT = GT
cmp _ _ = panic "vectAlgCase/cmp"
proc_alt arity sel _ lty (DataAlt dc, bndrs, body@((fvs_body, _), _))
= do
dflags <- getDynFlags
vect_dc <- maybeV dataConErr (lookupDataCon dc)
let ntag = dataConTagZ vect_dc
tag = mkDataConTag dflags vect_dc
fvs = fvs_body `delDVarSetList` bndrs
sel_tags <- liftM (`App` sel) (builtin (selTags arity))
lc <- builtin liftingContext
elems <- builtin (selElements arity ntag)
(vbndrs, vbody)
<- vectBndrsIn bndrs
. localV
$ do
{ binds <- mapM (pack_var (Var lc) sel_tags tag)
. filter isLocalId
$ dVarSetElems fvs
; traceVt "case alternative:" (ppr . deAnnotate $ body)
; (ve, le) <- vectExpr body
; return (ve, Case (elems `App` sel) lc lty
[(DEFAULT, [], (mkLets (concat binds) le))])
}
-- empty <- emptyPD vty
-- return (ve, Case (elems `App` sel) lc lty
-- [(DEFAULT, [], Let (NonRec flags_var flags_expr)
-- $ mkLets (concat binds) le),
-- (LitAlt (mkMachInt 0), [], empty)])
let (vect_bndrs, lift_bndrs) = unzip vbndrs
return (vect_dc, vect_bndrs, lift_bndrs, vbody)
where
dataConErr = (text "vectAlgCase: data constructor not vectorised" <+> ppr dc)
proc_alt _ _ _ _ _ = panic "vectAlgCase/proc_alt"
mk_vect_alt vect_dc bndrs body = (DataAlt vect_dc, bndrs, body)
-- Pack a variable for a case alternative context *if* the variable is vectorised. If it
-- isn't, ignore it as scalar variables don't need to be packed.
pack_var len tags t v
= do
{ r <- lookupVar_maybe v
; case r of
Just (Local (vv, lv)) ->
do
{ lv' <- cloneVar lv
; expr <- packByTagPD (idType vv) (Var lv) len tags t
; updLEnv (\env -> env { local_vars = extendVarEnv (local_vars env) v (vv, lv') })
; return [(NonRec lv' expr)]
}
_ -> return []
}
-- Support to compute information for vectorisation avoidance ------------------
-- Annotation for Core AST nodes that describes how they should be handled during vectorisation
-- and especially if vectorisation of the corresponding computation can be avoided.
--
data VectAvoidInfo = VIParr -- tree contains parallel computations
| VISimple -- result type is scalar & no parallel subcomputation
| VIComplex -- any result type, no parallel subcomputation
| VIEncaps -- tree encapsulated by 'liftSimple'
| VIDict -- dictionary computation (never parallel)
deriving (Eq, Show)
-- Core expression annotated with free variables and vectorisation-specific information.
--
type CoreExprWithVectInfo = AnnExpr Id (DVarSet, VectAvoidInfo)
-- Yield the type of an annotated core expression.
--
annExprType :: AnnExpr Var ann -> Type
annExprType = exprType . deAnnotate
-- Project the vectorisation information from an annotated Core expression.
--
vectAvoidInfoOf :: CoreExprWithVectInfo -> VectAvoidInfo
vectAvoidInfoOf ((_, vi), _) = vi
-- Is this a 'VIParr' node?
--
isVIParr :: CoreExprWithVectInfo -> Bool
isVIParr = (== VIParr) . vectAvoidInfoOf
-- Is this a 'VIEncaps' node?
--
isVIEncaps :: CoreExprWithVectInfo -> Bool
isVIEncaps = (== VIEncaps) . vectAvoidInfoOf
-- Is this a 'VIDict' node?
--
isVIDict :: CoreExprWithVectInfo -> Bool
isVIDict = (== VIDict) . vectAvoidInfoOf
-- 'VIParr' if either argument is 'VIParr'; otherwise, the first argument.
--
unlessVIParr :: VectAvoidInfo -> VectAvoidInfo -> VectAvoidInfo
unlessVIParr _ VIParr = VIParr
unlessVIParr vi _ = vi
-- 'VIParr' if either arguments vectorisation information is 'VIParr'; otherwise, the vectorisation
-- information of the first argument is produced.
--
unlessVIParrExpr :: VectAvoidInfo -> CoreExprWithVectInfo -> VectAvoidInfo
infixl `unlessVIParrExpr`
unlessVIParrExpr e1 e2 = e1 `unlessVIParr` vectAvoidInfoOf e2
-- Compute Core annotations to determine for which subexpressions we can avoid vectorisation.
--
-- * The first argument is the set of free, local variables whose evaluation may entail parallelism.
--
vectAvoidInfo :: VarSet -> CoreExprWithFVs -> VM CoreExprWithVectInfo
vectAvoidInfo pvs ce@(_, AnnVar v)
= do
{ gpvs <- globalParallelVars
; vi <- if v `elemVarSet` pvs || v `elemDVarSet` gpvs
then return VIParr
else vectAvoidInfoTypeOf ce
; viTrace ce vi []
; when (vi == VIParr) $
traceVt " reason:" $ if v `elemVarSet` pvs then text "local" else
if v `elemDVarSet` gpvs then text "global" else text "parallel type"
; return ((fvs, vi), AnnVar v)
}
where
fvs = freeVarsOf ce
vectAvoidInfo _pvs ce@(_, AnnLit lit)
= do
{ vi <- vectAvoidInfoTypeOf ce
; viTrace ce vi []
; return ((fvs, vi), AnnLit lit)
}
where
fvs = freeVarsOf ce
vectAvoidInfo pvs ce@(_, AnnApp e1 e2)
= do
{ ceVI <- vectAvoidInfoTypeOf ce
; eVI1 <- vectAvoidInfo pvs e1
; eVI2 <- vectAvoidInfo pvs e2
; let vi = ceVI `unlessVIParrExpr` eVI1 `unlessVIParrExpr` eVI2
-- ; viTrace ce vi [eVI1, eVI2]
; return ((fvs, vi), AnnApp eVI1 eVI2)
}
where
fvs = freeVarsOf ce
vectAvoidInfo pvs ce@(_, AnnLam var body)
= do
{ bodyVI <- vectAvoidInfo pvs body
; varVI <- vectAvoidInfoType $ varType var
; let vi = vectAvoidInfoOf bodyVI `unlessVIParr` varVI
-- ; viTrace ce vi [bodyVI]
; return ((fvs, vi), AnnLam var bodyVI)
}
where
fvs = freeVarsOf ce
vectAvoidInfo pvs ce@(_, AnnLet (AnnNonRec var e) body)
= do
{ ceVI <- vectAvoidInfoTypeOf ce
; eVI <- vectAvoidInfo pvs e
; isScalarTy <- isScalar $ varType var
; (bodyVI, vi) <- if isVIParr eVI && not isScalarTy
then do -- binding is parallel
{ bodyVI <- vectAvoidInfo (pvs `extendVarSet` var) body
; return (bodyVI, VIParr)
}
else do -- binding doesn't affect parallelism
{ bodyVI <- vectAvoidInfo pvs body
; return (bodyVI, ceVI `unlessVIParrExpr` bodyVI)
}
-- ; viTrace ce vi [eVI, bodyVI]
; return ((fvs, vi), AnnLet (AnnNonRec var eVI) bodyVI)
}
where
fvs = freeVarsOf ce
vectAvoidInfo pvs ce@(_, AnnLet (AnnRec bnds) body)
= do
{ ceVI <- vectAvoidInfoTypeOf ce
; bndsVI <- mapM (vectAvoidInfoBnd pvs) bnds
; parrBndrs <- map fst <$> filterM isVIParrBnd bndsVI
; if not . null $ parrBndrs
then do -- body may trigger parallelism via at least one binding
{ new_pvs <- filterM ((not <$>) . isScalar . varType) parrBndrs
; let extendedPvs = pvs `extendVarSetList` new_pvs
; bndsVI <- mapM (vectAvoidInfoBnd extendedPvs) bnds
; bodyVI <- vectAvoidInfo extendedPvs body
-- ; viTrace ce VIParr (map snd bndsVI ++ [bodyVI])
; return ((fvs, VIParr), AnnLet (AnnRec bndsVI) bodyVI)
}
else do -- demanded bindings cannot trigger parallelism
{ bodyVI <- vectAvoidInfo pvs body
; let vi = ceVI `unlessVIParrExpr` bodyVI
-- ; viTrace ce vi (map snd bndsVI ++ [bodyVI])
; return ((fvs, vi), AnnLet (AnnRec bndsVI) bodyVI)
}
}
where
fvs = freeVarsOf ce
vectAvoidInfoBnd pvs (var, e) = (var,) <$> vectAvoidInfo pvs e
isVIParrBnd (var, eVI)
= do
{ isScalarTy <- isScalar (varType var)
; return $ isVIParr eVI && not isScalarTy
}
vectAvoidInfo pvs ce@(_, AnnCase e var ty alts)
= do
{ ceVI <- vectAvoidInfoTypeOf ce
; eVI <- vectAvoidInfo pvs e
; altsVI <- mapM (vectAvoidInfoAlt (isVIParr eVI)) alts
; let alteVIs = [eVI | (_, _, eVI) <- altsVI]
vi = foldl unlessVIParrExpr ceVI (eVI:alteVIs) -- NB: same effect as in the paper
-- ; viTrace ce vi (eVI : alteVIs)
; return ((fvs, vi), AnnCase eVI var ty altsVI)
}
where
fvs = freeVarsOf ce
vectAvoidInfoAlt scrutIsPar (con, bndrs, e)
= do
{ allScalar <- allScalarVarType bndrs
; let altPvs | scrutIsPar && not allScalar = pvs `extendVarSetList` bndrs
| otherwise = pvs
; (con, bndrs,) <$> vectAvoidInfo altPvs e
}
vectAvoidInfo pvs ce@(_, AnnCast e (fvs_ann, ann))
= do
{ eVI <- vectAvoidInfo pvs e
; return ((fvs, vectAvoidInfoOf eVI), AnnCast eVI ((freeVarsOfAnn fvs_ann, VISimple), ann))
}
where
fvs = freeVarsOf ce
vectAvoidInfo pvs ce@(_, AnnTick tick e)
= do
{ eVI <- vectAvoidInfo pvs e
; return ((fvs, vectAvoidInfoOf eVI), AnnTick tick eVI)
}
where
fvs = freeVarsOf ce
vectAvoidInfo _pvs ce@(_, AnnType ty)
= return ((fvs, VISimple), AnnType ty)
where
fvs = freeVarsOf ce
vectAvoidInfo _pvs ce@(_, AnnCoercion coe)
= return ((fvs, VISimple), AnnCoercion coe)
where
fvs = freeVarsOf ce
-- Compute vectorisation avoidance information for a type.
--
vectAvoidInfoType :: Type -> VM VectAvoidInfo
vectAvoidInfoType ty
| isPredTy ty
= return VIDict
| Just (arg, res) <- splitFunTy_maybe ty
= do
{ argVI <- vectAvoidInfoType arg
; resVI <- vectAvoidInfoType res
; case (argVI, resVI) of
(VISimple, VISimple) -> return VISimple -- NB: diverts from the paper: scalar functions
(_ , VIDict) -> return VIDict
_ -> return $ VIComplex `unlessVIParr` argVI `unlessVIParr` resVI
}
| otherwise
= do
{ parr <- maybeParrTy ty
; if parr
then return VIParr
else do
{ scalar <- isScalar ty
; if scalar
then return VISimple
else return VIComplex
} }
-- Compute vectorisation avoidance information for the type of a Core expression (with FVs).
--
vectAvoidInfoTypeOf :: AnnExpr Var ann -> VM VectAvoidInfo
vectAvoidInfoTypeOf = vectAvoidInfoType . annExprType
-- Checks whether the type might be a parallel array type.
--
maybeParrTy :: Type -> VM Bool
maybeParrTy ty
-- looking through newtypes
| Just ty' <- coreView ty
= (== VIParr) <$> vectAvoidInfoType ty'
-- decompose constructor applications
| Just (tc, ts) <- splitTyConApp_maybe ty
= do
{ isParallel <- (tyConName tc `elemNameSet`) <$> globalParallelTyCons
; if isParallel
then return True
else or <$> mapM maybeParrTy ts
}
-- must be a Named ForAllTy because anon ones respond to splitTyConApp_maybe
maybeParrTy (ForAllTy _ ty) = maybeParrTy ty
maybeParrTy _ = return False
-- Are the types of all variables in the 'Scalar' class or toplevel variables?
--
-- NB: 'liftSimple' does not abstract over toplevel variables.
--
allScalarVarType :: [Var] -> VM Bool
allScalarVarType vs = and <$> mapM isScalarOrToplevel vs
where
isScalarOrToplevel v | isToplevel v = return True
| otherwise = isScalar (varType v)
-- Are the types of all variables in the set in the 'Scalar' class or toplevel variables?
--
allScalarVarTypeSet :: DVarSet -> VM Bool
allScalarVarTypeSet = allScalarVarType . dVarSetElems
-- Debugging support
--
viTrace :: CoreExprWithFVs -> VectAvoidInfo -> [CoreExprWithVectInfo] -> VM ()
viTrace ce vi vTs
= traceVt ("vect info: " ++ show vi ++ "[" ++
(concat $ map ((++ " ") . show . vectAvoidInfoOf) vTs) ++ "]")
(ppr $ deAnnotate ce)
| vTurbine/ghc | compiler/vectorise/Vectorise/Exp.hs | bsd-3-clause | 49,617 | 6 | 22 | 14,195 | 11,335 | 5,938 | 5,397 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : Database.PostgreSQL.Simple.LargeObjects
-- Copyright : (c) 2011-2012 Leon P Smith
-- License : BSD3
--
-- Maintainer : [email protected]
--
-- Support for PostgreSQL's Large Objects; see
-- <https://www.postgresql.org/docs/9.5/static/largeobjects.html> for more
-- information.
--
-- Note that Large Object File Descriptors are only valid within a single
-- database transaction, so if you are interested in using anything beyond
-- 'loCreat', 'loCreate', and 'loUnlink', you will need to run the entire
-- sequence of functions in a transaction. As 'loImport' and 'loExport'
-- are simply C functions that call 'loCreat', 'loOpen', 'loRead', and
-- 'loWrite', and do not perform any transaction handling themselves,
-- they also need to be wrapped in an explicit transaction.
--
-----------------------------------------------------------------------------
module Database.PostgreSQL.Simple.LargeObjects
( loCreat
, loCreate
, loImport
, loImportWithOid
, loExport
, loOpen
, loWrite
, loRead
, loSeek
, loTell
, loTruncate
, loClose
, loUnlink
, Oid(..)
, LoFd
, IOMode(..)
, SeekMode(..)
) where
import Control.Applicative ((<$>))
import Control.Exception (throwIO)
import qualified Data.ByteString as B
import Database.PostgreSQL.LibPQ (Oid(..),LoFd(..))
import qualified Database.PostgreSQL.LibPQ as PQ
import Database.PostgreSQL.Simple.Internal
import System.IO (IOMode(..),SeekMode(..))
liftPQ :: B.ByteString -> Connection -> (PQ.Connection -> IO (Maybe a)) -> IO a
liftPQ str conn m = withConnection conn $ \c -> do
res <- m c
case res of
Nothing -> do
msg <- maybe str id <$> PQ.errorMessage c
throwIO $ fatalError msg
Just x -> return x
loCreat :: Connection -> IO Oid
loCreat conn = liftPQ "loCreat" conn (\c -> PQ.loCreat c)
loCreate :: Connection -> Oid -> IO Oid
loCreate conn oid = liftPQ "loCreate" conn (\c -> PQ.loCreate c oid)
loImport :: Connection -> FilePath -> IO Oid
loImport conn path = liftPQ "loImport" conn (\c -> PQ.loImport c path)
loImportWithOid :: Connection -> FilePath -> Oid -> IO Oid
loImportWithOid conn path oid = liftPQ "loImportWithOid" conn (\c -> PQ.loImportWithOid c path oid)
loExport :: Connection -> Oid -> FilePath -> IO ()
loExport conn oid path = liftPQ "loExport" conn (\c -> PQ.loExport c oid path)
loOpen :: Connection -> Oid -> IOMode -> IO LoFd
loOpen conn oid mode = liftPQ "loOpen" conn (\c -> PQ.loOpen c oid mode )
loWrite :: Connection -> LoFd -> B.ByteString -> IO Int
loWrite conn fd dat = liftPQ "loWrite" conn (\c -> PQ.loWrite c fd dat)
loRead :: Connection -> LoFd -> Int -> IO B.ByteString
loRead conn fd maxlen = liftPQ "loRead" conn (\c -> PQ.loRead c fd maxlen)
loSeek :: Connection -> LoFd -> SeekMode -> Int -> IO Int
loSeek conn fd seekmode offset = liftPQ "loSeek" conn (\c -> PQ.loSeek c fd seekmode offset)
loTell :: Connection -> LoFd -> IO Int
loTell conn fd = liftPQ "loTell" conn (\c -> PQ.loTell c fd)
loTruncate :: Connection -> LoFd -> Int -> IO ()
loTruncate conn fd len = liftPQ "loTruncate" conn (\c -> PQ.loTruncate c fd len)
loClose :: Connection -> LoFd -> IO ()
loClose conn fd = liftPQ "loClose" conn (\c -> PQ.loClose c fd)
loUnlink :: Connection -> Oid -> IO ()
loUnlink conn oid = liftPQ "loUnlink" conn (\c -> PQ.loUnlink c oid)
| tomjaguarpaw/postgresql-simple | src/Database/PostgreSQL/Simple/LargeObjects.hs | bsd-3-clause | 3,546 | 0 | 17 | 744 | 1,005 | 538 | 467 | 59 | 2 |
{-# LANGUAGE FlexibleInstances #-}
module Control.Effect.Identity where
import Control.Effect
import qualified Data.Functor.Identity as Id
import qualified Control.Monad.Trans.Identity as Id
runIdentity
:: Monad m
=> Eff Id.Identity m a -> m a
runIdentity = Id.runIdentityT . translate (return . Id.runIdentity)
{-# INLINE runIdentity #-}
| ocharles/interpreters | Control/Effect/Identity.hs | bsd-3-clause | 346 | 0 | 9 | 50 | 84 | 50 | 34 | 10 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Main (main) where
import Robots.Nice
import Robots.Generator
import Robots.Solver
import Robots.QSearch
import Robots.Config hiding ( breit )
import Robots.Data
import Robots.Move
import Autolib.ToDoc
import Autolib.Schichten
import Autolib.Util.Zufall ( eins, repeat_until, selektion )
import Autolib.Util.Sort
import Control.Monad ( when, guard )
import System.Environment
import System.Random
import Data.IORef
import Data.Ix
import Data.List ( tails )
import System.IO
main :: IO ()
main = do
[ n, w ] <- getArgs
top <- newIORef 0
<<<<<<< Generator_Main.hs
sequence_ $ repeat $ action3 top ( read n ) ( read w )
=======
sequence_ $ repeat $ action3 top ( read n :: Int ) ( read w :: Int )
>>>>>>> 1.11
<<<<<<< Generator_Main.hs
action3 top n w = do
mid <- some n $ rectangle w 1
handle top [ mid ]
rectangle w h = range ((-w,-h),(w,h))
=======
action3 top n w = do
k <- stairway st
when ( each_goal_in_right_cluster k ) $ do
print $ vcat [ nice k
, toDoc $ each_goal_in_right_cluster k
, text $ replicate 50 '-'
]
handle top [k]
>>>>>>> 1.11
action2 top n w = do
start0 <- some_without_target n $ border w
let start = attach_target_to_first (0,0) start0
print $ vcat [ nice start , text $ replicate 50 '*' ]
let ks = find start
mapM_ ( \ (b,c,zs) -> when ( is_shifted start c ) $ do
print $ vcat [ besides [ nice start, nice c ]
, toDoc $ reverse zs
]
error "huh"
) ks
find k = takeUntil ( \ (b,c,_) -> is_shifted k c )
$ take 10000
$ tail
$ search znachfolger_all_onboard badness k
is_shifted k0 k1 =
let ds = diffs k0 k1
tag (a,b) = if abs a == abs b then abs a else 0
all_equal xs = 1 == length ( sort xs )
in k0 /= k1 && all_equal ( map tag ds )
diffs k0 k1 =
let smp = sort . map position . robots
in zipWith (\ (a,b) (c,d) -> (a-c,b-d)) ( smp k0 ) ( smp k1 )
values xys = do (x,y) <- xys; [x,y]
check_for_shifts (k, zs ) = do
let zks = zip [0..] $ unfold k zs
sequence_ $ do
(x,k) : rest <- tails zks
(y,k') <- drop ( length $ robots k ) rest
return $ do
let ds = diffs k k'
vs = values ds
ma = maximum $ map abs vs
mi = minimum $ map abs vs
if ma == 1 && mi == 1
then print $ vcat
[ text "-"
, toDoc k
, besides [ nice k
, text "=>"
, vcat [ text " ", nice k' ] ]
, toDoc $ take (y - x) $ drop x $ zs
, toDoc k'
, toDoc $ ds
, toDoc $ vs
]
else return ()
unfold k zs = k : case zs of
[] -> []
z : zs -> case execute k z of
Just k' -> unfold k' zs
Nothing -> []
--------------------------------------------------------------------------
data Stair = Stair
{ breit :: Integer
, dist :: Integer
, hoch :: Integer
, robs :: Int
} deriving ( Show )
st = Stair { breit = 3, dist = 5, hoch = 3, robs = 3 }
stairway st = do
let punkt w = do
[ x,y ] <- sequence $ replicate 2 $ randomRIO ( 0, w - 1 )
return ( x, y)
let block (x,y) = do
k <- randomRIO ( 2, robs st )
let d = breit st - 1
selektion k $ range ((x,y),(x+d,y+d))
bs <- sequence $ do
h <- [ 0 .. hoch st - 1 ]
w <- [ 0 , 1 ]
let grid = breit st + dist st
return $ block ( (h + w) * grid, h * grid )
return $ make_with_hull $ make_robots $ concat bs
-- | drop first position, assign as target to last
make_robots ( p : ps ) = do
let names = map return [ 'A' .. ]
( n, p, z ) <- zip3 names ( reverse ps ) $ Just p : repeat Nothing
return $ Robot { name = n, position = p, ziel = z }
--------------------------------------------------------------------------
action1 top n w = do
mid0 <- some_without_target n $ corner w
let mid = attach_target_to_first (0,0) mid0
handle top [ mid ]
border w = do
p @ (x,y) <- range ((-w,-w),(w,w))
guard $ abs x > w - 3 || abs y > w - 3
return p
corner w = do
p @ (x,y) <- range ((-w,-w),(w,w))
-- guard $ abs x > w - 2 || abs y > w - 2
guard $ abs x > w - 3 && abs y > w - 3
return p
attach_target_to_first p k = make $
let r : rs = robots k
in r { ziel = Just p } : rs
----------------------------------------------------------------------
action0 top n w = do
mid0 <- some_without_target n $ range ((-w,-w),(w,w))
-- print $ vcat [ text "mid0", nice mid0 ]
let fss :: [[Config]]
fss = reachables mid0
f :: Config <- eins ( last $ init fss )
`repeat_until` \ f -> not $ null $ robots f
r :: Robot <- eins $ robots f
let mid :: Config
mid = attach_target r mid0
-- print $ vcat [ text "mid", nice mid ]
( b, c, zs ) <- qsolve mid
let pss = [ mid ] : predecessors mid
hPutStr stderr $ show ( length zs ) ++ "."
best <- readIORef top
mapM_ ( handle top )
$ drop ( best - length zs )
$ pss
attach_target r conf = make $ do
s <- robots conf
return $ if name r == name s
then s { ziel = Just $ position r }
else s
handle top is = do
i <- eins is
( b, c, zs) <- qsolve i
best <- readIORef top
when ( ist_final c ) $ do
-- check_for_shifts ( i, reverse zs )
when ( length zs >= best ) $ do
print i
print $ besides [ nice i , text "=>", nice c ]
print $ fsep
$ map ( \ (n,d) -> text n <> text ":" <> toDoc d )
$ reverse zs
putStrLn $ "length: " ++ show ( length zs )
hFlush stdout
writeIORef top $ length zs
| florianpilz/autotool | src/Robots/Generator_Main.hs | gpl-2.0 | 5,664 | 74 | 24 | 1,810 | 2,318 | 1,213 | 1,105 | -1 | -1 |
module Usage.Usage where
import qualified Definition.Definition as Definition
import qualified Other.Definition as Definition
test :: Int
test = D<caret>efinition.seven + 1
testBis :: Int
testBis = Definition.eight + 8
| charleso/intellij-haskforce | tests/gold/codeInsight/QualifiedImport_MultipleImportSameQualifiedName1/Usage/Usage.hs | apache-2.0 | 225 | 0 | 7 | 35 | 62 | 38 | 24 | -1 | -1 |
fun x y z = f x x y z | mpickering/hlint-refactor | tests/examples/Lambda5.hs | bsd-3-clause | 21 | 1 | 5 | 9 | 27 | 10 | 17 | 1 | 1 |
{-# LANGUAGE EmptyCase #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -Wall #-}
module T17270 where
import Data.Type.Equality
f :: a :~: Int -> b :~: Bool -> a :~: b -> void
f Refl Refl x = case x of {}
$([d| g :: a :~: Int -> b :~: Bool -> a :~: b -> void
g Refl Refl x = case x of {}
|])
| sdiehl/ghc | testsuite/tests/th/T17270.hs | bsd-3-clause | 363 | 0 | 8 | 88 | 73 | 44 | 29 | 11 | 0 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE FlexibleInstances #-}
module HigherOrderParse where
import Data.Tree
-- |Adapter class for various error types such as BNFCs ErrM etc.
-- b is the given polymorphic errortype (e.g. ErrM Program) whose
-- parameter is a, thus we require that b -> a. Then a is the right
-- result of Either.
class Result b a | b -> a where
from :: b -> Either String a
instance Result (Maybe a) a where
from (Just a) = Right a
from Nothing = Left "Parse error"
instance (Show b) => Result (Either b a) a where
from (Right a) = Right a
from (Left e ) = Left $ show e
-- |higher-order build tree
buildTreeGen :: (Result b a)
=> (String -> b) -- ^ some parsefunction that results in
-- an instance of Result
-> (a -> Tree String) -- ^ some generic data2tree function
-> String -- ^ some input
-> Tree String -- ^ resulting tree
buildTreeGen parse data2tree s =
case (from $ parse s) of
Right ast -> data2tree ast
Left err -> Node ("Parse Failed: "++err) []
| RefactoringTools/HaRe | hareview/data/HigherOrderParse.hs | bsd-3-clause | 1,125 | 0 | 10 | 289 | 271 | 142 | 129 | 22 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
module List () where
{-@ Decrease go 3 4 5 @-}
{-@ Decrease perms 4 5 6 @-}
{-@ foo :: xs:[a] -> ys:[a] -> {v:Int| v = (len xs)- (len ys)} -> Int @-}
foo :: [a] -> [a] -> Int -> Int
foo = undefined
permutations :: [a] -> [[a]]
permutations xs = go xs xs (length xs) (length xs) 1
where
go xs0 xs (d2 :: Int) d1 (d3::Int) = xs : perms xs0 xs [] d2 d1 0
perms _ [] _ _ _ _ = []
perms xs0 (t:ts) is (d2 :: Int) (d1::Int) (d3 :: Int) = (perms ts xs0 (t:is) d2 (length ts) d3) ++ (go xs0 is (length xs0 - length is) d1 1)
-- permutations :: [a] -> [[a]]
-- permutations xs = go xs xs (length xs) (0::Int) 1
-- where
-- go xs0 xs d1 (d2::Int) (d3::Int) = xs : perms xs0 xs [] d1 0 0
-- perms _ [] _ _ _ _ = []
-- perms xs0 (t:ts) is (d1::Int) (d2 :: Int) (d3 :: Int) = (perms ts xs0 (t:is) (length ts) 0 d3) ++ (go xs0 is (length is) 0 1)
--
--
| mightymoose/liquidhaskell | tests/pos/malformed0.hs | bsd-3-clause | 947 | 0 | 12 | 274 | 275 | 151 | 124 | 9 | 2 |
module ListDemo where
data Poo a = C { t :: Poo a }
{-@ type Geq N = {v:_ | N <= v} @-}
{-@ data Poo a = C { t :: Poo (Geq 0) } @-}
| mightymoose/liquidhaskell | tests/crash/hole-crash1.hs | bsd-3-clause | 135 | 0 | 9 | 42 | 25 | 16 | 9 | 2 | 0 |
module Distribution.Server.Users.Group (
module UserIdSet,
UserGroup(..),
GroupDescription(..),
nullDescription,
groupName,
queryUserGroups,
) where
import Distribution.Server.Users.Types
import Distribution.Server.Users.UserIdSet as UserIdSet
import Distribution.Server.Framework.MemSize
import Control.DeepSeq
-- | A stateful interface to a group of users. It provides actions for
-- querying and modifying a user group.
--
-- This interface is meant not just for singleton user groups, but also
-- collections of groups. Some features may provide a UserGroup parametrized
-- by an argument (e.g. there's a maintainer group per-package).
--
-- It includes a list of which other users groups are supposed to be allowed
-- to edit this one: the 'canRemoveGroup' and 'canAddGroup' lists. One often
-- wants a user group to be in its own 'canRemoveGroup' or 'canAddGroup'
-- lists. This is easy using a recursive definition such as:
--
-- > let fooGroup = UserGroup { ... , canAddGroup = [adminGroup, fooGroup] }
--
data UserGroup = UserGroup {
-- | A description of the group for display purposes
groupDesc :: GroupDescription,
-- | Query the current set of group members
queryUserGroup :: IO UserIdSet,
-- | Add a user to this group. This does nothing if it already exists.
-- It initialises the group state if it wasn't previously initialised.
addUserToGroup :: UserId -> IO (),
-- | Remove a user from this group. It does nothing if not present.
-- It initialises the group state if it wasn't previously initialised.
removeUserFromGroup :: UserId -> IO (),
-- | Other user groups which are authorised to remove users from this one
-- (which may include this one recursively).
--
groupsAllowedToDelete :: [UserGroup],
-- | User groups which are authorised to add members to this one (which
-- may include this one recursively).
--
groupsAllowedToAdd :: [UserGroup]
}
-- | A displayable description for a user group.
--
-- Given a groupTitle of A and a group entity of Nothing, the group will be
-- called "A"; given a groupTitle of "A" and a groupEntity of Just ("B",
-- Just "C"), the title will be displayed as "A for <a href=C>B</a>".
data GroupDescription = GroupDescription {
groupTitle :: String,
groupEntity :: Maybe (String, Maybe String),
groupPrologue :: String
}
nullDescription :: GroupDescription
nullDescription =
GroupDescription {
groupTitle = "",
groupEntity = Nothing,
groupPrologue = ""
}
groupName :: GroupDescription -> String
groupName desc =
groupTitle desc ++ maybe "" (\(for, _) -> " for " ++ for) (groupEntity desc)
queryUserGroups :: [UserGroup] -> IO UserIdSet
queryUserGroups = fmap UserIdSet.unions . mapM queryUserGroup
-- for use in Caches, really...
instance NFData GroupDescription where
rnf (GroupDescription a b c) = rnf a `seq` rnf b `seq` rnf c
instance MemSize GroupDescription where
memSize (GroupDescription a b c) = memSize3 a b c
| ocharles/hackage-server | Distribution/Server/Users/Group.hs | bsd-3-clause | 3,048 | 0 | 11 | 626 | 406 | 248 | 158 | 37 | 1 |
{-# LANGUAGE RankNTypes #-}
-- This one showed up a bug in pre-subsumption
module ShouldCompile where
class Data a where {}
type GenericQ r = forall a. Data a => a -> r
everything :: (r -> r -> r) -> GenericQ r
everything k f = error "urk"
-- | Get a list of all entities that meet a predicate
listify :: (r -> Bool) -> GenericQ [r]
listify p = everything (++)
| spacekitteh/smcghc | testsuite/tests/typecheck/should_compile/tc206.hs | bsd-3-clause | 371 | 0 | 8 | 84 | 112 | 62 | 50 | -1 | -1 |
-- Set up the data structures provided by 'Vectorise.Builtins'.
module Vectorise.Builtins.Initialise (
-- * Initialisation
initBuiltins, initBuiltinVars
) where
import Vectorise.Builtins.Base
import BasicTypes
import TysPrim
import DsMonad
import TysWiredIn
import DataCon
import TyCon
import Class
import CoreSyn
import Type
import NameEnv
import Name
import Id
import FastString
import Outputable
import Control.Monad
import Data.Array
-- |Create the initial map of builtin types and functions.
--
initBuiltins :: DsM Builtins
initBuiltins
= do { -- 'PArray: representation type for parallel arrays
; parrayTyCon <- externalTyCon (fsLit "PArray")
-- 'PData': type family mapping array element types to array representation types
-- Not all backends use `PDatas`.
; pdataTyCon <- externalTyCon (fsLit "PData")
; pdatasTyCon <- externalTyCon (fsLit "PDatas")
-- 'PR': class of basic array operators operating on 'PData' types
; prClass <- externalClass (fsLit "PR")
; let prTyCon = classTyCon prClass
-- 'PRepr': type family mapping element types to representation types
; preprTyCon <- externalTyCon (fsLit "PRepr")
-- 'PA': class of basic operations on arrays (parametrised by the element type)
; paClass <- externalClass (fsLit "PA")
; let paTyCon = classTyCon paClass
[paDataCon] = tyConDataCons paTyCon
paPRSel = classSCSelId paClass 0
-- Functions on array representations
; replicatePDVar <- externalVar (fsLit "replicatePD")
; replicate_vars <- mapM externalVar (suffixed "replicatePA" aLL_DPH_PRIM_TYCONS)
; emptyPDVar <- externalVar (fsLit "emptyPD")
; empty_vars <- mapM externalVar (suffixed "emptyPA" aLL_DPH_PRIM_TYCONS)
; packByTagPDVar <- externalVar (fsLit "packByTagPD")
; packByTag_vars <- mapM externalVar (suffixed "packByTagPA" aLL_DPH_PRIM_TYCONS)
; let combineNamesD = [("combine" ++ show i ++ "PD") | i <- [2..mAX_DPH_COMBINE]]
; let combineNamesA = [("combine" ++ show i ++ "PA") | i <- [2..mAX_DPH_COMBINE]]
; combines <- mapM externalVar (map mkFastString combineNamesD)
; combines_vars <- mapM (mapM externalVar) $
map (\name -> suffixed name aLL_DPH_PRIM_TYCONS) combineNamesA
; let replicatePD_PrimVars = mkNameEnv (zip aLL_DPH_PRIM_TYCONS replicate_vars)
emptyPD_PrimVars = mkNameEnv (zip aLL_DPH_PRIM_TYCONS empty_vars)
packByTagPD_PrimVars = mkNameEnv (zip aLL_DPH_PRIM_TYCONS packByTag_vars)
combinePDVars = listArray (2, mAX_DPH_COMBINE) combines
combinePD_PrimVarss = listArray (2, mAX_DPH_COMBINE)
[ mkNameEnv (zip aLL_DPH_PRIM_TYCONS vars)
| vars <- combines_vars]
-- 'Scalar': class moving between plain unboxed arrays and 'PData' representations
; scalarClass <- externalClass (fsLit "Scalar")
-- N-ary maps ('zipWith' family)
; scalar_map <- externalVar (fsLit "scalar_map")
; scalar_zip2 <- externalVar (fsLit "scalar_zipWith")
; scalar_zips <- mapM externalVar (numbered "scalar_zipWith" 3 mAX_DPH_SCALAR_ARGS)
; let scalarZips = listArray (1, mAX_DPH_SCALAR_ARGS)
(scalar_map : scalar_zip2 : scalar_zips)
-- Types and functions for generic type representations
; voidTyCon <- externalTyCon (fsLit "Void")
; voidVar <- externalVar (fsLit "void")
; fromVoidVar <- externalVar (fsLit "fromVoid")
; sum_tcs <- mapM externalTyCon (numbered "Sum" 2 mAX_DPH_SUM)
; let sumTyCons = listArray (2, mAX_DPH_SUM) sum_tcs
; wrapTyCon <- externalTyCon (fsLit "Wrap")
; pvoidVar <- externalVar (fsLit "pvoid")
; pvoidsVar <- externalVar (fsLit "pvoids#")
-- Types and functions for closure conversion
; closureTyCon <- externalTyCon (fsLit ":->")
; closureVar <- externalVar (fsLit "closure")
; liftedClosureVar <- externalVar (fsLit "liftedClosure")
; applyVar <- externalVar (fsLit "$:")
; liftedApplyVar <- externalVar (fsLit "liftedApply")
; closures <- mapM externalVar (numbered "closure" 1 mAX_DPH_SCALAR_ARGS)
; let closureCtrFuns = listArray (1, mAX_DPH_SCALAR_ARGS) closures
-- Types and functions for selectors
; sel_tys <- mapM externalType (numbered "Sel" 2 mAX_DPH_SUM)
; sels_tys <- mapM externalType (numbered "Sels" 2 mAX_DPH_SUM)
; sels_length <- mapM externalFun (numbered_hash "lengthSels" 2 mAX_DPH_SUM)
; sel_replicates <- mapM externalFun (numbered_hash "replicateSel" 2 mAX_DPH_SUM)
; sel_tags <- mapM externalFun (numbered "tagsSel" 2 mAX_DPH_SUM)
; sel_elements <- mapM mk_elements [(i,j) | i <- [2..mAX_DPH_SUM], j <- [0..i-1]]
; let selTys = listArray (2, mAX_DPH_SUM) sel_tys
selsTys = listArray (2, mAX_DPH_SUM) sels_tys
selsLengths = listArray (2, mAX_DPH_SUM) sels_length
selReplicates = listArray (2, mAX_DPH_SUM) sel_replicates
selTagss = listArray (2, mAX_DPH_SUM) sel_tags
selElementss = array ((2, 0), (mAX_DPH_SUM, mAX_DPH_SUM)) sel_elements
-- Distinct local variable
; liftingContext <- liftM (\u -> mkSysLocal (fsLit "lc") u intPrimTy) newUnique
; return $ Builtins
{ parrayTyCon = parrayTyCon
, pdataTyCon = pdataTyCon
, pdatasTyCon = pdatasTyCon
, preprTyCon = preprTyCon
, prClass = prClass
, prTyCon = prTyCon
, paClass = paClass
, paTyCon = paTyCon
, paDataCon = paDataCon
, paPRSel = paPRSel
, replicatePDVar = replicatePDVar
, replicatePD_PrimVars = replicatePD_PrimVars
, emptyPDVar = emptyPDVar
, emptyPD_PrimVars = emptyPD_PrimVars
, packByTagPDVar = packByTagPDVar
, packByTagPD_PrimVars = packByTagPD_PrimVars
, combinePDVars = combinePDVars
, combinePD_PrimVarss = combinePD_PrimVarss
, scalarClass = scalarClass
, scalarZips = scalarZips
, voidTyCon = voidTyCon
, voidVar = voidVar
, fromVoidVar = fromVoidVar
, sumTyCons = sumTyCons
, wrapTyCon = wrapTyCon
, pvoidVar = pvoidVar
, pvoidsVar = pvoidsVar
, closureTyCon = closureTyCon
, closureVar = closureVar
, liftedClosureVar = liftedClosureVar
, applyVar = applyVar
, liftedApplyVar = liftedApplyVar
, closureCtrFuns = closureCtrFuns
, selTys = selTys
, selsTys = selsTys
, selsLengths = selsLengths
, selReplicates = selReplicates
, selTagss = selTagss
, selElementss = selElementss
, liftingContext = liftingContext
}
}
where
suffixed :: String -> [Name] -> [FastString]
suffixed pfx ns = [mkFastString (pfx ++ "_" ++ (occNameString . nameOccName) n) | n <- ns]
-- Make a list of numbered strings in some range, eg foo3, foo4, foo5
numbered :: String -> Int -> Int -> [FastString]
numbered pfx m n = [mkFastString (pfx ++ show i) | i <- [m..n]]
numbered_hash :: String -> Int -> Int -> [FastString]
numbered_hash pfx m n = [mkFastString (pfx ++ show i ++ "#") | i <- [m..n]]
mk_elements :: (Int, Int) -> DsM ((Int, Int), CoreExpr)
mk_elements (i,j)
= do { v <- externalVar $ mkFastString ("elementsSel" ++ show i ++ "_" ++ show j ++ "#")
; return ((i, j), Var v)
}
-- |Get the mapping of names in the Prelude to names in the DPH library.
--
initBuiltinVars :: Builtins -> DsM [(Var, Var)]
-- FIXME: must be replaced by VECTORISE pragmas!!!
initBuiltinVars (Builtins { })
= do
cvars <- mapM externalVar cfs
return $ zip (map dataConWorkId cons) cvars
where
(cons, cfs) = unzip preludeDataCons
preludeDataCons :: [(DataCon, FastString)]
preludeDataCons
= [mk_tup n (mkFastString $ "tup" ++ show n) | n <- [2..5]]
where
mk_tup n name = (tupleDataCon Boxed n, name)
-- Auxilliary look up functions -----------------------------------------------
-- |Lookup a variable given its name and the module that contains it.
externalVar :: FastString -> DsM Var
externalVar fs = dsLookupDPHRdrEnv (mkVarOccFS fs) >>= dsLookupGlobalId
-- |Like `externalVar` but wrap the `Var` in a `CoreExpr`.
externalFun :: FastString -> DsM CoreExpr
externalFun fs = Var <$> externalVar fs
-- |Lookup a 'TyCon' in 'Data.Array.Parallel.Prim', given its name.
-- Panic if there isn't one.
externalTyCon :: FastString -> DsM TyCon
externalTyCon fs = dsLookupDPHRdrEnv (mkTcOccFS fs) >>= dsLookupTyCon
-- |Lookup some `Type` in 'Data.Array.Parallel.Prim', given its name.
externalType :: FastString -> DsM Type
externalType fs
= do tycon <- externalTyCon fs
return $ mkTyConApp tycon []
-- |Lookup a 'Class' in 'Data.Array.Parallel.Prim', given its name.
externalClass :: FastString -> DsM Class
externalClass fs
= do { tycon <- dsLookupDPHRdrEnv (mkClsOccFS fs) >>= dsLookupTyCon
; case tyConClass_maybe tycon of
Nothing -> pprPanic "Vectorise.Builtins.Initialise" $
ptext (sLit "Data.Array.Parallel.Prim.") <>
ftext fs <+> ptext (sLit "is not a type class")
Just cls -> return cls
}
| urbanslug/ghc | compiler/vectorise/Vectorise/Builtins/Initialise.hs | bsd-3-clause | 10,353 | 1 | 17 | 3,316 | 2,278 | 1,208 | 1,070 | 163 | 2 |
module ShouldCompile where
import Data.List (nub) -- all unused
import Data.Char (ord, chr) -- some unused
x = chr 42
| urbanslug/ghc | testsuite/tests/rename/should_compile/rn046.hs | bsd-3-clause | 121 | 0 | 5 | 23 | 37 | 23 | 14 | 4 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Yesod.Auth.Message
( AuthMessage (..)
, defaultMessage
-- * All languages
, englishMessage
, portugueseMessage
, swedishMessage
, germanMessage
, frenchMessage
, norwegianBokmålMessage
, japaneseMessage
, finnishMessage
, chineseMessage
, croatianMessage
, spanishMessage
, czechMessage
, russianMessage
, dutchMessage
, danishMessage
, koreanMessage
) where
import Data.Monoid (mappend, (<>))
import Data.Text (Text)
data AuthMessage =
NoOpenID
| LoginOpenID
| LoginGoogle
| LoginYahoo
| Email
| UserName
| IdentifierNotFound Text
| Password
| Register
| RegisterLong
| EnterEmail
| ConfirmationEmailSentTitle
| ConfirmationEmailSent Text
| AddressVerified
| EmailVerifiedChangePass
| EmailVerified
| InvalidKeyTitle
| InvalidKey
| InvalidEmailPass
| BadSetPass
| SetPassTitle
| SetPass
| NewPass
| ConfirmPass
| PassMismatch
| PassUpdated
| Facebook
| LoginViaEmail
| InvalidLogin
| NowLoggedIn
| LoginTitle
| PleaseProvideUsername
| PleaseProvidePassword
| NoIdentifierProvided
| InvalidEmailAddress
| PasswordResetTitle
| ProvideIdentifier
| SendPasswordResetEmail
| PasswordResetPrompt
| CurrentPassword
| InvalidUsernamePass
| Logout
| LogoutTitle
| AuthError
{-# DEPRECATED Logout "Please, use LogoutTitle instead." #-}
{-# DEPRECATED AddressVerified "Please, use EmailVerifiedChangePass instead." #-}
-- | Defaults to 'englishMessage'.
defaultMessage :: AuthMessage -> Text
defaultMessage = englishMessage
englishMessage :: AuthMessage -> Text
englishMessage NoOpenID = "No OpenID identifier found"
englishMessage LoginOpenID = "Log in via OpenID"
englishMessage LoginGoogle = "Log in via Google"
englishMessage LoginYahoo = "Log in via Yahoo"
englishMessage Email = "Email"
englishMessage UserName = "User name"
englishMessage Password = "Password"
englishMessage CurrentPassword = "Current Password"
englishMessage Register = "Register"
englishMessage RegisterLong = "Register a new account"
englishMessage EnterEmail = "Enter your e-mail address below, and a confirmation e-mail will be sent to you."
englishMessage ConfirmationEmailSentTitle = "Confirmation e-mail sent"
englishMessage (ConfirmationEmailSent email) =
"A confirmation e-mail has been sent to " `Data.Monoid.mappend`
email `mappend`
"."
englishMessage AddressVerified = "Email address verified, please set a new password"
englishMessage EmailVerifiedChangePass = "Email address verified, please set a new password"
englishMessage EmailVerified = "Email address verified"
englishMessage InvalidKeyTitle = "Invalid verification key"
englishMessage InvalidKey = "I'm sorry, but that was an invalid verification key."
englishMessage InvalidEmailPass = "Invalid email/password combination"
englishMessage BadSetPass = "You must be logged in to set a password"
englishMessage SetPassTitle = "Set password"
englishMessage SetPass = "Set a new password"
englishMessage NewPass = "New password"
englishMessage ConfirmPass = "Confirm"
englishMessage PassMismatch = "Passwords did not match, please try again"
englishMessage PassUpdated = "Password updated"
englishMessage Facebook = "Log in with Facebook"
englishMessage LoginViaEmail = "Log in via email"
englishMessage InvalidLogin = "Invalid login"
englishMessage NowLoggedIn = "You are now logged in"
englishMessage LoginTitle = "Log In"
englishMessage PleaseProvideUsername = "Please fill in your username"
englishMessage PleaseProvidePassword = "Please fill in your password"
englishMessage NoIdentifierProvided = "No email/username provided"
englishMessage InvalidEmailAddress = "Invalid email address provided"
englishMessage PasswordResetTitle = "Password Reset"
englishMessage ProvideIdentifier = "Email or Username"
englishMessage SendPasswordResetEmail = "Send password reset email"
englishMessage PasswordResetPrompt = "Enter your e-mail address or username below, and a password reset e-mail will be sent to you."
englishMessage InvalidUsernamePass = "Invalid username/password combination"
englishMessage (IdentifierNotFound ident) = "Login not found: " `mappend` ident
englishMessage Logout = "Log Out"
englishMessage LogoutTitle = "Log Out"
englishMessage AuthError = "Authentication Error" -- FIXME by Google Translate
portugueseMessage :: AuthMessage -> Text
portugueseMessage NoOpenID = "Nenhum identificador OpenID encontrado"
portugueseMessage LoginOpenID = "Entrar via OpenID"
portugueseMessage LoginGoogle = "Entrar via Google"
portugueseMessage LoginYahoo = "Entrar via Yahoo"
portugueseMessage Email = "E-mail"
portugueseMessage UserName = "Nome de usuário" -- FIXME by Google Translate "user name"
portugueseMessage Password = "Senha"
portugueseMessage CurrentPassword = "Palavra de passe"
portugueseMessage Register = "Registrar"
portugueseMessage RegisterLong = "Registrar uma nova conta"
portugueseMessage EnterEmail = "Por favor digite seu endereço de e-mail abaixo e um e-mail de confirmação será enviado para você."
portugueseMessage ConfirmationEmailSentTitle = "E-mail de confirmação enviado"
portugueseMessage (ConfirmationEmailSent email) =
"Um e-mail de confirmação foi enviado para " `mappend`
email `mappend`
"."
portugueseMessage AddressVerified = "Endereço verificado, por favor entre com uma nova senha"
portugueseMessage EmailVerifiedChangePass = "Endereço verificado, por favor entre com uma nova senha"
portugueseMessage EmailVerified = "Endereço verificado"
portugueseMessage InvalidKeyTitle = "Chave de verificação inválida"
portugueseMessage InvalidKey = "Por favor nos desculpe, mas essa é uma chave de verificação inválida."
portugueseMessage InvalidEmailPass = "E-mail e/ou senha inválidos"
portugueseMessage BadSetPass = "Você deve entrar para definir uma senha"
portugueseMessage SetPassTitle = "Definir senha"
portugueseMessage SetPass = "Definir uma nova senha"
portugueseMessage NewPass = "Nova senha"
portugueseMessage ConfirmPass = "Confirmar"
portugueseMessage PassMismatch = "Senhas não conferem, por favor tente novamente"
portugueseMessage PassUpdated = "Senhas alteradas"
portugueseMessage Facebook = "Entrar via Facebook"
portugueseMessage LoginViaEmail = "Entrar via e-mail"
portugueseMessage InvalidLogin = "Informações de login inválidas"
portugueseMessage NowLoggedIn = "Você acaba de entrar no site com sucesso!"
portugueseMessage LoginTitle = "Entrar no site"
portugueseMessage PleaseProvideUsername = "Por favor digite seu nome de usuário"
portugueseMessage PleaseProvidePassword = "Por favor digite sua senha"
portugueseMessage NoIdentifierProvided = "Nenhum e-mail ou nome de usuário informado"
portugueseMessage InvalidEmailAddress = "Endereço de e-mail inválido informado"
portugueseMessage PasswordResetTitle = "Resetar senha"
portugueseMessage ProvideIdentifier = "E-mail ou nome de usuário"
portugueseMessage SendPasswordResetEmail = "Enviar e-mail para resetar senha"
portugueseMessage PasswordResetPrompt = "Insira seu endereço de e-mail ou nome de usuário abaixo. Um e-mail para resetar sua senha será enviado para você."
portugueseMessage InvalidUsernamePass = "Nome de usuário ou senha inválidos"
-- TODO
portugueseMessage i@(IdentifierNotFound _) = englishMessage i
portugueseMessage Logout = "Sair" -- FIXME by Google Translate
portugueseMessage LogoutTitle = "Sair" -- FIXME by Google Translate
portugueseMessage AuthError = "Erro de autenticação" -- FIXME by Google Translate
spanishMessage :: AuthMessage -> Text
spanishMessage NoOpenID = "No se encuentra el identificador OpenID"
spanishMessage LoginOpenID = "Entrar utilizando OpenID"
spanishMessage LoginGoogle = "Entrar utilizando Google"
spanishMessage LoginYahoo = "Entrar utilizando Yahoo"
spanishMessage Email = "Correo electrónico"
spanishMessage UserName = "Nombre de Usuario"
spanishMessage Password = "Contraseña"
spanishMessage CurrentPassword = "Contraseña actual"
spanishMessage Register = "Registrarse"
spanishMessage RegisterLong = "Registrar una nueva cuenta"
spanishMessage EnterEmail = "Coloque su dirección de correo electrónico, y un correo de confirmación le será enviado a su cuenta."
spanishMessage ConfirmationEmailSentTitle = "La confirmación de correo ha sido enviada"
spanishMessage (ConfirmationEmailSent email) =
"Una confirmación de correo electrónico ha sido enviada a " `mappend`
email `mappend`
"."
spanishMessage AddressVerified = "Dirección verificada, por favor introduzca una contraseña"
spanishMessage EmailVerifiedChangePass = "Dirección verificada, por favor introduzca una contraseña"
spanishMessage EmailVerified = "Dirección verificada"
spanishMessage InvalidKeyTitle = "Clave de verificación invalida"
spanishMessage InvalidKey = "Lo sentimos, pero esa clave de verificación es inválida."
spanishMessage InvalidEmailPass = "La combinación cuenta de correo/contraseña es inválida"
spanishMessage BadSetPass = "Debe acceder a la aplicación para modificar la contraseña"
spanishMessage SetPassTitle = "Modificar contraseña"
spanishMessage SetPass = "Actualizar nueva contraseña"
spanishMessage NewPass = "Nueva contraseña"
spanishMessage ConfirmPass = "Confirmar"
spanishMessage PassMismatch = "Las contraseñas no coinciden, inténtelo de nuevo"
spanishMessage PassUpdated = "Contraseña actualizada"
spanishMessage Facebook = "Entrar mediante Facebook"
spanishMessage LoginViaEmail = "Entrar mediante una cuenta de correo"
spanishMessage InvalidLogin = "Login inválido"
spanishMessage NowLoggedIn = "Usted ha ingresado al sitio"
spanishMessage LoginTitle = "Log In"
spanishMessage PleaseProvideUsername = "Por favor escriba su nombre de usuario"
spanishMessage PleaseProvidePassword = "Por favor escriba su contraseña"
spanishMessage NoIdentifierProvided = "No ha indicado una cuenta de correo/nombre de usuario"
spanishMessage InvalidEmailAddress = "La cuenta de correo es inválida"
spanishMessage PasswordResetTitle = "Actualización de contraseña"
spanishMessage ProvideIdentifier = "Cuenta de correo o nombre de usuario"
spanishMessage SendPasswordResetEmail = "Enviar correo de actualización de contraseña"
spanishMessage PasswordResetPrompt = "Escriba su cuenta de correo o nombre de usuario, y una confirmación de actualización de contraseña será enviada a su cuenta de correo."
spanishMessage InvalidUsernamePass = "Combinación de nombre de usuario/contraseña invalida"
-- TODO
spanishMessage i@(IdentifierNotFound _) = englishMessage i
spanishMessage Logout = "Finalizar la sesión" -- FIXME by Google Translate
spanishMessage LogoutTitle = "Finalizar la sesión" -- FIXME by Google Translate
spanishMessage AuthError = "Error de autenticación" -- FIXME by Google Translate
swedishMessage :: AuthMessage -> Text
swedishMessage NoOpenID = "Fann ej OpenID identifierare"
swedishMessage LoginOpenID = "Logga in via OpenID"
swedishMessage LoginGoogle = "Logga in via Google"
swedishMessage LoginYahoo = "Logga in via Yahoo"
swedishMessage Email = "Epost"
swedishMessage UserName = "Användarnamn" -- FIXME by Google Translate "user name"
swedishMessage Password = "Lösenord"
swedishMessage CurrentPassword = "Current password"
swedishMessage Register = "Registrera"
swedishMessage RegisterLong = "Registrera ett nytt konto"
swedishMessage EnterEmail = "Skriv in din epost nedan så kommer ett konfirmationsmail skickas till adressen."
swedishMessage ConfirmationEmailSentTitle = "Konfirmationsmail skickat"
swedishMessage (ConfirmationEmailSent email) =
"Ett konfirmationsmeddelande har skickats till" `mappend`
email `mappend`
"."
swedishMessage AddressVerified = "Adress verifierad, vänligen välj nytt lösenord"
swedishMessage EmailVerifiedChangePass = "Adress verifierad, vänligen välj nytt lösenord"
swedishMessage EmailVerified = "Adress verifierad"
swedishMessage InvalidKeyTitle = "Ogiltig verifikationsnyckel"
swedishMessage InvalidKey = "Tyvärr, du angav en ogiltig verifimationsnyckel."
swedishMessage InvalidEmailPass = "Ogiltig epost/lösenord kombination"
swedishMessage BadSetPass = "Du måste vara inloggad för att ange ett lösenord"
swedishMessage SetPassTitle = "Ange lösenord"
swedishMessage SetPass = "Ange nytt lösenord"
swedishMessage NewPass = "Nytt lösenord"
swedishMessage ConfirmPass = "Godkänn"
swedishMessage PassMismatch = "Lösenorden matcha ej, vänligen försök igen"
swedishMessage PassUpdated = "Lösenord updaterades"
swedishMessage Facebook = "Logga in med Facebook"
swedishMessage LoginViaEmail = "Logga in via epost"
swedishMessage InvalidLogin = "Ogiltigt login"
swedishMessage NowLoggedIn = "Du är nu inloggad"
swedishMessage LoginTitle = "Logga in"
swedishMessage PleaseProvideUsername = "Vänligen fyll i användarnamn"
swedishMessage PleaseProvidePassword = "Vänligen fyll i lösenord"
swedishMessage NoIdentifierProvided = "Emailadress eller användarnamn saknas"
swedishMessage InvalidEmailAddress = "Ogiltig emailadress angiven"
swedishMessage PasswordResetTitle = "Återställning av lösenord"
swedishMessage ProvideIdentifier = "Epost eller användarnamn"
swedishMessage SendPasswordResetEmail = "Skicka email för återställning av lösenord"
swedishMessage PasswordResetPrompt = "Skriv in din emailadress eller användarnamn nedan och " `mappend`
"ett email för återställning av lösenord kommmer att skickas till dig."
swedishMessage InvalidUsernamePass = "Ogiltig kombination av användarnamn och lösenord"
-- TODO
swedishMessage i@(IdentifierNotFound _) = englishMessage i
swedishMessage Logout = "Loggar ut" -- FIXME by Google Translate
swedishMessage LogoutTitle = "Loggar ut" -- FIXME by Google Translate
swedishMessage AuthError = "Autentisering Fel" -- FIXME by Google Translate
germanMessage :: AuthMessage -> Text
germanMessage NoOpenID = "Kein OpenID-Identifier gefunden"
germanMessage LoginOpenID = "Login via OpenID"
germanMessage LoginGoogle = "Login via Google"
germanMessage LoginYahoo = "Login via Yahoo"
germanMessage Email = "E-Mail"
germanMessage UserName = "Benutzername"
germanMessage Password = "Passwort"
germanMessage CurrentPassword = "Aktuelles Passwort"
germanMessage Register = "Registrieren"
germanMessage RegisterLong = "Neuen Account registrieren"
germanMessage EnterEmail = "Bitte die E-Mail Adresse angeben, eine Bestätigungsmail wird verschickt."
germanMessage ConfirmationEmailSentTitle = "Bestätigung verschickt."
germanMessage (ConfirmationEmailSent email) =
"Eine Bestätigung wurde an " `mappend`
email `mappend`
" versandt."
germanMessage AddressVerified = "Adresse bestätigt, bitte neues Passwort angeben"
germanMessage EmailVerifiedChangePass = "Adresse bestätigt, bitte neues Passwort angeben"
germanMessage EmailVerified = "Adresse bestätigt"
germanMessage InvalidKeyTitle = "Ungültiger Bestätigungsschlüssel"
germanMessage InvalidKey = "Das war leider ein ungültiger Bestätigungsschlüssel"
germanMessage InvalidEmailPass = "Ungültiger Nutzername oder Passwort"
germanMessage BadSetPass = "Um das Passwort zu ändern muss man eingeloggt sein"
germanMessage SetPassTitle = "Passwort angeben"
germanMessage SetPass = "Neues Passwort angeben"
germanMessage NewPass = "Neues Passwort"
germanMessage ConfirmPass = "Bestätigen"
germanMessage PassMismatch = "Die Passwörter stimmen nicht überein"
germanMessage PassUpdated = "Passwort überschrieben"
germanMessage Facebook = "Login über Facebook"
germanMessage LoginViaEmail = "Login via E-Mail"
germanMessage InvalidLogin = "Ungültiger Login"
germanMessage NowLoggedIn = "Login erfolgreich"
germanMessage LoginTitle = "Anmelden"
germanMessage PleaseProvideUsername = "Bitte Nutzername angeben"
germanMessage PleaseProvidePassword = "Bitte Passwort angeben"
germanMessage NoIdentifierProvided = "Keine E-Mail-Adresse oder kein Nutzername angegeben"
germanMessage InvalidEmailAddress = "Unzulässiger E-Mail-Anbieter"
germanMessage PasswordResetTitle = "Passwort zurücksetzen"
germanMessage ProvideIdentifier = "E-Mail-Adresse oder Nutzername"
germanMessage SendPasswordResetEmail = "E-Mail zusenden um Passwort zurückzusetzen"
germanMessage PasswordResetPrompt = "Nach Einhabe der E-Mail-Adresse oder des Nutzernamen wird eine E-Mail zugesendet mit welcher das Passwort zurückgesetzt werden kann."
germanMessage InvalidUsernamePass = "Ungültige Kombination aus Nutzername und Passwort"
germanMessage i@(IdentifierNotFound _) = englishMessage i -- TODO
germanMessage Logout = "Abmelden"
germanMessage LogoutTitle = "Abmelden"
germanMessage AuthError = "Fehler beim Anmelden"
frenchMessage :: AuthMessage -> Text
frenchMessage NoOpenID = "Aucun fournisseur OpenID n'a été trouvé"
frenchMessage LoginOpenID = "Se connecter avec OpenID"
frenchMessage LoginGoogle = "Se connecter avec Google"
frenchMessage LoginYahoo = "Se connecter avec Yahoo"
frenchMessage Email = "Adresse électronique"
frenchMessage UserName = "Nom d'utilisateur" -- FIXME by Google Translate "user name"
frenchMessage Password = "Mot de passe"
frenchMessage CurrentPassword = "Mot de passe actuel"
frenchMessage Register = "S'inscrire"
frenchMessage RegisterLong = "Créer un compte"
frenchMessage EnterEmail = "Entrez ci-dessous votre adresse électronique, et un message de confirmation vous sera envoyé"
frenchMessage ConfirmationEmailSentTitle = "Message de confirmation"
frenchMessage (ConfirmationEmailSent email) =
"Un message de confirmation a été envoyé à " `mappend`
email `mappend`
"."
frenchMessage AddressVerified = "Votre adresse électronique a été validée, merci de choisir un nouveau mot de passe."
frenchMessage EmailVerifiedChangePass = "Votre adresse électronique a été validée, merci de choisir un nouveau mot de passe."
frenchMessage EmailVerified = "Votre adresse électronique a été validée"
frenchMessage InvalidKeyTitle = "Clef de validation incorrecte"
frenchMessage InvalidKey = "Désolé, mais cette clef de validation est incorrecte"
frenchMessage InvalidEmailPass = "La combinaison de ce mot de passe et de cette adresse électronique n'existe pas."
frenchMessage BadSetPass = "Vous devez être connecté pour choisir un mot de passe"
frenchMessage SetPassTitle = "Changer de mot de passe"
frenchMessage SetPass = "Choisir un nouveau mot de passe"
frenchMessage NewPass = "Nouveau mot de passe"
frenchMessage ConfirmPass = "Confirmation du mot de passe"
frenchMessage PassMismatch = "Le deux mots de passe sont différents, veuillez les corriger"
frenchMessage PassUpdated = "Le mot de passe a bien été changé"
frenchMessage Facebook = "Se connecter avec Facebook"
frenchMessage LoginViaEmail = "Se connecter avec une adresse électronique"
frenchMessage InvalidLogin = "Nom d'utilisateur incorrect"
frenchMessage NowLoggedIn = "Vous êtes maintenant connecté"
frenchMessage LoginTitle = "Se connecter"
frenchMessage PleaseProvideUsername = "Veuillez fournir votre nom d'utilisateur"
frenchMessage PleaseProvidePassword = "Veuillez fournir votre mot de passe"
frenchMessage NoIdentifierProvided = "Adresse électronique/nom d'utilisateur non spécifié"
frenchMessage InvalidEmailAddress = "Adresse électronique spécifiée invalide"
frenchMessage PasswordResetTitle = "Réinitialisation du mot de passe"
frenchMessage ProvideIdentifier = "Adresse électronique ou nom d'utilisateur"
frenchMessage SendPasswordResetEmail = "Envoi d'un courriel pour réinitialiser le mot de passe"
frenchMessage PasswordResetPrompt = "Entrez votre courriel ou votre nom d'utilisateur ci-dessous, et vous recevrez un message électronique pour réinitialiser votre mot de passe."
frenchMessage InvalidUsernamePass = "La combinaison de ce mot de passe et de ce nom d'utilisateur n'existe pas."
frenchMessage (IdentifierNotFound ident) = "Nom d'utilisateur introuvable: " `mappend` ident
frenchMessage Logout = "Déconnexion"
frenchMessage LogoutTitle = "Déconnexion"
frenchMessage AuthError = "Erreur d'authentification" -- FIXME by Google Translate
norwegianBokmålMessage :: AuthMessage -> Text
norwegianBokmålMessage NoOpenID = "Ingen OpenID-identifiserer funnet"
norwegianBokmålMessage LoginOpenID = "Logg inn med OpenID"
norwegianBokmålMessage LoginGoogle = "Logg inn med Google"
norwegianBokmålMessage LoginYahoo = "Logg inn med Yahoo"
norwegianBokmålMessage Email = "E-post"
norwegianBokmålMessage UserName = "Brukernavn" -- FIXME by Google Translate "user name"
norwegianBokmålMessage Password = "Passord"
norwegianBokmålMessage CurrentPassword = "Current password"
norwegianBokmålMessage Register = "Registrer"
norwegianBokmålMessage RegisterLong = "Registrer en ny konto"
norwegianBokmålMessage EnterEmail = "Skriv inn e-postadressen din nedenfor og en e-postkonfirmasjon vil bli sendt."
norwegianBokmålMessage ConfirmationEmailSentTitle = "E-postkonfirmasjon sendt."
norwegianBokmålMessage (ConfirmationEmailSent email) =
"En e-postkonfirmasjon har blitt sendt til " `mappend`
email `mappend`
"."
norwegianBokmålMessage AddressVerified = "Adresse verifisert, vennligst sett et nytt passord."
norwegianBokmålMessage EmailVerifiedChangePass = "Adresse verifisert, vennligst sett et nytt passord."
norwegianBokmålMessage EmailVerified = "Adresse verifisert"
norwegianBokmålMessage InvalidKeyTitle = "Ugyldig verifiseringsnøkkel"
norwegianBokmålMessage InvalidKey = "Beklager, men det var en ugyldig verifiseringsnøkkel."
norwegianBokmålMessage InvalidEmailPass = "Ugyldig e-post/passord-kombinasjon"
norwegianBokmålMessage BadSetPass = "Du må være logget inn for å sette et passord."
norwegianBokmålMessage SetPassTitle = "Sett passord"
norwegianBokmålMessage SetPass = "Sett et nytt passord"
norwegianBokmålMessage NewPass = "Nytt passord"
norwegianBokmålMessage ConfirmPass = "Bekreft"
norwegianBokmålMessage PassMismatch = "Passordene stemte ikke overens, vennligst prøv igjen"
norwegianBokmålMessage PassUpdated = "Passord oppdatert"
norwegianBokmålMessage Facebook = "Logg inn med Facebook"
norwegianBokmålMessage LoginViaEmail = "Logg inn med e-post"
norwegianBokmålMessage InvalidLogin = "Ugyldig innlogging"
norwegianBokmålMessage NowLoggedIn = "Du er nå logget inn"
norwegianBokmålMessage LoginTitle = "Logg inn"
norwegianBokmålMessage PleaseProvideUsername = "Vennligst fyll inn ditt brukernavn"
norwegianBokmålMessage PleaseProvidePassword = "Vennligst fyll inn ditt passord"
norwegianBokmålMessage NoIdentifierProvided = "No email/username provided"
norwegianBokmålMessage InvalidEmailAddress = "Invalid email address provided"
norwegianBokmålMessage PasswordResetTitle = "Password Reset"
norwegianBokmålMessage ProvideIdentifier = "Email or Username"
norwegianBokmålMessage SendPasswordResetEmail = "Send password reset email"
norwegianBokmålMessage PasswordResetPrompt = "Enter your e-mail address or username below, and a password reset e-mail will be sent to you."
norwegianBokmålMessage InvalidUsernamePass = "Invalid username/password combination"
-- TODO
norwegianBokmålMessage i@(IdentifierNotFound _) = englishMessage i
norwegianBokmålMessage Logout = "Logge ut" -- FIXME by Google Translate
norwegianBokmålMessage LogoutTitle = "Logge ut" -- FIXME by Google Translate
norwegianBokmålMessage AuthError = "Godkjenningsfeil" -- FIXME by Google Translate
japaneseMessage :: AuthMessage -> Text
japaneseMessage NoOpenID = "OpenID識別子がありません"
japaneseMessage LoginOpenID = "OpenIDでログイン"
japaneseMessage LoginGoogle = "Googleでログイン"
japaneseMessage LoginYahoo = "Yahooでログイン"
japaneseMessage Email = "Eメール"
japaneseMessage UserName = "ユーザー名" -- FIXME by Google Translate "user name"
japaneseMessage Password = "パスワード"
japaneseMessage CurrentPassword = "現在のパスワード"
japaneseMessage Register = "登録"
japaneseMessage RegisterLong = "新規アカウント登録"
japaneseMessage EnterEmail = "メールアドレスを入力してください。確認メールが送られます"
japaneseMessage ConfirmationEmailSentTitle = "確認メールを送信しました"
japaneseMessage (ConfirmationEmailSent email) =
"確認メールを " `mappend`
email `mappend`
" に送信しました"
japaneseMessage AddressVerified = "アドレスは認証されました。新しいパスワードを設定してください"
japaneseMessage EmailVerifiedChangePass = "アドレスは認証されました。新しいパスワードを設定してください"
japaneseMessage EmailVerified = "アドレスは認証されました"
japaneseMessage InvalidKeyTitle = "認証キーが無効です"
japaneseMessage InvalidKey = "申し訳ありません。無効な認証キーです"
japaneseMessage InvalidEmailPass = "メールアドレスまたはパスワードが無効です"
japaneseMessage BadSetPass = "パスワードを設定するためには、ログインしてください"
japaneseMessage SetPassTitle = "パスワードの設定"
japaneseMessage SetPass = "新しいパスワードを設定する"
japaneseMessage NewPass = "新しいパスワード"
japaneseMessage ConfirmPass = "確認"
japaneseMessage PassMismatch = "パスワードが合いません。もう一度試してください"
japaneseMessage PassUpdated = "パスワードは更新されました"
japaneseMessage Facebook = "Facebookでログイン"
japaneseMessage LoginViaEmail = "Eメールでログイン"
japaneseMessage InvalidLogin = "無効なログインです"
japaneseMessage NowLoggedIn = "ログインしました"
japaneseMessage LoginTitle = "ログイン"
japaneseMessage PleaseProvideUsername = "ユーザ名を入力してください"
japaneseMessage PleaseProvidePassword = "パスワードを入力してください"
japaneseMessage NoIdentifierProvided = "メールアドレス/ユーザ名が入力されていません"
japaneseMessage InvalidEmailAddress = "メールアドレスが無効です"
japaneseMessage PasswordResetTitle = "パスワードの再設定"
japaneseMessage ProvideIdentifier = "メールアドレスまたはユーザ名"
japaneseMessage SendPasswordResetEmail = "パスワード再設定用メールの送信"
japaneseMessage PasswordResetPrompt = "以下にメールアドレスまたはユーザ名を入力してください。パスワードを再設定するためのメールが送信されます。"
japaneseMessage InvalidUsernamePass = "ユーザ名とパスワードの組み合わせが間違っています"
japaneseMessage (IdentifierNotFound ident) =
ident `mappend` "は登録されていません"
japaneseMessage Logout = "ログアウト" -- FIXME by Google Translate
japaneseMessage LogoutTitle = "ログアウト" -- FIXME by Google Translate
japaneseMessage AuthError = "認証エラー" -- FIXME by Google Translate
finnishMessage :: AuthMessage -> Text
finnishMessage NoOpenID = "OpenID-tunnistetta ei löydy"
finnishMessage LoginOpenID = "Kirjaudu OpenID-tilillä"
finnishMessage LoginGoogle = "Kirjaudu Google-tilillä"
finnishMessage LoginYahoo = "Kirjaudu Yahoo-tilillä"
finnishMessage Email = "Sähköposti"
finnishMessage UserName = "Käyttäjätunnus" -- FIXME by Google Translate "user name"
finnishMessage Password = "Salasana"
finnishMessage CurrentPassword = "Current password"
finnishMessage Register = "Luo uusi"
finnishMessage RegisterLong = "Luo uusi tili"
finnishMessage EnterEmail = "Kirjoita alle sähköpostiosoitteesi, johon vahvistussähköposti lähetetään."
finnishMessage ConfirmationEmailSentTitle = "Vahvistussähköposti lähetetty."
finnishMessage (ConfirmationEmailSent email) =
"Vahvistussähköposti on lähetty osoitteeseen " `mappend`
email `mappend`
"."
finnishMessage AddressVerified = "Sähköpostiosoite vahvistettu. Anna uusi salasana"
finnishMessage EmailVerifiedChangePass = "Sähköpostiosoite vahvistettu. Anna uusi salasana"
finnishMessage EmailVerified = "Sähköpostiosoite vahvistettu"
finnishMessage InvalidKeyTitle = "Virheellinen varmistusavain"
finnishMessage InvalidKey = "Valitettavasti varmistusavain on virheellinen."
finnishMessage InvalidEmailPass = "Virheellinen sähköposti tai salasana."
finnishMessage BadSetPass = "Kirjaudu ensin sisään asettaaksesi salasanan"
finnishMessage SetPassTitle = "Salasanan asettaminen"
finnishMessage SetPass = "Aseta uusi salasana"
finnishMessage NewPass = "Uusi salasana"
finnishMessage ConfirmPass = "Vahvista"
finnishMessage PassMismatch = "Salasanat eivät täsmää"
finnishMessage PassUpdated = "Salasana vaihdettu"
finnishMessage Facebook = "Kirjaudu Facebook-tilillä"
finnishMessage LoginViaEmail = "Kirjaudu sähköpostitilillä"
finnishMessage InvalidLogin = "Kirjautuminen epäonnistui"
finnishMessage NowLoggedIn = "Olet nyt kirjautunut sisään"
finnishMessage LoginTitle = "Kirjautuminen"
finnishMessage PleaseProvideUsername = "Käyttäjänimi puuttuu"
finnishMessage PleaseProvidePassword = "Salasana puuttuu"
finnishMessage NoIdentifierProvided = "Sähköpostiosoite/käyttäjänimi puuttuu"
finnishMessage InvalidEmailAddress = "Annettu sähköpostiosoite ei kelpaa"
finnishMessage PasswordResetTitle = "Uuden salasanan tilaaminen"
finnishMessage ProvideIdentifier = "Sähköpostiosoite tai käyttäjänimi"
finnishMessage SendPasswordResetEmail = "Lähetä uusi salasana sähköpostitse"
finnishMessage PasswordResetPrompt = "Anna sähköpostiosoitteesi tai käyttäjätunnuksesi alla, niin lähetämme uuden salasanan sähköpostitse."
finnishMessage InvalidUsernamePass = "Virheellinen käyttäjänimi tai salasana."
-- TODO
finnishMessage i@(IdentifierNotFound _) = englishMessage i
finnishMessage Logout = "Kirjaudu ulos" -- FIXME by Google Translate
finnishMessage LogoutTitle = "Kirjaudu ulos" -- FIXME by Google Translate
finnishMessage AuthError = "Authentication Error" -- FIXME by Google Translate
chineseMessage :: AuthMessage -> Text
chineseMessage NoOpenID = "无效的OpenID"
chineseMessage LoginOpenID = "用OpenID登录"
chineseMessage LoginGoogle = "用Google帐户登录"
chineseMessage LoginYahoo = "用Yahoo帐户登录"
chineseMessage Email = "邮箱"
chineseMessage UserName = "用户名"
chineseMessage Password = "密码"
chineseMessage CurrentPassword = "当前密码"
chineseMessage Register = "注册"
chineseMessage RegisterLong = "注册新帐户"
chineseMessage EnterEmail = "输入你的邮箱地址,你将收到一封确认邮件。"
chineseMessage ConfirmationEmailSentTitle = "确认邮件已发送"
chineseMessage (ConfirmationEmailSent email) =
"确认邮件已发送至 " `mappend`
email `mappend`
"."
chineseMessage AddressVerified = "地址验证成功,请设置新密码"
chineseMessage EmailVerifiedChangePass = "地址验证成功,请设置新密码"
chineseMessage EmailVerified = "地址验证成功"
chineseMessage InvalidKeyTitle = "无效的验证码"
chineseMessage InvalidKey = "对不起,验证码无效。"
chineseMessage InvalidEmailPass = "无效的邮箱/密码组合"
chineseMessage BadSetPass = "你需要登录才能设置密码"
chineseMessage SetPassTitle = "设置密码"
chineseMessage SetPass = "设置新密码"
chineseMessage NewPass = "新密码"
chineseMessage ConfirmPass = "确认"
chineseMessage PassMismatch = "密码不匹配,请重新输入"
chineseMessage PassUpdated = "密码更新成功"
chineseMessage Facebook = "用Facebook帐户登录"
chineseMessage LoginViaEmail = "用邮箱登录"
chineseMessage InvalidLogin = "登录失败"
chineseMessage NowLoggedIn = "登录成功"
chineseMessage LoginTitle = "登录"
chineseMessage PleaseProvideUsername = "请输入用户名"
chineseMessage PleaseProvidePassword = "请输入密码"
chineseMessage NoIdentifierProvided = "缺少邮箱/用户名"
chineseMessage InvalidEmailAddress = "无效的邮箱地址"
chineseMessage PasswordResetTitle = "重置密码"
chineseMessage ProvideIdentifier = "邮箱或用户名"
chineseMessage SendPasswordResetEmail = "发送密码重置邮件"
chineseMessage PasswordResetPrompt = "输入你的邮箱地址或用户名,你将收到一封密码重置邮件。"
chineseMessage InvalidUsernamePass = "无效的用户名/密码组合"
chineseMessage (IdentifierNotFound ident) = "邮箱/用户名不存在: " `mappend` ident
chineseMessage Logout = "注销"
chineseMessage LogoutTitle = "注销"
chineseMessage AuthError = "验证错误"
czechMessage :: AuthMessage -> Text
czechMessage NoOpenID = "Nebyl nalezen identifikátor OpenID"
czechMessage LoginOpenID = "Přihlásit přes OpenID"
czechMessage LoginGoogle = "Přihlásit přes Google"
czechMessage LoginYahoo = "Přihlásit přes Yahoo"
czechMessage Email = "E-mail"
czechMessage UserName = "Uživatelské jméno"
czechMessage Password = "Heslo"
czechMessage CurrentPassword = "Current password"
czechMessage Register = "Registrovat"
czechMessage RegisterLong = "Zaregistrovat nový účet"
czechMessage EnterEmail = "Níže zadejte svou e-mailovou adresu a bude vám poslán potvrzovací e-mail."
czechMessage ConfirmationEmailSentTitle = "Potvrzovací e-mail odeslán"
czechMessage (ConfirmationEmailSent email) =
"Potvrzovací e-mail byl odeslán na " `mappend` email `mappend` "."
czechMessage AddressVerified = "Adresa byla ověřena, prosím nastavte si nové heslo"
czechMessage EmailVerifiedChangePass = "Adresa byla ověřena, prosím nastavte si nové heslo"
czechMessage EmailVerified = "Adresa byla ověřena"
czechMessage InvalidKeyTitle = "Neplatný ověřovací klíč"
czechMessage InvalidKey = "Bohužel, ověřovací klíč je neplatný."
czechMessage InvalidEmailPass = "Neplatná kombinace e-mail/heslo"
czechMessage BadSetPass = "Pro nastavení hesla je vyžadováno přihlášení"
czechMessage SetPassTitle = "Nastavit heslo"
czechMessage SetPass = "Nastavit nové heslo"
czechMessage NewPass = "Nové heslo"
czechMessage ConfirmPass = "Potvrdit"
czechMessage PassMismatch = "Hesla si neodpovídají, zkuste to znovu"
czechMessage PassUpdated = "Heslo aktualizováno"
czechMessage Facebook = "Přihlásit přes Facebook"
czechMessage LoginViaEmail = "Přihlásit přes e-mail"
czechMessage InvalidLogin = "Neplatné přihlášení"
czechMessage NowLoggedIn = "Přihlášení proběhlo úspěšně"
czechMessage LoginTitle = "Přihlásit"
czechMessage PleaseProvideUsername = "Prosím, zadejte svoje uživatelské jméno"
czechMessage PleaseProvidePassword = "Prosím, zadejte svoje heslo"
czechMessage NoIdentifierProvided = "Nebyl poskytnut žádný e-mail nebo uživatelské jméno"
czechMessage InvalidEmailAddress = "Zadaná e-mailová adresa je neplatná"
czechMessage PasswordResetTitle = "Obnovení hesla"
czechMessage ProvideIdentifier = "E-mail nebo uživatelské jméno"
czechMessage SendPasswordResetEmail = "Poslat e-mail pro obnovení hesla"
czechMessage PasswordResetPrompt = "Zadejte svou e-mailovou adresu nebo uživatelské jméno a bude vám poslán email pro obnovení hesla."
czechMessage InvalidUsernamePass = "Neplatná kombinace uživatelského jména a hesla"
-- TODO
czechMessage i@(IdentifierNotFound _) = englishMessage i
czechMessage Logout = "Odhlásit" -- FIXME by Google Translate
czechMessage LogoutTitle = "Odhlásit" -- FIXME by Google Translate
czechMessage AuthError = "Chyba ověřování" -- FIXME by Google Translate
-- Так как e-mail – это фактическое сокращение словосочетания electronic mail,
-- для русского перевода так же использовано сокращение: эл.почта
russianMessage :: AuthMessage -> Text
russianMessage NoOpenID = "Идентификатор OpenID не найден"
russianMessage LoginOpenID = "Вход с помощью OpenID"
russianMessage LoginGoogle = "Вход с помощью Google"
russianMessage LoginYahoo = "Вход с помощью Yahoo"
russianMessage Email = "Эл.почта"
russianMessage UserName = "Имя пользователя"
russianMessage Password = "Пароль"
russianMessage CurrentPassword = "Старый пароль"
russianMessage Register = "Регистрация"
russianMessage RegisterLong = "Создать учётную запись"
russianMessage EnterEmail = "Введите свой адрес эл.почты ниже, вам будет отправлено письмо для подтверждения."
russianMessage ConfirmationEmailSentTitle = "Письмо для подтверждения отправлено"
russianMessage (ConfirmationEmailSent email) =
"Письмо для подтверждения было отправлено на адрес " `mappend`
email `mappend`
"."
russianMessage AddressVerified = "Адрес подтверждён. Пожалуйста, установите новый пароль."
russianMessage EmailVerifiedChangePass = "Адрес подтверждён. Пожалуйста, установите новый пароль."
russianMessage EmailVerified = "Адрес подтверждён"
russianMessage InvalidKeyTitle = "Неверный ключ подтверждения"
russianMessage InvalidKey = "Извините, но ключ подтверждения оказался недействительным."
russianMessage InvalidEmailPass = "Неверное сочетание эл.почты и пароля"
russianMessage BadSetPass = "Чтобы изменить пароль, необходимо выполнить вход"
russianMessage SetPassTitle = "Установить пароль"
russianMessage SetPass = "Установить новый пароль"
russianMessage NewPass = "Новый пароль"
russianMessage ConfirmPass = "Подтверждение пароля"
russianMessage PassMismatch = "Пароли не совпадают, повторите снова"
russianMessage PassUpdated = "Пароль обновлён"
russianMessage Facebook = "Войти с помощью Facebook"
russianMessage LoginViaEmail = "Войти по адресу эл.почты"
russianMessage InvalidLogin = "Неверный логин"
russianMessage NowLoggedIn = "Вход выполнен"
russianMessage LoginTitle = "Войти"
russianMessage PleaseProvideUsername = "Пожалуйста, введите ваше имя пользователя"
russianMessage PleaseProvidePassword = "Пожалуйста, введите ваш пароль"
russianMessage NoIdentifierProvided = "Не указан адрес эл.почты/имя пользователя"
russianMessage InvalidEmailAddress = "Указан неверный адрес эл.почты"
russianMessage PasswordResetTitle = "Сброс пароля"
russianMessage ProvideIdentifier = "Имя пользователя или эл.почта"
russianMessage SendPasswordResetEmail = "Отправить письмо для сброса пароля"
russianMessage PasswordResetPrompt = "Введите адрес эл.почты или ваше имя пользователя ниже, вам будет отправлено письмо для сброса пароля."
russianMessage InvalidUsernamePass = "Неверное сочетание имени пользователя и пароля"
russianMessage (IdentifierNotFound ident) = "Логин не найден: " `mappend` ident
russianMessage Logout = "Выйти"
russianMessage LogoutTitle = "Выйти"
russianMessage AuthError = "Ошибка аутентификации"
dutchMessage :: AuthMessage -> Text
dutchMessage NoOpenID = "Geen OpenID identificator gevonden"
dutchMessage LoginOpenID = "Inloggen via OpenID"
dutchMessage LoginGoogle = "Inloggen via Google"
dutchMessage LoginYahoo = "Inloggen via Yahoo"
dutchMessage Email = "E-mail"
dutchMessage UserName = "Gebruikersnaam"
dutchMessage Password = "Wachtwoord"
dutchMessage CurrentPassword = "Huidig wachtwoord"
dutchMessage Register = "Registreren"
dutchMessage RegisterLong = "Registreer een nieuw account"
dutchMessage EnterEmail = "Voer uw e-mailadres hieronder in, er zal een bevestigings-e-mail naar u worden verzonden."
dutchMessage ConfirmationEmailSentTitle = "Bevestigings-e-mail verzonden"
dutchMessage (ConfirmationEmailSent email) =
"Een bevestigings-e-mail is verzonden naar " `mappend`
email `mappend`
"."
dutchMessage AddressVerified = "Adres geverifieerd, stel alstublieft een nieuwe wachtwoord in"
dutchMessage EmailVerifiedChangePass = "Adres geverifieerd, stel alstublieft een nieuwe wachtwoord in"
dutchMessage EmailVerified = "Adres geverifieerd"
dutchMessage InvalidKeyTitle = "Ongeldig verificatietoken"
dutchMessage InvalidKey = "Dat was helaas een ongeldig verificatietoken."
dutchMessage InvalidEmailPass = "Ongeldige e-mailadres/wachtwoord combinatie"
dutchMessage BadSetPass = "U moet ingelogd zijn om een nieuwe wachtwoord in te stellen"
dutchMessage SetPassTitle = "Wachtwoord instellen"
dutchMessage SetPass = "Een nieuwe wachtwoord instellen"
dutchMessage NewPass = "Nieuw wachtwoord"
dutchMessage ConfirmPass = "Bevestig"
dutchMessage PassMismatch = "Wachtwoorden kwamen niet overeen, probeer het alstublieft nog eens"
dutchMessage PassUpdated = "Wachtwoord geüpdatet"
dutchMessage Facebook = "Inloggen met Facebook"
dutchMessage LoginViaEmail = "Inloggen via e-mail"
dutchMessage InvalidLogin = "Ongeldige inloggegevens"
dutchMessage NowLoggedIn = "U bent nu ingelogd"
dutchMessage LoginTitle = "Inloggen"
dutchMessage PleaseProvideUsername = "Voer alstublieft uw gebruikersnaam in"
dutchMessage PleaseProvidePassword = "Voer alstublieft uw wachtwoord in"
dutchMessage NoIdentifierProvided = "Geen e-mailadres/gebruikersnaam opgegeven"
dutchMessage InvalidEmailAddress = "Ongeldig e-mailadres opgegeven"
dutchMessage PasswordResetTitle = "Wachtwoord wijzigen"
dutchMessage ProvideIdentifier = "E-mailadres of gebruikersnaam"
dutchMessage SendPasswordResetEmail = "Stuur een wachtwoord reset e-mail"
dutchMessage PasswordResetPrompt = "Voer uw e-mailadres of gebruikersnaam hieronder in, er zal een e-mail naar u worden verzonden waarmee u uw wachtwoord kunt wijzigen."
dutchMessage InvalidUsernamePass = "Ongeldige gebruikersnaam/wachtwoord combinatie"
dutchMessage (IdentifierNotFound ident) = "Inloggegevens niet gevonden: " `mappend` ident
dutchMessage Logout = "Uitloggen"
dutchMessage LogoutTitle = "Uitloggen"
dutchMessage AuthError = "Verificatiefout"
croatianMessage :: AuthMessage -> Text
croatianMessage NoOpenID = "Nije pronađen OpenID identifikator"
croatianMessage LoginOpenID = "Prijava uz OpenID"
croatianMessage LoginGoogle = "Prijava uz Google"
croatianMessage LoginYahoo = "Prijava uz Yahoo"
croatianMessage Facebook = "Prijava uz Facebook"
croatianMessage LoginViaEmail = "Prijava putem e-pošte"
croatianMessage Email = "E-pošta"
croatianMessage UserName = "Korisničko ime"
croatianMessage Password = "Lozinka"
croatianMessage CurrentPassword = "Current Password"
croatianMessage Register = "Registracija"
croatianMessage RegisterLong = "Registracija novog računa"
croatianMessage EnterEmail = "Dolje unesite adresu e-pošte, pa ćemo vam poslati e-poruku za potvrdu."
croatianMessage PasswordResetPrompt = "Dolje unesite adresu e-pošte ili korisničko ime, pa ćemo vam poslati e-poruku za potvrdu."
croatianMessage ConfirmationEmailSentTitle = "E-poruka za potvrdu"
croatianMessage (ConfirmationEmailSent email) = "E-poruka za potvrdu poslana je na adresu " <> email <> "."
croatianMessage AddressVerified = "Adresa ovjerena, postavite novu lozinku"
croatianMessage EmailVerifiedChangePass = "Adresa ovjerena, postavite novu lozinku"
croatianMessage EmailVerified = "Adresa ovjerena"
croatianMessage InvalidKeyTitle = "Ključ za ovjeru nije valjan"
croatianMessage InvalidKey = "Nažalost, taj ključ za ovjeru nije valjan."
croatianMessage InvalidEmailPass = "Kombinacija e-pošte i lozinke nije valjana"
croatianMessage InvalidUsernamePass = "Kombinacija korisničkog imena i lozinke nije valjana"
croatianMessage BadSetPass = "Za postavljanje lozinke morate biti prijavljeni"
croatianMessage SetPassTitle = "Postavi lozinku"
croatianMessage SetPass = "Postavite novu lozinku"
croatianMessage NewPass = "Nova lozinka"
croatianMessage ConfirmPass = "Potvrda lozinke"
croatianMessage PassMismatch = "Lozinke se ne podudaraju, pokušajte ponovo"
croatianMessage PassUpdated = "Lozinka ažurirana"
croatianMessage InvalidLogin = "Prijava nije valjana"
croatianMessage NowLoggedIn = "Sada ste prijavljeni u"
croatianMessage LoginTitle = "Prijava"
croatianMessage PleaseProvideUsername = "Unesite korisničko ime"
croatianMessage PleaseProvidePassword = "Unesite lozinku"
croatianMessage NoIdentifierProvided = "Nisu dani e-pošta/korisničko ime"
croatianMessage InvalidEmailAddress = "Dana adresa e-pošte nije valjana"
croatianMessage PasswordResetTitle = "Poništavanje lozinke"
croatianMessage ProvideIdentifier = "E-pošta ili korisničko ime"
croatianMessage SendPasswordResetEmail = "Pošalji e-poruku za poništavanje lozinke"
croatianMessage (IdentifierNotFound ident) = "Korisničko ime/e-pošta nisu pronađeni: " <> ident
croatianMessage Logout = "Odjava"
croatianMessage LogoutTitle = "Odjava"
croatianMessage AuthError = "Pogreška provjere autentičnosti"
danishMessage :: AuthMessage -> Text
danishMessage NoOpenID = "Mangler OpenID identifier"
danishMessage LoginOpenID = "Login med OpenID"
danishMessage LoginGoogle = "Login med Google"
danishMessage LoginYahoo = "Login med Yahoo"
danishMessage Email = "E-mail"
danishMessage UserName = "Brugernavn"
danishMessage Password = "Kodeord"
danishMessage CurrentPassword = "Nuværende kodeord"
danishMessage Register = "Opret"
danishMessage RegisterLong = "Opret en ny konto"
danishMessage EnterEmail = "Indtast din e-mailadresse nedenfor og en bekræftelsesmail vil blive sendt til dig."
danishMessage ConfirmationEmailSentTitle = "Bekræftelsesmail sendt"
danishMessage (ConfirmationEmailSent email) =
"En bekræftelsesmail er sendt til " `mappend`
email `mappend`
"."
danishMessage AddressVerified = "Adresse bekræftet, sæt venligst et nyt kodeord"
danishMessage EmailVerifiedChangePass = "Adresse bekræftet, sæt venligst et nyt kodeord"
danishMessage EmailVerified = "Adresse bekræftet"
danishMessage InvalidKeyTitle = "Ugyldig verifikationsnøgle"
danishMessage InvalidKey = "Beklager, det var en ugyldigt verifikationsnøgle."
danishMessage InvalidEmailPass = "Ugyldigt e-mail/kodeord"
danishMessage BadSetPass = "Du skal være logget ind for at sætte et kodeord"
danishMessage SetPassTitle = "Sæt kodeord"
danishMessage SetPass = "Sæt et nyt kodeord"
danishMessage NewPass = "Nyt kodeord"
danishMessage ConfirmPass = "Bekræft"
danishMessage PassMismatch = "Kodeordne var forskellige, prøv venligst igen"
danishMessage PassUpdated = "Kodeord opdateret"
danishMessage Facebook = "Login med Facebook"
danishMessage LoginViaEmail = "Login med e-mail"
danishMessage InvalidLogin = "Ugyldigt login"
danishMessage NowLoggedIn = "Du er nu logget ind"
danishMessage LoginTitle = "Log ind"
danishMessage PleaseProvideUsername = "Indtast venligst dit brugernavn"
danishMessage PleaseProvidePassword = "Indtasy venligst dit kodeord"
danishMessage NoIdentifierProvided = "Mangler e-mail/username"
danishMessage InvalidEmailAddress = "Ugyldig e-mailadresse indtastet"
danishMessage PasswordResetTitle = "Nulstilning af kodeord"
danishMessage ProvideIdentifier = "E-mail eller brugernavn"
danishMessage SendPasswordResetEmail = "Send kodeordsnulstillingsmail"
danishMessage PasswordResetPrompt = "Indtast din e-mailadresse eller dit brugernavn nedenfor, så bliver en kodeordsnulstilningsmail sendt til dig."
danishMessage InvalidUsernamePass = "Ugyldigt brugernavn/kodeord"
danishMessage (IdentifierNotFound ident) = "Brugernavn findes ikke: " `mappend` ident
danishMessage Logout = "Log ud"
danishMessage LogoutTitle = "Log ud"
danishMessage AuthError = "Fejl ved bekræftelse af identitet"
koreanMessage :: AuthMessage -> Text
koreanMessage NoOpenID = "OpenID ID가 없습니다"
koreanMessage LoginOpenID = "OpenID로 로그인"
koreanMessage LoginGoogle = "Google로 로그인"
koreanMessage LoginYahoo = "Yahoo로 로그인"
koreanMessage Email = "이메일"
koreanMessage UserName = "사용자 이름"
koreanMessage Password = "비밀번호"
koreanMessage CurrentPassword = "현재 비밀번호"
koreanMessage Register = "등록"
koreanMessage RegisterLong = "새 계정 등록"
koreanMessage EnterEmail = "이메일 주소를 아래에 입력하시면 확인 이메일이 발송됩니다."
koreanMessage ConfirmationEmailSentTitle = "확인 이메일을 보냈습니다"
koreanMessage (ConfirmationEmailSent email) =
"확인 이메일을 " `mappend`
email `mappend`
"에 보냈습니다."
koreanMessage AddressVerified = "주소가 인증되었습니다. 새 비밀번호를 설정하세요."
koreanMessage EmailVerifiedChangePass = "주소가 인증되었습니다. 새 비밀번호를 설정하세요."
koreanMessage EmailVerified = "주소가 인증되었습니다"
koreanMessage InvalidKeyTitle = "인증키가 잘못되었습니다"
koreanMessage InvalidKey = "죄송합니다. 잘못된 인증키입니다."
koreanMessage InvalidEmailPass = "이메일 주소나 비밀번호가 잘못되었습니다"
koreanMessage BadSetPass = "비밀번호를 설정하기 위해서는 로그인해야 합니다"
koreanMessage SetPassTitle = "비밀번호 설정"
koreanMessage SetPass = "새 비밀번호 설정"
koreanMessage NewPass = "새 비밀번호"
koreanMessage ConfirmPass = "확인"
koreanMessage PassMismatch = "비밀번호가 맞지 않습니다. 다시 시도해주세요."
koreanMessage PassUpdated = "비밀번호가 업데이트 되었습니다"
koreanMessage Facebook = "Facebook으로 로그인"
koreanMessage LoginViaEmail = "이메일로"
koreanMessage InvalidLogin = "잘못된 로그인입니다"
koreanMessage NowLoggedIn = "로그인했습니다"
koreanMessage LoginTitle = "로그인"
koreanMessage PleaseProvideUsername = "사용자 이름을 입력하세요"
koreanMessage PleaseProvidePassword = "비밀번호를 입력하세요"
koreanMessage NoIdentifierProvided = "이메일 주소나 사용자 이름이 입력되어 있지 않습니다"
koreanMessage InvalidEmailAddress = "이메일 주소가 잘못되었습니다"
koreanMessage PasswordResetTitle = "비밀번호 변경"
koreanMessage ProvideIdentifier = "이메일 주소나 사용자 이름"
koreanMessage SendPasswordResetEmail = "비밀번호 재설정 이메일 보내기"
koreanMessage PasswordResetPrompt = "이메일 주소나 사용자 이름을 아래에 입력하시면 비밀번호 재설정 이메일이 발송됩니다."
koreanMessage InvalidUsernamePass = "사용자 이름이나 비밀번호가 잘못되었습니다"
koreanMessage (IdentifierNotFound ident) = ident `mappend` "는 등록되어 있지 않습니다"
koreanMessage Logout = "로그아웃"
koreanMessage LogoutTitle = "로그아웃"
koreanMessage AuthError = "인증오류"
| yesodweb/yesod | yesod-auth/Yesod/Auth/Message.hs | mit | 51,070 | 3 | 8 | 5,757 | 6,642 | 3,427 | 3,215 | 836 | 1 |
module Y2018.M02.D02.Solution where
{--
We have been able to download sets of articles and then we've triaged them,
but before we do triage, we have to do a bifurcation from before: we don't
want Associated Press articles showing up in our NEW / UPDATED / REDUNDANT
stacks.
Today's Haskell problem is to remove the AP articles from the downloaded
packets.
Hint: you may have seen this before in a different context.
--}
import Control.Monad ((>=>))
import Control.Monad.Writer
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Time
import Database.PostgreSQL.Simple (Connection, connect, close)
-- below imports available via 1HaskellADay git repository
import Control.DList (dlToList)
import Control.Logic.Frege (assert)
import Data.Logger (Logger, LogEntry)
import Data.Time.Stamped (Stamped)
import Store.SQL.Connection (withConnection, Database(PILOT))
import Y2017.M12.D27.Solution (DatedArticle)
import Y2017.M12.D29.Solution (apArt)
import Y2018.M01.D26.Solution (ow)
import Y2018.M01.D29.Solution (oneWeekAgo)
import Y2018.M01.D30.Solution hiding (main') -- for triaging from the triage
deAPify :: DatedArticle a -> Maybe (DatedArticle a)
deAPify = assert apArt
-- given a parsed article, remove it (return Nothing) if it's an AP article
-- How many articles did you download?
-- How many articles were left after you delinted the AP articles?
{--
>>> connectInfo
ConnectInfo {connectHost = "...", ...}
>>> conn <- connect it
>>> owa <- oneWeekAgo conn
>>> owa
2018-01-23
>>> (packs,log) <- runWriterT (ow owa 0 [])
>>> length packs
5
>>> arts = articles packs
>>> length arts
459
>>> pilotArts = filter (apArt . snd . snd) (articles packs)
>>> length pilotArts
444
--}
{-- BONUS -----------------------------------------------------------------
Recreate the triage report app that downloads the articles and triages them,
but this time, first removes the AP articles
--}
triageSansAP :: Connection
-> IO (([ArticleMetaData], Map Triage [ArticleTriageInformation]), [Stamped LogEntry])
triageSansAP conn = do
owa <- oneWeekAgo conn
(packs,log) <- runWriterT (ow owa 0 [])
putStrLn ("Fetched " ++ show (length packs) ++ " packets")
let term = addDays (-1) owa
let arts = articles packs
let pilotArts = filter (apArt . snd . snd) arts
putStrLn ("Excluded " ++ show (length arts - length pilotArts)
++ " AP articles")
amd <- fetchArticleMetaData conn term
return ((amd, triageArticles amd pilotArts), dlToList log)
main' :: [String] -> IO ()
main' [] = errmsg
main' ["go"] = withConnection PILOT (triageSansAP >=> \((_,tri), log) ->
mapM_ print log >>
print (Map.map length tri))
main' _ = errmsg
| geophf/1HaskellADay | exercises/HAD/Y2018/M02/D02/Solution.hs | mit | 2,737 | 0 | 14 | 499 | 564 | 314 | 250 | 38 | 1 |
{-# OPTIONS_JHC -fno-prelude -fffi #-}
module Jhc.Storable(Storable_(..)) where
import Jhc.Basics
import Jhc.Addr
import Jhc.IO
class Storable_ a where
sizeOf_ :: a -> Word__
alignment_ :: a -> Word__
peekElemOff_ :: Addr__ -> Word__ -> IO a
pokeElemOff_ :: Addr__ -> Word__ -> a -> UIO_
peek_ :: Addr__ -> IO a
poke_ :: Addr__ -> a -> UIO_
alignment x = sizeOf x
peekElemOff addr idx = res where
res = IO $ \w -> unIO (peek_ (addr `plus` (idx `times` sizeOf_ (_f res)))) w
pokeElemOff addr idx x = \w -> poke_ (addr `plus` (idx `times` sizeOf_ x)) x w
_f :: IO a -> a
_f _ = undefined
foreign import "Add" plus :: BitsPtr_ -> Word__ -> BitsPtr_
foreign import "UMul" plus :: Word__ -> Word__ -> Word__
| m-alvarez/jhc | lib/jhc/Jhc/Storable.hs | mit | 752 | 0 | 20 | 180 | 296 | 161 | 135 | -1 | -1 |
-- Parenthesization
---- (2^) $ (+2) $ 3*2
---- (2^) $ 2 + 2 $ (*30)
---- (2^) $ 2 + 2 $ (*30)
---- 2 + 2 $ (*30)
---- (2 + 2) (*30)
---- 4 (* 30)
---- (2^) $ (*30) $ 2 + 2
---- (2^) $ (*30) $ 2 + 2
---- (2^) $ (*30) 4
---- (2^) $ 120
---- (2^) 120
---- 1329227995784915872903807060280344576
---- 1. 2 + 2 * 3 - 1
---- 2 + (2 * 3) - 1
---- 2. (^) 10 $ 1 + 1
---- (^) 10 (1 + 1)
---- 3. 2 ^ 2 * 4 ^ 5 + 1
---- (2 ^ 2) * (4 ^ 5) + 1
-- Equivalent expressions
-- 1. 1 + 1
-- 2
-- 2. 10 ^ 2
-- 10 + 9 * 10
-- 3. 400 - 37
-- (-) 37 400
-- 4. 100 `div` 3
-- 100 / 3
-- 5. 2 * 5 + 18
-- 2 * (5 + 18)
-- 1. Same
-- 2. Same
-- 3. Different
-- 4. Different
-- 5. Different
| diminishedprime/.org | reading-list/haskell_programming_from_first_principles/02_13.hs | mit | 720 | 0 | 2 | 245 | 37 | 36 | 1 | 1 | 0 |
import Network.Socket
import System.IO
import Control.Concurrent
import Network.Connection
import qualified Data.ByteString.Char8 as BSC
import Aws
import Aws.Core
import Aws.General
import Aws.Sns
import Data.IORef
import Data.Time.Clock
import qualified Data.Text as DT
main :: IO ()
main = do
-- create socket
sock <- socket AF_INET Stream 0
-- make socket immediately reusable - eases debugging.
setSocketOption sock ReuseAddr 1
-- listen on TCP port 4242
bindSocket sock (SockAddrInet 4242 iNADDR_ANY)
-- allow a maximum of 2 outstanding connections
listen sock 2
sendToSns "test"
mainLoop sock
mainLoop :: Socket -> IO ()
mainLoop sock = do
conn <- accept sock
forkIO (runConn conn)
mainLoop sock
runConn :: (Socket, SockAddr) -> IO ()
runConn (sock, _) = do
hdl <- socketToHandle sock ReadWriteMode
hSetBuffering hdl NoBuffering
con <- startTls
forkIO (serverToClient con hdl)
forkIO (clientToServer hdl con)
return ()
--hClose hdl
--connectionClose con
serverToClient :: Connection -> Handle -> IO ()
serverToClient con hdl = do
msg <- connectionGet con 1024
putStrLn $ "Server says: " ++ (BSC.unpack msg)
hPutStrLn hdl $ BSC.unpack msg
serverToClient con hdl
clientToServer :: Handle -> Connection -> IO ()
clientToServer hdl con = do
msg <- hGetLine hdl
putStrLn $ "Client says: " ++ msg
connectionPut con $ BSC.pack msg
clientToServer hdl con
startTls :: IO Connection
startTls = do
ctx <- initConnectionContext
con <- connectTo ctx $ ConnectionParams
{ connectionHostname = "skynet.csh.rit.edu"
, connectionPort = 6697
, connectionUseSecure = Just $ TLSSettingsSimple True False False
, connectionUseSocks = Nothing
}
return con
sendToSns :: String -> IO ()
sendToSns msg = do
snsioref <- newIORef []
creds <- makeCredentials (BSC.pack "asdf") (BSC.pack "asdf")
let cfg = Aws.Configuration (ExpiresIn 3600) creds (Aws.defaultLog Aws.Debug)
let snsCfg = SnsConfiguration HTTPS UsWest2
let arn = Arn ServiceNamespaceSns (Just UsWest2) (Just $ AccountId $ DT.pack "1337") ([DT.pack "asdf"])
topics <- simpleAws cfg snsCfg $ Publish (snsMessage (DT.pack msg)) Nothing Nothing (Right arn)
putStrLn $ show topics
| dgonyeo/irc-locator | Locator.hs | mit | 2,433 | 1 | 14 | 629 | 760 | 362 | 398 | 63 | 1 |
-- PutJSON.hs
module PutJSON where
import Data.List (intercalate)
import SimpleJSON
renderJValue :: JValue -> String
renderJValue (JString s) = show s
renderJValue (JNumber n) = show s
renderJValue (JBool True) = "true"
renderJValue (JBool False) = "false"
renderJValue (JNull) = "null"
renderJValue (JObject o) = "{" ++ pairs o ++ "}"
where pairs [] = ""
pairs ps = intercalate ", " (map renderPair ps)
renderPair (k,v) = show k ++ ": " ++ renderJValue v
renderJValue (JArray a) = "[" ++ values ++ "]"
where values [] = ""
values vs = intercalate ", " (map renderJValue vs)
putJValue :: JValue -> IO ()
putJValue v = putStrLn (renderJValue v) | sammyd/Learning-Haskell | ch05/PutJSON.hs | mit | 696 | 0 | 9 | 163 | 272 | 137 | 135 | 18 | 3 |
type Vector = (Double, Double)
data Shape = Circle Vector Double
| Poly [Vector]
| akampjes/learning-realworldhaskell | ch03/ShapeUnion.hs | mit | 97 | 0 | 7 | 30 | 32 | 19 | 13 | -1 | -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.