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 Lamdu.GUI.Expr.TagEdit
( makeRecordTag, makeVariantTag
, makeParamTag, addParamId
, makeArgTag
, makeTagHoleEdit
, makeBinderTagEdit
) where
import qualified Control.Lens as Lens
import qualified Data.Char as Char
import Data.MRUMemo (memo)
import qualified Data.Property as Property
import qualified Data.Text as Text
import qualified GUI.Momentu as M
import qualified GUI.Momentu.Element as Element
import GUI.Momentu.EventMap (EventMap)
import qualified GUI.Momentu.EventMap as E
import qualified GUI.Momentu.Glue as Glue
import qualified GUI.Momentu.Hover as Hover
import qualified GUI.Momentu.I18N as MomentuTexts
import qualified GUI.Momentu.State as GuiState
import qualified GUI.Momentu.Widget as Widget
import qualified GUI.Momentu.Widgets.Menu as Menu
import qualified GUI.Momentu.Widgets.Menu.Search as SearchMenu
import qualified GUI.Momentu.Widgets.Spacer as Spacer
import qualified GUI.Momentu.Widgets.TextView as TextView
import qualified Lamdu.Config as Config
import qualified Lamdu.Config.Theme as Theme
import Lamdu.Config.Theme.TextColors (TextColors)
import qualified Lamdu.Config.Theme.TextColors as TextColors
import Lamdu.Fuzzy (Fuzzy)
import qualified Lamdu.Fuzzy as Fuzzy
import Lamdu.GUI.Monad (GuiM)
import qualified Lamdu.GUI.Monad as GuiM
import qualified Lamdu.GUI.NameView as NameView
import qualified Lamdu.GUI.Styled as Styled
import qualified Lamdu.GUI.TagView as TagView
import qualified Lamdu.GUI.WidgetIds as WidgetIds
import qualified Lamdu.I18N.CodeUI as Texts
import qualified Lamdu.I18N.Navigation as Texts
import Lamdu.Name (Name(..))
import qualified Lamdu.Name as Name
import qualified Lamdu.Style as Style
import Lamdu.Sugar.EntityId (EntityId)
import qualified Lamdu.Sugar.Types as Sugar
import Lamdu.Prelude
makePickEventMap :: _ => f Menu.PickResult -> m (EventMap (f M.Update))
makePickEventMap action =
Lens.view id <&>
\env ->
let pickKeys = env ^. has . Menu.configKeysPickOption
jumpNextKeys = env ^. has . Menu.configKeysPickOptionAndGotoNext
mkDoc lens =
E.toDoc env [has . MomentuTexts.edit, has . Texts.tag, has . lens]
in
E.keysEventMapMovesCursor pickKeys (mkDoc Texts.new)
(action <&> (^. Menu.pickDest))
-- TODO: DRY with search-menu?
<> E.keyPresses jumpNextKeys
(mkDoc Texts.newAndJumpToNextEntry)
(action <&> \result ->
case result ^. Menu.pickMNextEntry of
Just nextEntry -> GuiState.updateCursor nextEntry
Nothing ->
GuiState.updateCursor (result ^. Menu.pickDest)
& GuiState.uPreferStroll .~ True ^. Lens._Unwrapped
)
makeNewTag ::
(Monad i, Monad o) =>
Sugar.TagOption Name o ->
GuiM env i o (Text -> (EntityId -> r) -> o r)
makeNewTag tagOpt =
GuiM.assocTagName <&>
\assocTagName searchTerm mkPickResult ->
mkPickResult (tagOpt ^. Sugar.toInfo . Sugar.tagInstance) <$
do
Property.setP (assocTagName (tagOpt ^. Sugar.toInfo . Sugar.tagVal)) searchTerm
tagOpt ^. Sugar.toPick
makeNewTagPreEvent ::
_ =>
Sugar.TagOption Name o ->
GuiM env i o (Text -> (EntityId -> r) -> Maybe (Widget.PreEvent (o r)))
makeNewTagPreEvent tagOpt =
(,) <$> Lens.view (has . Texts.newName) <*> makeNewTag tagOpt
<&>
\(newNameText, newTag) searchTerm mkPickResult ->
if Text.null searchTerm
then Nothing
else
Just Widget.PreEvent
{ Widget._pDesc = newNameText
, Widget._pAction = newTag searchTerm mkPickResult
, Widget._pTextRemainder = ""
}
makeAddNewTag ::
_ =>
Sugar.TagOption Name o ->
GuiM menv i o
( (EntityId -> Menu.PickResult) ->
SearchMenu.ResultsContext -> Maybe (Menu.Option f o)
)
makeAddNewTag tagOpt =
makeNewTagPreEvent tagOpt <&>
\newTagPreEvent mkPickResult ctx ->
let optionId =
(ctx ^. SearchMenu.rResultIdPrefix) `Widget.joinId` ["Create new"]
searchTerm = ctx ^. SearchMenu.rSearchTerm
in newTagPreEvent searchTerm mkPickResult
<&> \preEvent ->
Menu.Option
{ Menu._oId = optionId
, Menu._oSubmenuWidgets = Menu.SubmenuEmpty
, Menu._oRender =
(Widget.makeFocusableView ?? optionId <&> fmap)
<*> Styled.label Texts.createNew
<&> (`Menu.RenderedOption` preEvent)
& Styled.withColor TextColors.actionTextColor
}
nameText :: Lens.Traversal' (Sugar.TagOption Name m) Text
nameText = Sugar.toInfo . Sugar.tagName . Name._NameTag . Name.tnDisplayText . Name.ttText
{-# NOINLINE fuzzyMaker #-}
fuzzyMaker :: [(Text, Int)] -> Fuzzy (Set Int)
fuzzyMaker = memo Fuzzy.make
makeOptions ::
_ =>
Sugar.TagChoice Name o ->
Sugar.TagOption Name o ->
(EntityId -> Menu.PickResult) ->
SearchMenu.ResultsContext ->
GuiM env i o (Menu.OptionList (Menu.Option m o))
makeOptions tagRefReplace newTagOpt mkPickResult ctx
| Text.null searchTerm = pure Menu.OptionList { Menu._olIsTruncated = True, Menu._olOptions = [] }
| otherwise =
do
resultCount <-
Lens.view
(Config.hasConfig . Config.completion . Config.completionResultCount)
let nonFuzzyResults =
results ^? Lens.ix 0 . _1 . Fuzzy.isFuzzy
& any not
addNewTag <- makeAddNewTag newTagOpt
let maybeAddNewTagOption
| nonFuzzyResults || not (Name.isValidText searchTerm) = id
| otherwise =
maybe id (:) (addNewTag mkPickResult ctx)
chooseText <- Lens.view (has . MomentuTexts.choose)
let makeOption opt =
Menu.Option
{ Menu._oId = optionWId
, Menu._oRender =
(Widget.makeFocusableView ?? optionWId <&> fmap)
<*> NameView.make (opt ^. Sugar.toInfo . Sugar.tagName)
& local (M.animIdPrefix .~ Widget.toAnimId instanceId)
<&>
\widget ->
Menu.RenderedOption
{ Menu._rWidget = widget
, Menu._rPick = Widget.PreEvent
{ Widget._pDesc = chooseText
, Widget._pAction =
mkPickResult (opt ^. Sugar.toInfo . Sugar.tagInstance)
<$ opt ^. Sugar.toPick
, Widget._pTextRemainder = ""
}
}
, Menu._oSubmenuWidgets = Menu.SubmenuEmpty
}
where
instanceId =
opt ^. Sugar.toInfo . Sugar.tagInstance
& WidgetIds.fromEntityId
optionWId =
ctx ^. SearchMenu.rResultIdPrefix <> instanceId
results <&> snd
& splitAt resultCount
& _2 %~ not . null
& _1 %~ maybeAddNewTagOption . map makeOption
& (\(list, isTrunc) -> Menu.OptionList isTrunc list)
& pure
where
results = Fuzzy.memoableMake fuzzyMaker (tagRefReplace ^. Sugar.tcOptions >>= withText) searchTerm
withText tagOption = tagOption ^.. nameText <&> ((,) ?? tagOption)
searchTerm = ctx ^. SearchMenu.rSearchTerm
allowedSearchTerm :: Text -> Bool
allowedSearchTerm = Name.isValidText
makeHoleSearchTerm ::
_ =>
Sugar.TagOption Name o ->
(EntityId -> Menu.PickResult) -> Widget.Id ->
GuiM env i o (SearchMenu.Term o)
makeHoleSearchTerm newTagOption mkPickResult holeId =
do
searchTerm <- SearchMenu.readSearchTerm holeId
let allowNewTag = Name.isValidText searchTerm
newTag <- makeNewTag newTagOption
newTagEventMap <-
if allowNewTag
then newTag searchTerm mkPickResult & makePickEventMap
else pure mempty
newTagPreEvent <- makeNewTagPreEvent newTagOption
let newTagPreEvents =
newTagPreEvent searchTerm mkPickResult
^.. Lens._Just
<&> fmap (mempty <$)
let addPreEvents =
Widget.wState . Widget._StateFocused . Lens.mapped .
Widget.fPreEvents %~ (newTagPreEvents <>)
term <-
SearchMenu.addDelSearchTerm holeId
<*> SearchMenu.basicSearchTermEdit newTagId holeId (pure . allowedSearchTerm)
SearchMenu.defaultEmptyStrings
<&> SearchMenu.termWidget . M.tValue %~
addPreEvents . Widget.weakerEvents newTagEventMap
tooltip <- Lens.view (has . Theme.tooltip)
if allowNewTag &&
Widget.isFocused (term ^. SearchMenu.termWidget . M.tValue)
then
do
newText <- Lens.view (has . Texts.new)
newTagLabel <-
(TextView.make ?? "(" <> newText <> ")")
<*> (Element.subAnimId ?? ["label"])
space <- Spacer.stdHSpace
hover <- Hover.hover
Glue.Poly (|||) <- Glue.mkPoly ?? Glue.Horizontal
anchor <- Hover.anchor <&> fmap
let hNewTagLabel = hover newTagLabel & Hover.sequenceHover
let termWithHover termW =
let hoverOptions =
[ anchor (termW ||| space) ||| hNewTagLabel
, hNewTagLabel ||| anchor (space ||| termW)
] <&> (^. M.tValue)
in anchor termW
<&> Hover.hoverInPlaceOf hoverOptions
term & SearchMenu.termWidget %~ termWithHover & pure
& local (Hover.backgroundColor .~ tooltip ^. Theme.tooltipBgColor)
& local (TextView.color .~ tooltip ^. Theme.tooltipFgColor)
& local (M.animIdPrefix <>~ ["label"])
else pure term
where
newTagId = newTagOption ^. Sugar.toInfo . Sugar.tagInstance & WidgetIds.fromEntityId & Widget.toAnimId
makeTagHoleEdit ::
_ =>
(EntityId -> Menu.PickResult) ->
Widget.Id ->
Sugar.TagChoice Name o ->
GuiM env i o (M.TextWidget o)
makeTagHoleEdit mkPickResult holeId tagRefReplace =
SearchMenu.make
(const (makeHoleSearchTerm newTagOption mkPickResult holeId))
(makeOptions tagRefReplace newTagOption mkPickResult) M.empty holeId
?? Menu.AnyPlace
where
newTagOption = tagRefReplace ^. Sugar.tcNewTag
makeTagRefEdit :: _ => Sugar.TagRef Name i o -> GuiM env i o (M.TextWidget o)
makeTagRefEdit = makeTagRefEditWith id (const Nothing) Nothing <&> fmap snd
data TagRefEditType
= TagHole
| SimpleView
deriving (Eq)
makeTagRefEditWith ::
_ =>
(n (M.TextWidget o) ->
GuiM env i o (M.TextWidget o)) ->
(Sugar.EntityId -> Maybe Widget.Id) ->
Maybe (o EntityId) ->
Sugar.TagRef Name i o ->
GuiM env i o (TagRefEditType, M.TextWidget o)
makeTagRefEditWith onView onPickNext mSetToAnon tag =
do
isHole <- GuiState.isSubCursor ?? holeId
env <- Lens.view id
let jumpToTagEventMap jump =
jump <&> WidgetIds.fromEntityId
& E.keysEventMapMovesCursor
(env ^. Config.hasConfig . Config.jumpToDefinitionKeys)
(E.toDoc env
[ has . MomentuTexts.edit
, has . Texts.tag
, has . Texts.jumpToTag
])
let chooseNewTagEventMap =
E.keysEventMapMovesCursor
(Config.delKeys env <> env ^. Config.hasConfig . Config.jumpToDefinitionKeys)
( E.toDoc env
[ has . MomentuTexts.edit
, has . Texts.tag
, has . MomentuTexts.choose
] ) chooseAction
let eventMap =
foldMap jumpToTagEventMap (tag ^. Sugar.tagRefJumpTo)
<> chooseNewTagEventMap
nameView <-
(Widget.makeFocusableView ?? viewId <&> fmap) <*>
TagView.make info
<&> Lens.mapped %~ Widget.weakerEvents eventMap
& onView
if isHole
then
tag ^. Sugar.tagRefReplace & GuiM.im
>>= makeTagHoleEdit mkPickResult holeId
<&> (,) TagHole
else pure (SimpleView, nameView)
& GuiState.assignCursor myId viewId
where
info = tag ^. Sugar.tagRefTag
myId = info ^. Sugar.tagInstance & WidgetIds.fromEntityId
holeId = WidgetIds.tagHoleId myId
viewId = Widget.joinId myId ["view"]
mkPickResult tagInstance =
Menu.PickResult
{ Menu._pickDest = WidgetIds.fromEntityId tagInstance
, Menu._pickMNextEntry = onPickNext tagInstance
}
chooseAction =
case mSetToAnon of
Nothing -> pure myId
Just setAnon -> setAnon <&> WidgetIds.fromEntityId
<&> WidgetIds.tagHoleId
makeRecordTag :: _ => Sugar.TagRef Name i o -> GuiM env i o (M.TextWidget o)
makeRecordTag =
makeTagRefEdit <&> Styled.withColor TextColors.recordTagColor
makeVariantTag :: _ => Sugar.TagRef Name i o -> GuiM env i o (M.TextWidget o)
makeVariantTag tag =
makeTagRefEdit tag
& Styled.withColor TextColors.caseTagColor
addParamId :: Widget.Id -> Widget.Id
addParamId = (`Widget.joinId` ["add param"])
makeLHSTag ::
_ =>
(Sugar.EntityId -> Maybe Widget.Id) ->
Lens.ALens' TextColors M.Color ->
Maybe (o EntityId) -> Sugar.TagRef Name i o ->
GuiM env i o (M.TextWidget o)
makeLHSTag onPickNext color mSetToAnon tag =
do
env <- Lens.view id
(tagEditType, tagEdit) <-
makeTagRefEditWith onView onPickNext mSetToAnon tag
& Styled.withColor color
& local (has .~ env ^. has . Style.nameAtBinder)
let chooseEventMap =
E.charEventMap "Letter"
(E.toDoc env
[has . MomentuTexts.edit, has . Texts.tag, has . MomentuTexts.choose])
chooseWithChar
let eventMap =
case tagEditType of
SimpleView -> chooseEventMap
_ -> mempty
tagEdit <&> Widget.weakerEvents eventMap & pure
where
chooseWithChar c =
SearchMenu.enterWithSearchTerm (Text.singleton c)
(WidgetIds.tagHoleId myId)
<$ guard (Char.isAlpha c)
<&> pure
myId = tag ^. Sugar.tagRefTag . Sugar.tagInstance & WidgetIds.fromEntityId
-- Apply the name style only when the tag is a view. If it is
-- a tag hole, the name style (indicating auto-name) makes no sense
onView =
Styled.nameAtBinder (tag ^. Sugar.tagRefTag . Sugar.tagName) .
Styled.withColor color
makeParamTag :: _ => Maybe (o EntityId) -> Sugar.TagRef Name i o -> GuiM env i o (M.TextWidget o)
makeParamTag =
makeLHSTag onPickNext TextColors.parameterColor
where
onPickNext pos = WidgetIds.fromEntityId pos & addParamId & Just
-- | Unfocusable tag view (e.g: in apply args)
makeArgTag :: _ => Name -> Sugar.EntityId -> m (M.WithTextPos M.View)
makeArgTag name tagInstance =
NameView.make name
& Styled.withColor TextColors.argTagColor
& local (M.animIdPrefix .~ animId)
where
animId = WidgetIds.fromEntityId tagInstance & Widget.toAnimId
makeBinderTagEdit ::
_ =>
Lens.ALens' TextColors M.Color -> Sugar.OptionalTag Name i o ->
GuiM env i o (M.TextWidget o)
makeBinderTagEdit color (Sugar.OptionalTag tag setToAnon) =
makeLHSTag (const Nothing) color (Just setToAnon) tag
& local (has . Menu.configKeysPickOptionAndGotoNext .~ [])
|
Peaker/lamdu
|
src/Lamdu/GUI/Expr/TagEdit.hs
|
gpl-3.0
| 16,160
| 0
| 25
| 5,156
| 4,190
| 2,183
| 2,007
| -1
| -1
|
import Tree23
import Data.Maybe
test1 :: Bool
test1 = let tree = Tree23.makeTree([
(6,"six"),
(5,"five"),
(8,"ten"),
(3,"three"),
(1,"one")])
in (Data.Maybe.fromJust (findTree tree 5)) == "five"
|
joelwilliamson/Haskell_Learning
|
Tree23_test.hs
|
gpl-3.0
| 208
| 10
| 12
| 38
| 120
| 67
| 53
| 10
| 1
|
module Main where
main :: IO ()
main = do
putStrLn "cliente"
|
nettok/culebra-hs
|
client/Main.hs
|
gpl-3.0
| 67
| 0
| 7
| 18
| 25
| 13
| 12
| 4
| 1
|
{- ============================================================================
| Copyright 2010 Matthew D. Steele <mdsteele@alum.mit.edu> |
| |
| This file is part of Fallback. |
| |
| Fallback is free software: you can redistribute it and/or modify it under |
| the terms of the GNU General Public License as published by the Free |
| Software Foundation, either version 3 of the License, or (at your option) |
| any later version. |
| |
| Fallback 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 Fallback. If not, see <http://www.gnu.org/licenses/>. |
============================================================================ -}
{-# LANGUAGE ForeignFunctionInterface, GeneralizedNewtypeDeriving #-}
module Fallback.Draw.Base
(-- * Setting up the screen
initializeScreen, setFullscreen,
-- * The Draw monad
Draw, MonadDraw(..), debugDraw,
-- * The Handler monad
Handler, MonadHandler(..), handleScreen,
canvasWidth, canvasHeight, canvasSize, canvasRect,
-- * The Paint monad
Paint, paintScreen,
-- * Reference cells
DrawRef, newDrawRef, readDrawRef, writeDrawRef, modifyDrawRef,
-- * Keyboard/mouse input
getKeyState, getMouseButtonState, getRelativeMousePos, withInputsSuppressed,
-- * Textures
Texture, loadTexture,
-- * Sprites
Sprite, makeSprite, makeSubSprite, Strip, Sheet,
-- ** Creating
takeScreenshot,
-- ** Loading
loadSprite, loadSubSprite, loadVStrip, loadSheet, loadSheetWithTileSize,
-- ** Querying
spriteWidth, spriteHeight, spriteSize, stripLength, (!),
-- ** Blitting
blitTopleft, blitTopleftTinted, blitLoc, blitLocTinted,
blitStretch, blitStretchTinted, blitRepeat, blitRepeatTinted,
blitRotate, blitRotateTinted,
-- * Geometric primitives
tintRect, tintCanvas, drawLine, drawRect,
drawLineChain, drawPolygon, tintPolygon, gradientPolygon,
tintRing, gradientRing, gradientFan,
-- * Fonts and text
Font, loadFont, drawText, {-renderText,-} textRenderSize, textRenderWidth,
-- * Minimaps
Minimap, minimapMapSize, minimapBlitSize,
newMinimap, alterMinimap, blitMinimap, minimapScale)
where
import Control.Applicative ((<$>), (<*), Applicative)
import Control.Arrow ((&&&), (***))
import Control.Monad ((<=<), forM_, when)
import Data.Array ((!), Array, bounds, listArray, range)
import qualified Data.HashTable as HT
import Data.Int (Int32)
import Data.IORef (IORef, modifyIORef, newIORef, readIORef, writeIORef)
import Data.Word (Word8, Word32)
import Foreign (allocaBytes, pokeElemOff, withArray, withForeignPtr)
import Graphics.Rendering.OpenGL (($=))
import qualified Graphics.Rendering.OpenGL as GL
import qualified Graphics.UI.SDL as SDL
import qualified Graphics.UI.SDL.Extras as SDLx
import qualified Graphics.UI.SDL.Image as SDLi
import qualified Graphics.UI.SDL.TTF as SDLt
import System.IO.Unsafe (unsafePerformIO)
import Fallback.Constants (screenHeight, screenRect, screenWidth)
import Fallback.Data.Color (Color(Color), Tint(Tint), whiteTint)
import Fallback.Data.Point
import Fallback.Draw.Texture
import Fallback.Event (Key, getKeyStateIO, getMouseButtonStateIO)
import Fallback.Resource (getResourcePath)
import Fallback.Utility (ceilDiv, flip3)
-------------------------------------------------------------------------------
debugResources :: Bool
debugResources = False
-------------------------------------------------------------------------------
-- Setting up the screen:
initializeScreen :: Bool -> IO ()
initializeScreen fullscreen = do
SDL.glSetAttribute SDL.glDoubleBuffer 1
SDLx.glSetVsyncEnabled True
_ <- SDL.setVideoMode screenWidth screenHeight 32 $ SDL.OpenGL :
(if fullscreen then [SDL.Fullscreen] else [])
-- Turn off the depth buffer:
GL.depthFunc $= Nothing
GL.depthMask $= GL.Disabled
-- Set up blending:
GL.blend $= GL.Enabled
GL.blendEquation $= GL.FuncAdd
GL.blendFunc $= (GL.SrcAlpha, GL.OneMinusSrcAlpha)
-- Turn on antialiasing:
GL.lineSmooth $= GL.Enabled
GL.pointSmooth $= GL.Enabled
GL.polygonSmooth $= GL.Enabled
-- Enable textures:
GL.texture GL.Texture2D $= GL.Enabled
GL.textureFunction $= GL.Modulate
-- Set the view:
GL.clearColor $= GL.Color4 0 0 0 0
GL.viewport $= (GL.Position 0 0, GL.Size (fromIntegral screenWidth)
(fromIntegral screenHeight))
GL.ortho 0 (fromIntegral screenWidth) (fromIntegral screenHeight) 0 (-1) 1
setFullscreen :: Bool -> IO ()
setFullscreen = preservingTextures . initializeScreen
-------------------------------------------------------------------------------
-- Sprites:
data Sprite = Sprite
{ spriteTexture :: !Texture,
spriteTexRect :: !(Rect GL.GLdouble),
spriteWidth :: !Int,
spriteHeight :: !Int }
makeSprite :: Texture -> Sprite
makeSprite texture =
Sprite { spriteTexture = texture, spriteTexRect = Rect 0 0 1 1,
spriteWidth = textureWidth texture,
spriteHeight = textureHeight texture }
makeSubSprite :: IRect -> Texture -> Sprite
makeSubSprite rect texture =
let tw = toGLdouble (textureWidth texture)
th = toGLdouble (textureHeight texture)
Rect sx sy sw sh = toGLdouble <$> rect
in Sprite { spriteTexture = texture,
spriteTexRect = Rect (sx / tw) (sy / th) (sw / tw) (sh / th),
spriteWidth = rectW rect, spriteHeight = rectH rect }
-- | Return the width and height of the 'Sprite', in pixels.
spriteSize :: Sprite -> (Int, Int)
spriteSize = spriteWidth &&& spriteHeight
type Strip = Array Int Sprite
stripLength :: Strip -> Int
stripLength = subtract 1 . snd . bounds
type Sheet = Array (Int, Int) Sprite
-------------------------------------------------------------------------------
-- The Draw monad:
newtype Draw a = Draw { fromDraw :: IO a }
deriving (Applicative, Functor, Monad)
class (Applicative m, Monad m) => MonadDraw m where
runDraw :: Draw a -> m a
instance MonadDraw Draw where runDraw = id
instance MonadDraw IO where runDraw = fromDraw
debugDraw :: (MonadDraw m) => String -> m ()
debugDraw = drawIO . putStrLn
-------------------------------------------------------------------------------
-- The Handler monad:
newtype Handler a = Handler { fromHandler :: IO a }
deriving (Applicative, Functor, Monad, MonadDraw)
class (MonadDraw m) => MonadHandler m where
runHandler :: Handler a -> m a
withSubCanvas :: IRect -> m a -> m a
instance MonadHandler Handler where
runHandler = id
withSubCanvas subRect action = Handler $ do
oldRect <- readIORef canvasRectRef
let newRect = subRect `rectPlus` rectTopleft oldRect
writeIORef canvasRectRef newRect
fromHandler action <* writeIORef canvasRectRef oldRect
handleScreen :: Handler a -> IO a
handleScreen action = withAbsoluteCanvas screenRect (fromHandler action)
canvasWidth :: (MonadHandler m) => m Int
canvasWidth = handlerIO (rectW <$> readIORef canvasRectRef)
canvasHeight :: (MonadHandler m) => m Int
canvasHeight = handlerIO (rectH <$> readIORef canvasRectRef)
canvasSize :: (MonadHandler m) => m (Int, Int)
canvasSize = handlerIO (rectSize <$> readIORef canvasRectRef)
canvasRect :: (MonadHandler m) => m IRect
canvasRect = do
(width, height) <- canvasSize
return $ Rect 0 0 width height
{-# NOINLINE canvasRectRef #-} -- needed for unsafePerformIO
canvasRectRef :: IORef IRect
canvasRectRef = unsafePerformIO (newIORef screenRect)
withAbsoluteCanvas :: IRect -> IO a -> IO a
withAbsoluteCanvas newRect action = do
oldRect <- readIORef canvasRectRef
writeIORef canvasRectRef newRect
action <* writeIORef canvasRectRef oldRect
-------------------------------------------------------------------------------
-- The Paint monad:
newtype Paint a = Paint { fromPaint :: IO a }
deriving (Applicative, Functor, Monad, MonadDraw)
instance MonadHandler Paint where
runHandler = Paint . fromHandler
withSubCanvas = paintWithSubCanvas
paintWithSubCanvas :: IRect -> Paint a -> Paint a
paintWithSubCanvas subRect paint = Paint $ GL.preservingMatrix $ do
let fromScissor (GL.Position x y, GL.Size w h) =
Rect (fromIntegral x) (screenHeight - fromIntegral y - fromIntegral h)
(fromIntegral w) (fromIntegral h)
let toScissor (Rect x y w h) =
(GL.Position (toGLint x) (toGLint (screenHeight - y - h)),
GL.Size (toGLsizei w) (toGLsizei h))
-- Change the canvas rect:
oldRect <- readIORef canvasRectRef
let newRect = subRect `rectPlus` rectTopleft oldRect
writeIORef canvasRectRef newRect
-- Change the GL coordinates and scissor:
GL.translate $ GL.Vector3 (toGLdouble $ rectX subRect)
(toGLdouble $ rectY subRect) 0
oldScissor <- GL.get GL.scissor
let oldScissorRect = maybe screenRect fromScissor oldScissor
let newScissorRect = oldScissorRect `rectIntersection` newRect
GL.scissor $= Just (toScissor newScissorRect)
-- Perform the inner paint:
result <- fromPaint paint
-- Reset to previous state before returning:
GL.scissor $= oldScissor
writeIORef canvasRectRef oldRect
return result
paintScreen :: Paint () -> IO ()
paintScreen paint = do
GL.clear [GL.ColorBuffer]
withAbsoluteCanvas screenRect (fromPaint paint)
GL.flush -- Are the flush and finish at all necessary? I'm not sure.
GL.finish
SDL.glSwapBuffers
-------------------------------------------------------------------------------
-- Reference cells:
newtype DrawRef a = DrawRef (IORef a)
newDrawRef :: (MonadDraw m) => a -> m (DrawRef a)
newDrawRef = drawIO . fmap DrawRef . newIORef
readDrawRef :: (MonadDraw m) => DrawRef a -> m a
readDrawRef (DrawRef ref) = drawIO (readIORef ref)
writeDrawRef :: (MonadDraw m) => DrawRef a -> a -> m ()
writeDrawRef (DrawRef ref) value = drawIO (writeIORef ref value)
modifyDrawRef :: (MonadDraw m) => DrawRef a -> (a -> a) -> m ()
modifyDrawRef (DrawRef ref) fn = drawIO (modifyIORef ref fn)
-------------------------------------------------------------------------------
-- Keyboard/mouse input:
getKeyState :: (MonadHandler m) => Key -> m Bool
getKeyState key = handlerIO $ do
suppressed <- readIORef inputsSuppressed
if suppressed then return False else getKeyStateIO key
getMouseButtonState :: (MonadHandler m) => m Bool
getMouseButtonState = handlerIO $ do
suppressed <- readIORef inputsSuppressed
if suppressed then return False else getMouseButtonStateIO
getRelativeMousePos :: (MonadHandler m) => m (Maybe IPoint)
getRelativeMousePos = handlerIO $ do
suppressed <- readIORef inputsSuppressed
if suppressed then return Nothing else do
(absoluteMouseX, absoluteMouseY, _) <- SDL.getMouseState
rect <- readIORef canvasRectRef
return $ Just $ Point (absoluteMouseX - rectX rect)
(absoluteMouseY - rectY rect)
withInputsSuppressed :: (MonadHandler m) => m a -> m a
withInputsSuppressed action = do
suppressed <- handlerIO (readIORef inputsSuppressed <*
writeIORef inputsSuppressed True)
action <* handlerIO (writeIORef inputsSuppressed suppressed)
{-# NOINLINE inputsSuppressed #-} -- needed for unsafePerformIO
inputsSuppressed :: IORef Bool
inputsSuppressed = unsafePerformIO (newIORef False)
-------------------------------------------------------------------------------
-- Creating new sprites:
-- | Make a copy of the current state of a region of the screen.
takeScreenshot :: IRect -> IO Sprite
takeScreenshot (Rect left top width height) =
allocaBytes (width * height * 4) $ \pixelsPtr -> do
let pixelData = GL.PixelData GL.RGB GL.UnsignedByte pixelsPtr
GL.pixelZoom $= (1, 1)
GL.readPixels (GL.Position (toGLint left) (toGLint (top + height)))
(GL.Size (fromIntegral width) (fromIntegral height))
pixelData
fmap makeSprite $ newTexture width height $ do
GL.texImage2D Nothing GL.NoProxy 0 GL.RGB'
(GL.TextureSize2D (fromIntegral width) (fromIntegral height))
0 pixelData
-------------------------------------------------------------------------------
-- Blitting sprites:
blitTopleft :: (Axis a) => Sprite -> Point a -> Paint ()
blitTopleft = blitTopleftTinted whiteTint
blitTopleftTinted :: (Axis a) => Tint -> Sprite -> Point a -> Paint ()
blitTopleftTinted tint sprite (Point x y) =
blitStretchTinted tint sprite $
(Rect x y (fromIntegral $ spriteWidth sprite)
(fromIntegral $ spriteHeight sprite))
blitLoc :: (Axis a) => Sprite -> LocSpec a -> Paint ()
blitLoc = blitLocTinted whiteTint
blitLocTinted :: (Axis a) => Tint -> Sprite -> LocSpec a -> Paint ()
blitLocTinted tint sprite loc =
blitTopleftTinted tint sprite $ locTopleft loc $
(fromIntegral *** fromIntegral) $ spriteSize sprite
blitStretch :: (Axis a) => Sprite -> Rect a -> Paint ()
blitStretch = blitStretchTinted whiteTint
blitStretchTinted :: (Axis a) => Tint -> Sprite -> Rect a -> Paint ()
blitStretchTinted tint sprite rect = Paint $ do
withTexture (spriteTexture sprite) $ do
setTint tint
GL.renderPrimitive GL.Quads $ do
let Rect tx ty tw th = spriteTexRect sprite
let Rect rx ry rw rh = toGLdouble <$> rect
GL.texCoord $ GL.TexCoord2 tx ty
glVertex rx ry
GL.texCoord $ GL.TexCoord2 (tx + tw) ty
glVertex (rx + rw) ry
GL.texCoord $ GL.TexCoord2 (tx + tw) (ty + th)
glVertex (rx + rw) (ry + rh)
GL.texCoord $ GL.TexCoord2 tx (ty + th)
glVertex rx (ry + rh)
blitRotate :: (Axis a) => Sprite {-^sprite-} -> Point a {-^center-}
-> Double {-^ angle (in radians) -} -> Paint ()
blitRotate = blitRotateTinted whiteTint
blitRotateTinted :: (Axis a) => Tint {-^tint-} -> Sprite {-^sprite-}
-> Point a {-^center-} -> Double {-^ angle (in radians) -}
-> Paint ()
blitRotateTinted tint sprite (Point cx cy) radians = Paint $ do
withTexture (spriteTexture sprite) $ do
setTint tint
GL.preservingMatrix $ do
GL.translate $ GL.Vector3 (toGLdouble cx) (toGLdouble cy) 0
GL.rotate (toGLdouble (radians * (180 / pi)))
(GL.Vector3 0 0 (1 :: GL.GLdouble))
GL.renderPrimitive GL.Quads $ do
let Rect tx ty tw th = spriteTexRect sprite
let sw = toGLdouble (spriteWidth sprite) / 2
sh = toGLdouble (spriteHeight sprite) / 2
GL.texCoord $ GL.TexCoord2 tx ty
glVertex (negate sw) (negate sh)
GL.texCoord $ GL.TexCoord2 (tx + tw) ty
glVertex sw (negate sh)
GL.texCoord $ GL.TexCoord2 (tx + tw) (ty + th)
glVertex sw sh
GL.texCoord $ GL.TexCoord2 tx (ty + th)
glVertex (negate sw) sh
blitRepeat :: Sprite -> IPoint -> IRect -> Paint ()
blitRepeat = blitRepeatTinted whiteTint
blitRepeatTinted :: Tint -> Sprite -> IPoint -> IRect -> Paint ()
blitRepeatTinted tint sprite (Point ox oy) rect = withSubCanvas rect $ do
let width = spriteWidth sprite
height = spriteHeight sprite
let startCol = negate (ox `ceilDiv` width)
startRow = negate (oy `ceilDiv` height)
let endCol = (rectW rect - ox) `div` width
endRow = (rectH rect - oy) `div` height
forM_ [startRow .. endRow] $ \row -> do
forM_ [startCol .. endCol] $ \col -> do
blitTopleftTinted tint sprite $
Point (ox + col * width) (oy + row * height)
-------------------------------------------------------------------------------
-- Geometric primitives:
-- | Draw an antialiased line onto the canvas.
drawLine :: (Axis a) => Tint {-^color-} -> Point a {-^start-}
-> Point a {-^end-} -> Paint ()
drawLine tint start end = Paint $ do
drawPrimitive GL.Lines tint $ pointVertex' start >> pointVertex' end
drawRect :: (Axis a) => Tint -> Rect a -> Paint ()
drawRect tint (Rect x y w h) = Paint $ do
drawPrimitive GL.LineLoop tint $ do
axisVertex' x y
axisVertex' (x + w - 1) y
axisVertex' (x + w - 1) (y + h - 1)
axisVertex' x (y + h - 1)
-- | Tint a subrectangle of the canvas uniformly.
tintRect :: (Axis a) => Tint -> Rect a -> Paint ()
tintRect tint (Rect x y w h) = Paint $ do
drawPrimitive GL.Quads tint $ do
axisVertex x y
axisVertex (x + w) y
axisVertex (x + w) (y + h)
axisVertex x (y + h)
-- | Tint the whole canvas uniformly.
tintCanvas :: Tint -> Paint ()
tintCanvas tint = canvasRect >>= tintRect tint
-- -- | Draw an antialiased circle onto the canvas.
-- drawCircle :: (Axis a) => Tint {-^color-} -> Point a {-^center-}
-- -> a {-^radius-} -> Paint ()
-- drawCircle tint (Point cx cy) radius = Draw $ do
-- GL.preservingMatrix $ do
-- GL.translate $ GL.Vector3 (toGLdouble cx) (toGLdouble cy) 0
-- let rad = toGLdouble radius
-- thetaStep = 2 / rad
-- drawPrimitive GL.LineLoop tint $ do
-- untilM 0 (>= 2 * pi) (+thetaStep) $ \theta -> do
-- GL.vertex $ GL.Vertex3 (rad * cos theta) (rad * sin theta) 0
-- -- | Draw an antialiased oval onto the canvas.
-- drawOval :: (Axis a) => Tint -> Rect a -> Paint ()
-- drawOval = strokeOval GL.LineLoop
-- tintOval :: (Axis a) => Tint -> Rect a -> Paint ()
-- tintOval = strokeOval GL.Polygon
-- strokeOval :: (Axis a) => GL.PrimitiveMode -> Tint -> Rect a -> Paint ()
-- strokeOval mode tint (Rect x y w h) = Draw $ when (w > 0 && h > 0) $ do
-- let hRad = toGLdouble w / 2
-- vRad = toGLdouble h / 2
-- let cx = toGLdouble x + hRad
-- cy = toGLdouble y + vRad
-- GL.preservingMatrix $ do
-- GL.translate $ GL.Vector3 cx cy 0
-- let thetaStep = 2 / max hRad vRad
-- drawPrimitive mode tint $ do
-- untilM 0 (>= 2 * pi) (+thetaStep) $ \theta -> do
-- GL.vertex $ GL.Vertex3 (hRad * cos theta) (vRad * sin theta) 0
-- drawTriangle :: Tint {-^color-} -> Point {-^vertex 1-}
-- -> Point {-^vertex 2-} -> Point {-^vertex 3-} -> Paint ()
-- drawTriangle tint point1 point2 point3 =
-- drawPolygon tint [point1, point2, point3]
-- drawFilledTriangle :: Tint {-^color-} -> Point {-^vertex 1-}
-- -> Point {-^vertex 2-} -> Point {-^vertex 3-} -> Paint ()
-- drawFilledTriangle tint point1 point2 point3 = Draw $ do
-- drawPrimitive GL.Triangles tint $ do
-- pointVertex' point1
-- pointVertex' point2
-- pointVertex' point3
drawLineChain :: (Axis a) => Tint -> [Point a] -> Paint ()
drawLineChain tint points = Paint $ do
drawPrimitive GL.LineStrip tint $ mapM_ pointVertex' points
drawPolygon :: (Axis a) => Tint -> [Point a] -> Paint ()
drawPolygon tint points = Paint $ do
drawPrimitive GL.LineLoop tint $ mapM_ pointVertex' points
tintPolygon :: (Axis a) => Tint -> [Point a] -> Paint ()
tintPolygon tint points = Paint $ do
drawPrimitive GL.Polygon tint $ mapM_ pointVertex' points
gradientPolygon :: (Axis a) => [(Tint, Point a)] -> Paint ()
gradientPolygon pointTints = Paint $ do
GL.textureBinding GL.Texture2D $= Nothing
let doVertex (tint, point) = setTint tint >> pointVertex point
GL.renderPrimitive GL.Polygon $ mapM_ doVertex pointTints
tintRing :: (Axis a) => Tint -> a -> Point a -> a -> a -> Paint ()
tintRing tint thickness (Point cx cy) hRad vRad = Paint $ do
GL.preservingMatrix $ do
GL.translate $ GL.Vector3 (toGLdouble cx) (toGLdouble cy) 0
drawPrimitive GL.TriangleStrip tint $ do
let { hr = toGLdouble hRad; vr = toGLdouble vRad }
let st = toGLdouble thickness / 2
let { ihr = hr - st; ivr = vr - st; ohr = hr + st; ovr = vr + st }
let step = toGLdouble (pi / 24 :: Double) -- TODO
forM_ [0, (2 * step) .. 2 * (pi - step)] $ \theta -> do
let theta' = theta + step
GL.vertex $ GL.Vertex3 (ihr * cos theta) (ivr * sin theta) 0
GL.vertex $ GL.Vertex3 (ohr * cos theta') (ovr * sin theta') 0
GL.vertex $ GL.Vertex3 (ihr * cos 0) (ivr * sin 0) 0
GL.vertex $ GL.Vertex3 (ohr * cos step) (ovr * sin step) 0
gradientRing :: (Double -> (Double, Tint)) -> (Double -> (Double, Tint))
-> DPoint {-^center-} -> Double -> Double -> Paint ()
gradientRing innerFn outerFn (Point cx cy) hRad vRad = Paint $ do
GL.preservingMatrix $ do
GL.translate $ GL.Vector3 (toGLdouble cx) (toGLdouble cy) 0
GL.textureBinding GL.Texture2D $= Nothing
GL.renderPrimitive GL.TriangleStrip $ do
let step = pi / 24 :: Double -- TODO
let doPt fn theta = do
let (rad, tint) = fn theta
setTint tint
axisVertex (rad * hRad * cos theta) (rad * vRad * sin theta)
forM_ [0, (2 * step) .. 2 * (pi - step)] $ \theta -> do
doPt innerFn theta
doPt outerFn (theta + step)
doPt innerFn 0
doPt outerFn step
gradientFan :: DPoint -> Tint -> (Double -> (Double, Tint)) -> Paint ()
gradientFan (Point cx cy) centerTint fn = Paint $ do
GL.preservingMatrix $ do
GL.translate $ GL.Vector3 (toGLdouble cx) (toGLdouble cy) 0
GL.textureBinding GL.Texture2D $= Nothing
GL.renderPrimitive GL.TriangleFan $ do
setTint centerTint
glVertex 0 0
let step = pi / 24 :: Double -- TODO
let doPt theta = do
let (rad, tint) = fn theta
setTint tint
axisVertex (rad * cos theta) (rad * sin theta)
mapM_ doPt [0, step .. 2 * pi - step]
doPt 0
-------------------------------------------------------------------------------
-- Fonts and text:
newtype Font = Font SDLt.Font
deriving (Eq)
-- | Draw text with the given font and color onto the screen at the specified
-- location.
drawText :: (Axis a) => Font -> Color -> LocSpec a -> String -> Paint ()
drawText font color spec string = Paint $ do
surface <- renderText' font color string
blitSurface 1 surface spec
-- | Create a new SDL surface containing text with the given font and color.
renderText' :: Font -> Color -> String -> IO SDL.Surface
renderText' (Font font) color string =
if null string then SDL.createRGBSurfaceEndian [SDL.SWSurface] 0 0 32
else SDLt.renderTextBlended font string (toSDLColor color)
-- | Determine the width and height that a given string would have when
-- rendered in the given font.
textRenderSize :: Font -> String -> (Int, Int)
textRenderSize (Font font) str =
-- Note: SDLt.textSize has no side effects, but is in the IO monad because
-- SDL font objects are mutable. However, our abstraction in this module
-- prevents mutation of font objects, so in fact this function is
-- referentially transparent. Thus, the use of unsafePerformIO is justified.
unsafePerformIO $ SDLt.textSize font str
-- | Determine the width that a given string would have when rendered in the
-- given font.
textRenderWidth :: Font -> String -> Int
textRenderWidth = (fst .) . textRenderSize
-------------------------------------------------------------------------------
-- Minimaps:
-- | A 'Minimap' is a mutable image intended for drawing terrain minimaps.
newtype Minimap = Minimap Texture
-- | Return the original dimensions passed to 'newMinimap'.
minimapMapSize :: Minimap -> (Int, Int)
minimapMapSize (Minimap texture) =
(textureWidth texture, textureHeight texture)
-- | Return the size of the image that will be drawn by 'blitMinimap'.
minimapBlitSize :: Minimap -> (Int, Int)
minimapBlitSize (Minimap texture) =
(textureWidth texture * minimapScale, textureHeight texture * minimapScale)
-- | Create a new minimap for a map with the given dimensions, initially all
-- black.
newMinimap :: (Int, Int) -> IO Minimap
newMinimap (width, height) = do
texture <- newTexture width height $ do
withArray (replicate (width * height) (0 :: Word32)) $ \pixelsPtr -> do
GL.texImage2D Nothing GL.NoProxy 0 GL.RGB'
(GL.TextureSize2D (toGLsizei width) (toGLsizei height)) 0
(GL.PixelData GL.RGB GL.UnsignedByte pixelsPtr)
return (Minimap texture)
-- | Mutate the color of some of the map locations on the minimap.
alterMinimap :: Minimap -> [(IPoint, Color)] -> IO ()
alterMinimap (Minimap texture) pixels = withTexture texture $ do
allocaBytes 4 $ \pixelPtr -> do
pokeElemOff pixelPtr 3 255
forM_ pixels $ \(Point x y, Color r g b) -> do
pokeElemOff pixelPtr 0 r
pokeElemOff pixelPtr 1 g
pokeElemOff pixelPtr 2 b
GL.texSubImage2D Nothing 0 (GL.TexturePosition2D (toGLint x) (toGLint y))
(GL.TextureSize2D 1 1) (GL.PixelData GL.RGBA GL.UnsignedByte pixelPtr)
-- | Draw the minimap to the screen.
blitMinimap :: (Axis a) => Minimap -> LocSpec a -> Paint ()
blitMinimap mm@(Minimap texture) loc = Paint $ withTexture texture $ do
setTint whiteTint
GL.renderPrimitive GL.Quads $ do
let (w, h) = minimapBlitSize mm
let Rect rx ry rw rh = toGLdouble <$> locRect loc (fromIntegral w,
fromIntegral h)
GL.texCoord $ GL.TexCoord2 0 (0 :: GL.GLdouble)
glVertex rx ry
GL.texCoord $ GL.TexCoord2 1 (0 :: GL.GLdouble)
glVertex (rx + rw) ry
GL.texCoord $ GL.TexCoord2 1 (1 :: GL.GLdouble)
glVertex (rx + rw) (ry + rh)
GL.texCoord $ GL.TexCoord2 0 (1 :: GL.GLdouble)
glVertex rx (ry + rh)
-- | The width/height of each minimap tile, in pixels.
minimapScale :: Int
minimapScale = 2
-------------------------------------------------------------------------------
-- Loading resources:
-- | Load a font of a particular size.
loadFont :: String -> Int -> IO Font
loadFont name size = do
when debugResources $ do
putStrLn ("loading font " ++ name ++ " " ++ show size)
path <- getResourcePath "fonts" name
fmap Font $ SDLt.openFont path size
loadSprite :: (MonadDraw m) => String -> m Sprite
loadSprite name = drawIO (makeSprite <$> loadTexture name)
loadSubSprite :: (MonadDraw m) => String -> IRect -> m Sprite
loadSubSprite name rect = drawIO (makeSubSprite rect <$> loadTexture name)
loadVStrip :: (MonadDraw m) => String -> Int -> m Strip
loadVStrip name size = drawIO $ do
texture <- loadTexture name
let (height, extra) = textureHeight texture `divMod` size
when (extra /= 0) $ fail ("bad vstrip size " ++ show size ++ " for " ++ name)
let width = textureWidth texture
let slice n = makeSubSprite (Rect 0 (n * height) width height) texture
return $ listArray (0, size - 1) $ map slice [0 .. size - 1]
loadSheet :: (MonadDraw m) => FilePath -> (Int, Int) -> m Sheet
loadSheet name (rows, cols) = drawIO $ do
texture <- loadTexture name
let (height, extraH) = textureHeight texture `divMod` rows
let (width, extraW) = textureWidth texture `divMod` cols
when (extraH /= 0 || extraW /= 0) $ do
fail ("bad sheet size " ++ show (rows, cols) ++ " for " ++ name)
return $ makeSheet texture width height cols rows
loadSheetWithTileSize :: (Int, Int) -> FilePath -> IO Sheet
loadSheetWithTileSize (width, height) name = do
texture <- loadTexture name
let (rows, extraH) = textureHeight texture `divMod` height
let (cols, extraW) = textureWidth texture `divMod` width
when (extraH /= 0 || extraW /= 0) $ do
fail ("bad tile size " ++ show (width, height) ++ " for " ++ name)
return $ makeSheet texture width height cols rows
makeSheet :: Texture -> Int -> Int -> Int -> Int -> Sheet
makeSheet texture w h cols rows = listArray bound $ map slice (range bound)
where slice (row, col) = makeSubSprite (Rect (col * w) (row * h) w h) texture
bound = ((0, 0), (rows - 1, cols - 1))
-- | Load an image from disk as a 'Texture' object.
loadTexture :: String -> IO Texture
loadTexture = ioEverCached HT.hashString $ \name -> do
when debugResources $ do
putStrLn ("loading texture " ++ name)
(newTextureFromSurface <=< loadSurface) name
-- | Load an image from disk as an SDL surface.
loadSurface :: String -> IO SDL.Surface
loadSurface name = do -- = ioWeakCached HT.hashString $ \name -> do
when debugResources $ do
putStrLn ("loading surface " ++ name)
surface <- getResourcePath "images" name >>= SDLi.load
_ <- SDL.setAlpha surface [] 255 -- Turn off the SDL.SrcAlpha flag, if set.
return surface
-- | Wrap an 'IO' function with a strong-value hash table cache.
{-# NOINLINE ioEverCached #-} -- needed for unsafePerformIO
ioEverCached :: (Eq a) => (a -> Int32) -> (a -> IO b) -> (a -> IO b)
ioEverCached hash fn = unsafePerformIO $ do
table <- HT.new (==) hash
return $ \key -> do
mbValue <- HT.lookup table key
flip3 maybe return mbValue $ do
value <- fn key
HT.insert table key value
return value
-------------------------------------------------------------------------------
-- Private utility functions:
-- | Blit an SDL surface to the screen.
blitSurface :: (Axis a) => Int -> SDL.Surface -> LocSpec a -> IO ()
blitSurface zoom surface spec = do
(format, _) <- surfaceFormats surface
let width = SDL.surfaceGetWidth surface
height = SDL.surfaceGetHeight surface
let (Point x y) = locTopleft spec (fromIntegral (zoom * width),
fromIntegral (zoom * height))
-- We draw "upside-down" relative to how GL normally draws things (i.e. we
-- have y increasing downwards rather than upwards), so we negate the
-- vertical zoom, so that when we use GL.drawPixels, the raster position will
-- correspond to the top-left of the pixel array rather than the bottom left.
GL.pixelZoom $= let z = fromIntegral zoom in (z, negate z)
GL.rasterPos (GL.Vertex3 (toGLdouble x) (toGLdouble y) 0)
GL.textureBinding GL.Texture2D $= Nothing
pixelsPtr <- SDL.surfaceGetPixels surface
GL.drawPixels (GL.Size (fromIntegral width) (fromIntegral height))
(GL.PixelData format GL.UnsignedByte pixelsPtr)
-- | Turn an SDL surface into a 'Texture'.
newTextureFromSurface :: SDL.Surface -> IO Texture
newTextureFromSurface surface = do
(format, format') <- surfaceFormats surface
let width = SDL.surfaceGetWidth surface
height = SDL.surfaceGetHeight surface
newTexture width height $ do
withForeignPtr surface $ const $ do
pixelsPtr <- SDL.surfaceGetPixels surface
GL.texImage2D Nothing GL.NoProxy 0 format'
(GL.TextureSize2D (toGLsizei width) (toGLsizei height))
0 (GL.PixelData format GL.UnsignedByte pixelsPtr)
-- | Determine the appropriate OpenGL pixel formats to use when interpreting
-- the raw pixel data of the given SDL surface.
surfaceFormats :: SDL.Surface -> IO (GL.PixelFormat, GL.PixelInternalFormat)
surfaceFormats surface = do
let pixelFormat = SDL.surfaceGetPixelFormat surface
bmask <- SDLx.pixelFormatGetBmask pixelFormat
let bgr = bmask == ntohl 0xff000000 -- Are we in BGR order or RGB order?
numColors <- SDL.pixelFormatGetBytesPerPixel pixelFormat
case numColors of
4 -> return (if bgr then GL.BGRA else GL.RGBA, GL.RGBA')
3 -> return (if bgr then GL.BGR else GL.RGB, GL.RGB')
_ -> fail ("numColors = " ++ show numColors)
-- | Convert a big-endian word to native endianness.
foreign import ccall unsafe "netinet/in.h" ntohl :: Word32 -> Word32
setTint :: Tint -> IO ()
setTint (Tint r g b a) =
GL.color $ GL.Color4 (fromWord r) (fromWord g) (fromWord b) (fromWord a)
fromWord :: Word8 -> GL.GLdouble
fromWord = (* recip 255) . fromIntegral
glVertex :: GL.GLdouble -> GL.GLdouble -> IO ()
glVertex x y = GL.vertex $ GL.Vertex3 x y 0
axisVertex :: (Axis a) => a -> a -> IO ()
axisVertex x y = GL.vertex $ GL.Vertex3 (toGLdouble x) (toGLdouble y) 0
axisVertex' :: (Axis a) => a -> a -> IO ()
axisVertex' x y =
GL.vertex $ GL.Vertex3 (toGLdouble x + 0.5) (toGLdouble y + 0.5) 0
pointVertex :: (Axis a) => Point a -> IO ()
pointVertex (Point x y) = axisVertex x y
pointVertex' :: (Axis a) => Point a -> IO ()
pointVertex' (Point x y) = axisVertex' x y
toSDLColor :: Color -> SDL.Color
toSDLColor (Color r g b) = SDL.Color r g b
drawPrimitive :: GL.PrimitiveMode -> Tint -> IO () -> IO ()
drawPrimitive mode tint action = do
GL.textureBinding GL.Texture2D $= Nothing
setTint tint
GL.renderPrimitive mode action
toGLdouble :: (Axis a) => a -> GL.GLdouble
toGLdouble = toFloating
toGLint :: Int -> GL.GLint
toGLint = fromIntegral
toGLsizei :: Int -> GL.GLsizei
toGLsizei = fromIntegral
drawIO :: (MonadDraw m) => IO a -> m a
drawIO = runDraw . Draw
handlerIO :: (MonadHandler m) => IO a -> m a
handlerIO = runHandler . Handler
-------------------------------------------------------------------------------
|
mdsteele/fallback
|
src/Fallback/Draw/Base.hs
|
gpl-3.0
| 32,901
| 0
| 23
| 7,199
| 9,604
| 4,892
| 4,712
| -1
| -1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.RegionInstanceGroupManagers.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes the specified managed instance group and all of the instances in
-- that group.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.regionInstanceGroupManagers.delete@.
module Network.Google.Resource.Compute.RegionInstanceGroupManagers.Delete
(
-- * REST Resource
RegionInstanceGroupManagersDeleteResource
-- * Creating a Request
, regionInstanceGroupManagersDelete
, RegionInstanceGroupManagersDelete
-- * Request Lenses
, rigmdProject
, rigmdInstanceGroupManager
, rigmdRegion
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.regionInstanceGroupManagers.delete@ method which the
-- 'RegionInstanceGroupManagersDelete' request conforms to.
type RegionInstanceGroupManagersDeleteResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"regions" :>
Capture "region" Text :>
"instanceGroupManagers" :>
Capture "instanceGroupManager" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] Operation
-- | Deletes the specified managed instance group and all of the instances in
-- that group.
--
-- /See:/ 'regionInstanceGroupManagersDelete' smart constructor.
data RegionInstanceGroupManagersDelete = RegionInstanceGroupManagersDelete'
{ _rigmdProject :: !Text
, _rigmdInstanceGroupManager :: !Text
, _rigmdRegion :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'RegionInstanceGroupManagersDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rigmdProject'
--
-- * 'rigmdInstanceGroupManager'
--
-- * 'rigmdRegion'
regionInstanceGroupManagersDelete
:: Text -- ^ 'rigmdProject'
-> Text -- ^ 'rigmdInstanceGroupManager'
-> Text -- ^ 'rigmdRegion'
-> RegionInstanceGroupManagersDelete
regionInstanceGroupManagersDelete pRigmdProject_ pRigmdInstanceGroupManager_ pRigmdRegion_ =
RegionInstanceGroupManagersDelete'
{ _rigmdProject = pRigmdProject_
, _rigmdInstanceGroupManager = pRigmdInstanceGroupManager_
, _rigmdRegion = pRigmdRegion_
}
-- | Project ID for this request.
rigmdProject :: Lens' RegionInstanceGroupManagersDelete Text
rigmdProject
= lens _rigmdProject (\ s a -> s{_rigmdProject = a})
-- | Name of the managed instance group to delete.
rigmdInstanceGroupManager :: Lens' RegionInstanceGroupManagersDelete Text
rigmdInstanceGroupManager
= lens _rigmdInstanceGroupManager
(\ s a -> s{_rigmdInstanceGroupManager = a})
-- | Name of the region scoping this request.
rigmdRegion :: Lens' RegionInstanceGroupManagersDelete Text
rigmdRegion
= lens _rigmdRegion (\ s a -> s{_rigmdRegion = a})
instance GoogleRequest
RegionInstanceGroupManagersDelete where
type Rs RegionInstanceGroupManagersDelete = Operation
type Scopes RegionInstanceGroupManagersDelete =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient RegionInstanceGroupManagersDelete'{..}
= go _rigmdProject _rigmdRegion
_rigmdInstanceGroupManager
(Just AltJSON)
computeService
where go
= buildClient
(Proxy ::
Proxy RegionInstanceGroupManagersDeleteResource)
mempty
|
rueshyna/gogol
|
gogol-compute/gen/Network/Google/Resource/Compute/RegionInstanceGroupManagers/Delete.hs
|
mpl-2.0
| 4,431
| 0
| 16
| 970
| 465
| 278
| 187
| 79
| 1
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.AdExchangeSeller.Types.Sum
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.AdExchangeSeller.Types.Sum where
import Network.Google.Prelude
|
rueshyna/gogol
|
gogol-adexchange-seller/gen/Network/Google/AdExchangeSeller/Types/Sum.hs
|
mpl-2.0
| 616
| 0
| 4
| 109
| 29
| 25
| 4
| 8
| 0
|
{-# 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.Plus.People.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Get a person\'s profile. If your app uses scope
-- https:\/\/www.googleapis.com\/auth\/plus.login, this method is
-- guaranteed to return ageRange and language.
--
-- /See:/ <https://developers.google.com/+/api/ Google+ API Reference> for @plus.people.get@.
module Network.Google.Resource.Plus.People.Get
(
-- * REST Resource
PeopleGetResource
-- * Creating a Request
, peopleGet
, PeopleGet
-- * Request Lenses
, pgUserId
) where
import Network.Google.Plus.Types
import Network.Google.Prelude
-- | A resource alias for @plus.people.get@ method which the
-- 'PeopleGet' request conforms to.
type PeopleGetResource =
"plus" :>
"v1" :>
"people" :>
Capture "userId" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Person
-- | Get a person\'s profile. If your app uses scope
-- https:\/\/www.googleapis.com\/auth\/plus.login, this method is
-- guaranteed to return ageRange and language.
--
-- /See:/ 'peopleGet' smart constructor.
newtype PeopleGet =
PeopleGet'
{ _pgUserId :: Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PeopleGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pgUserId'
peopleGet
:: Text -- ^ 'pgUserId'
-> PeopleGet
peopleGet pPgUserId_ = PeopleGet' {_pgUserId = pPgUserId_}
-- | The ID of the person to get the profile for. The special value \"me\"
-- can be used to indicate the authenticated user.
pgUserId :: Lens' PeopleGet Text
pgUserId = lens _pgUserId (\ s a -> s{_pgUserId = a})
instance GoogleRequest PeopleGet where
type Rs PeopleGet = Person
type Scopes PeopleGet =
'["https://www.googleapis.com/auth/plus.login",
"https://www.googleapis.com/auth/plus.me",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile"]
requestClient PeopleGet'{..}
= go _pgUserId (Just AltJSON) plusService
where go
= buildClient (Proxy :: Proxy PeopleGetResource)
mempty
|
brendanhay/gogol
|
gogol-plus/gen/Network/Google/Resource/Plus/People/Get.hs
|
mpl-2.0
| 2,963
| 0
| 12
| 659
| 313
| 195
| 118
| 48
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DFAReporting.RemarketingLists.Update
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates an existing remarketing list.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ Campaign Manager 360 API Reference> for @dfareporting.remarketingLists.update@.
module Network.Google.Resource.DFAReporting.RemarketingLists.Update
(
-- * REST Resource
RemarketingListsUpdateResource
-- * Creating a Request
, remarketingListsUpdate
, RemarketingListsUpdate
-- * Request Lenses
, rluXgafv
, rluUploadProtocol
, rluAccessToken
, rluUploadType
, rluProFileId
, rluPayload
, rluCallback
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.remarketingLists.update@ method which the
-- 'RemarketingListsUpdate' request conforms to.
type RemarketingListsUpdateResource =
"dfareporting" :>
"v3.5" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"remarketingLists" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] RemarketingList :>
Put '[JSON] RemarketingList
-- | Updates an existing remarketing list.
--
-- /See:/ 'remarketingListsUpdate' smart constructor.
data RemarketingListsUpdate =
RemarketingListsUpdate'
{ _rluXgafv :: !(Maybe Xgafv)
, _rluUploadProtocol :: !(Maybe Text)
, _rluAccessToken :: !(Maybe Text)
, _rluUploadType :: !(Maybe Text)
, _rluProFileId :: !(Textual Int64)
, _rluPayload :: !RemarketingList
, _rluCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RemarketingListsUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rluXgafv'
--
-- * 'rluUploadProtocol'
--
-- * 'rluAccessToken'
--
-- * 'rluUploadType'
--
-- * 'rluProFileId'
--
-- * 'rluPayload'
--
-- * 'rluCallback'
remarketingListsUpdate
:: Int64 -- ^ 'rluProFileId'
-> RemarketingList -- ^ 'rluPayload'
-> RemarketingListsUpdate
remarketingListsUpdate pRluProFileId_ pRluPayload_ =
RemarketingListsUpdate'
{ _rluXgafv = Nothing
, _rluUploadProtocol = Nothing
, _rluAccessToken = Nothing
, _rluUploadType = Nothing
, _rluProFileId = _Coerce # pRluProFileId_
, _rluPayload = pRluPayload_
, _rluCallback = Nothing
}
-- | V1 error format.
rluXgafv :: Lens' RemarketingListsUpdate (Maybe Xgafv)
rluXgafv = lens _rluXgafv (\ s a -> s{_rluXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
rluUploadProtocol :: Lens' RemarketingListsUpdate (Maybe Text)
rluUploadProtocol
= lens _rluUploadProtocol
(\ s a -> s{_rluUploadProtocol = a})
-- | OAuth access token.
rluAccessToken :: Lens' RemarketingListsUpdate (Maybe Text)
rluAccessToken
= lens _rluAccessToken
(\ s a -> s{_rluAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
rluUploadType :: Lens' RemarketingListsUpdate (Maybe Text)
rluUploadType
= lens _rluUploadType
(\ s a -> s{_rluUploadType = a})
-- | User profile ID associated with this request.
rluProFileId :: Lens' RemarketingListsUpdate Int64
rluProFileId
= lens _rluProFileId (\ s a -> s{_rluProFileId = a})
. _Coerce
-- | Multipart request metadata.
rluPayload :: Lens' RemarketingListsUpdate RemarketingList
rluPayload
= lens _rluPayload (\ s a -> s{_rluPayload = a})
-- | JSONP
rluCallback :: Lens' RemarketingListsUpdate (Maybe Text)
rluCallback
= lens _rluCallback (\ s a -> s{_rluCallback = a})
instance GoogleRequest RemarketingListsUpdate where
type Rs RemarketingListsUpdate = RemarketingList
type Scopes RemarketingListsUpdate =
'["https://www.googleapis.com/auth/dfatrafficking"]
requestClient RemarketingListsUpdate'{..}
= go _rluProFileId _rluXgafv _rluUploadProtocol
_rluAccessToken
_rluUploadType
_rluCallback
(Just AltJSON)
_rluPayload
dFAReportingService
where go
= buildClient
(Proxy :: Proxy RemarketingListsUpdateResource)
mempty
|
brendanhay/gogol
|
gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/RemarketingLists/Update.hs
|
mpl-2.0
| 5,299
| 0
| 19
| 1,248
| 806
| 467
| 339
| 117
| 1
|
{-# LANGUAGE OverloadedStrings, TemplateHaskell, QuasiQuotes, RecordWildCards, DataKinds #-}
module Model.Party
( module Model.Party.Types
, partyName
, partyEmail
, lookupParty
, isNobodyParty
, lookupPartyAuthorizations
, lookupAuthParty
, lookupSiteAuthByEmail
, changeParty
, changeAccount
, addParty
, addAccount
, removeParty
, auditAccountLogin
, recentAccountLogins
, partyRowJSON
, partyJSON
, toFormattedParty
, PartyFilter(..)
, findParties
, lookupAvatar
, changeAvatar
, getDuplicateParties
) where
import Control.Applicative ((<|>))
import Control.Exception.Lifted (handleJust)
import Control.Monad (guard)
import qualified Data.ByteString as BS
import Data.Int (Int64)
import Data.List (intercalate)
import Data.Maybe (isNothing, fromMaybe)
import Data.Monoid ((<>))
import qualified Data.String
import qualified Data.Text as T
-- import Database.PostgreSQL.Typed (pgSQL)
import Database.PostgreSQL.Typed.Query (unsafeModifyQuery)
import Database.PostgreSQL.Typed.Dynamic (pgLiteralRep, pgLiteralString, pgSafeLiteral)
import Database.PostgreSQL.Typed.Types
import Ops
import Has (Has(..), peek)
import Service.DB
import qualified JSON
import HTTP.Request
import Model.Id
import Model.SQL
import Model.Paginate
import Model.Paginate.SQL
import Model.Permission
import Model.Audit
-- import Model.Audit.SQL
import Model.Identity.Types
import Model.Volume
import Model.Asset.Types
import Model.Asset.SQL
import Model.Party.Types
import Model.Party.SQL
import Model.URL (URI)
useTDB
partyName :: PartyRow -> T.Text
partyName PartyRow{ partyPreName = Just p, partySortName = n } = p <> T.cons ' ' n
partyName PartyRow{ partySortName = n } = n
emailPermission :: Permission
emailPermission = PermissionSHARED
showEmail :: Identity -> Bool
showEmail i = accessSite i >= emailPermission
partyEmail :: Party -> Maybe BS.ByteString
partyEmail p =
guard (partyPermission p >= emailPermission) >> accountEmail <$> partyAccount p
-- | Core party object with formatting and authorization applied, ready for
-- JSON output
data FormattedParty = FormattedParty
{ fpyId :: !Int32
, fpySortname :: !T.Text
, fpyPrename :: !(Maybe T.Text)
, fpyOrcid :: !(Maybe String)
, fpyAffiliation :: !(Maybe T.Text)
, fpyUrl :: !(Maybe URI)
, fpyInstitution :: !(Maybe Bool)
, fpyEmail :: !(Maybe BS.ByteString)
, fpyPermission :: !(Maybe Permission)
, fpyAuthorization :: !(Maybe Permission)
}
instance JSON.ToJSON FormattedParty where
toJSON FormattedParty{..} = -- Bryan: if you want to use a fancy generic transform?
JSON.object (
["id" JSON..= fpyId]
<> ["sortname" JSON..= fpySortname]
<> "prename" `JSON.omitIfNothing` fpyPrename
<> "orcid" `JSON.omitIfNothing` fpyOrcid
<> "affiliation" `JSON.omitIfNothing` fpyAffiliation
<> "url" `JSON.omitIfNothing` fpyUrl
<> "institution" `JSON.omitIfNothing` fpyInstitution
<> "email" `JSON.omitIfNothing` fpyEmail
<> "permission" `JSON.omitIfNothing` fpyPermission
<> "authorization" `JSON.omitIfNothing` fpyAuthorization)
partyRowJSON :: JSON.ToObject o => PartyRow -> JSON.Record (Id Party) o
partyRowJSON PartyRow{..} = JSON.Record partyId $
"sortname" JSON..= partySortName
<> "prename" `JSON.kvObjectOrEmpty` partyPreName
<> "orcid" `JSON.kvObjectOrEmpty` (show <$> partyORCID)
<> "affiliation" `JSON.kvObjectOrEmpty` partyAffiliation
<> "url" `JSON.kvObjectOrEmpty` partyURL
partyJSON :: JSON.ToObject o => Party -> JSON.Record (Id Party) o
partyJSON p@Party{..} = partyRowJSON partyRow `JSON.foldObjectIntoRec`
( "institution" `JSON.kvObjectOrEmpty` (True `useWhen` isNothing partyAccount)
<> "email" `JSON.kvObjectOrEmpty` partyEmail p
<> "permission" `JSON.kvObjectOrEmpty` (partyPermission `useWhen` (partyPermission > PermissionREAD)))
-- | Apply formatting and authorization to a core Party object, replacing partyJSON gradually
toFormattedParty :: Party -> FormattedParty
toFormattedParty p@Party{..} = FormattedParty {
fpyId = unId (partyId partyRow)
, fpySortname = partySortName partyRow
, fpyPrename = partyPreName partyRow
, fpyOrcid = show <$> partyORCID partyRow
, fpyAffiliation = partyAffiliation partyRow
, fpyUrl = partyURL partyRow
, fpyInstitution = True `useWhen` isNothing partyAccount
, fpyEmail = partyEmail p
, fpyPermission = partyPermission `useWhen` (partyPermission > PermissionREAD)
, fpyAuthorization = loadedToMaybe partySiteAccess
}
changeParty :: MonadAudit c m => Party -> m ()
changeParty p = do
ident <- getAuditIdentity
let _tenv_a6PEM = unknownPGTypeEnv
dbExecute1' -- (updateParty 'ident 'p)
(mapQuery2
((\ _p_a6PEN _p_a6PEO _p_a6PEP _p_a6PEQ _p_a6PER _p_a6PES _p_a6PET ->
(BS.concat
[Data.String.fromString
"WITH audit_row AS (UPDATE party SET name=",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PEM
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_p_a6PEN,
Data.String.fromString ",prename=",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PEM
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_p_a6PEO,
Data.String.fromString ",affiliation=",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PEM
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_p_a6PEP,
Data.String.fromString ",url=",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PEM
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_p_a6PEQ,
Data.String.fromString " WHERE id=",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PEM
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PER,
Data.String.fromString
" RETURNING *) INSERT INTO audit.party SELECT CURRENT_TIMESTAMP, ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PEM
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PES,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PEM
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "inet")
_p_a6PET,
Data.String.fromString
", 'change'::audit.action, * FROM audit_row"]))
(partySortName $ partyRow p)
(partyPreName $ partyRow p)
(partyAffiliation $ partyRow p)
(partyURL $ partyRow p)
(partyId $ partyRow p)
(auditWho ident)
(auditIp ident))
(\ [] -> ()))
changeAccount :: MonadAudit c m => SiteAuth -> m ()
changeAccount a = do
ident <- getAuditIdentity
let _tenv_a6PFv = unknownPGTypeEnv
dbExecute1' -- (updateAccount 'ident 'a)
(mapQuery2
((\ _p_a6PFw _p_a6PFx _p_a6PFy _p_a6PFz _p_a6PFA ->
(BS.concat
[Data.String.fromString
"WITH audit_row AS (UPDATE account SET email=",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PFv
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "character varying")
_p_a6PFw,
Data.String.fromString ",password=",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PFv
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "character varying")
_p_a6PFx,
Data.String.fromString " WHERE id=",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PFv
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PFy,
Data.String.fromString
" RETURNING *) INSERT INTO audit.account SELECT CURRENT_TIMESTAMP, ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PFv
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PFz,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PFv
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "inet")
_p_a6PFA,
Data.String.fromString
", 'change'::audit.action, * FROM audit_row"]))
(accountEmail (siteAccount a))
(accountPasswd a)
(partyId $ partyRow (accountParty (siteAccount a)))
(auditWho ident)
(auditIp ident))
(\[] -> ()))
-- | Create a new party without an account, intended for creating institution parties.
addParty :: MonadAudit c m => Party -> m Party
addParty bp = do
ident <- getAuditIdentity
-- Similar to add account, load resulting party with default values for party permission and
-- access.
let _tenv_a6PKN = unknownPGTypeEnv
row <- dbQuery1' -- (insertParty 'ident 'bp)
(mapQuery2
((\ _p_a6PKO _p_a6PKP _p_a6PKQ _p_a6PKR _p_a6PKS _p_a6PKT ->
(BS.concat
[Data.String.fromString
"WITH audit_row AS (INSERT INTO party (name,prename,affiliation,url) VALUES (",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_p_a6PKO,
Data.String.fromString ",",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_p_a6PKP,
Data.String.fromString ",",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_p_a6PKQ,
Data.String.fromString ",",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_p_a6PKR,
Data.String.fromString
") RETURNING *) INSERT INTO audit.party SELECT CURRENT_TIMESTAMP, ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PKS,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "inet")
_p_a6PKT,
Data.String.fromString
", 'add'::audit.action, * FROM audit_row RETURNING party.id,party.name,party.prename,party.orcid,party.affiliation,party.url"]))
(partySortName $ partyRow bp)
(partyPreName $ partyRow bp)
(partyAffiliation $ partyRow bp)
(partyURL $ partyRow bp)
(auditWho ident)
(auditIp ident))
(\
[_cid_a6PKU,
_cname_a6PKV,
_cprename_a6PKX,
_corcid_a6PKY,
_caffiliation_a6PKZ,
_curl_a6PL0]
-> (Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_cid_a6PKU,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_cname_a6PKV,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_cprename_a6PKX,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "bpchar")
_corcid_a6PKY,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_caffiliation_a6PKZ,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_curl_a6PL0)))
let pRow =
(\ (vid_a6PKd, vname_a6PKe, vprename_a6PKf, vorcid_a6PKh,
vaffiliation_a6PKi, vurl_a6PKj)
-> PartyRow
vid_a6PKd
vname_a6PKe
vprename_a6PKf
vorcid_a6PKh
vaffiliation_a6PKi
vurl_a6PKj)
row
pure ((\p -> Party p Nothing NotLoaded PermissionREAD Nothing) pRow)
-- | Create a new account without any authorizations, during registration, using the nobodySiteAuth.
-- The account password will be blank. The party will not have any authorizations yet.
addAccount :: MonadAudit c m => Account -> m Account
addAccount ba@Account{ accountParty = bp } = do
let _tenv_a6PKN = unknownPGTypeEnv
ident <- getAuditIdentity
-- Create a party. The account will be created below, so start with no account.
-- Load resulting party with default values for party permission and access for now.
row <- dbQuery1' -- fmap (\p -> Party p Nothing PermissionREAD Nothing) -- (insertParty 'ident 'bp)
(mapQuery2
((\ _p_a6PKO _p_a6PKP _p_a6PKQ _p_a6PKR _p_a6PKS _p_a6PKT ->
(BS.concat
[Data.String.fromString
"WITH audit_row AS (INSERT INTO party (name,prename,affiliation,url) VALUES (",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_p_a6PKO,
Data.String.fromString ",",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_p_a6PKP,
Data.String.fromString ",",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_p_a6PKQ,
Data.String.fromString ",",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_p_a6PKR,
Data.String.fromString
") RETURNING *) INSERT INTO audit.party SELECT CURRENT_TIMESTAMP, ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PKS,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "inet")
_p_a6PKT,
Data.String.fromString
", 'add'::audit.action, * FROM audit_row RETURNING party.id,party.name,party.prename,party.orcid,party.affiliation,party.url"]))
(partySortName $ partyRow bp)
(partyPreName $ partyRow bp)
(partyAffiliation $ partyRow bp)
(partyURL $ partyRow bp)
(auditWho ident)
(auditIp ident))
(\
[_cid_a6PKU,
_cname_a6PKV,
_cprename_a6PKX,
_corcid_a6PKY,
_caffiliation_a6PKZ,
_curl_a6PL0]
-> (Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_cid_a6PKU,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_cname_a6PKV,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_cprename_a6PKX,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "bpchar")
_corcid_a6PKY,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_caffiliation_a6PKZ,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6PKN
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_curl_a6PL0)))
let pRow =
(\ (vid_a6PKd, vname_a6PKe, vprename_a6PKf, vorcid_a6PKh,
vaffiliation_a6PKi, vurl_a6PKj)
-> PartyRow
vid_a6PKd
vname_a6PKe
vprename_a6PKf
vorcid_a6PKh
vaffiliation_a6PKi
vurl_a6PKj)
row
p = (\pr -> Party pr Nothing NotLoaded PermissionREAD Nothing) pRow
let pa = p{ partyAccount = Just a }
a = ba{ accountParty = pa }
-- Create an account with no password, and the email provided
let _tenv_a6PRz = unknownPGTypeEnv
dbExecute1' -- (insertAccount 'ident 'a)
(mapQuery2
((\ _p_a6PRA _p_a6PRB _p_a6PRC _p_a6PRD ->
(BS.concat
[Data.String.fromString
"WITH audit_row AS (INSERT INTO account (id,email) VALUES (",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PRz
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PRA,
Data.String.fromString ",",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PRz
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "character varying")
_p_a6PRB,
Data.String.fromString
") RETURNING *) INSERT INTO audit.account SELECT CURRENT_TIMESTAMP, ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PRz
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PRC,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PRz
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "inet")
_p_a6PRD,
Data.String.fromString ", 'add'::audit.action, * FROM audit_row"]))
(partyId $ partyRow (accountParty a))
(accountEmail a)
(auditWho ident)
(auditIp ident))
(\ [] -> ()))
return a
removeParty :: MonadAudit c m => Party -> m Bool
removeParty p = do
ident <- getAuditIdentity
dbTransaction $ handleJust (guard . isForeignKeyViolation) (\_ -> return False) $ do
let (_tenv_a6PXO, _tenv_a6PZT) = (unknownPGTypeEnv, unknownPGTypeEnv)
_ <- dbExecute1 -- (deleteAccount 'ident 'p)
(mapQuery2
((\ _p_a6PXP _p_a6PXQ _p_a6PXR ->
(BS.concat
[Data.String.fromString
"WITH audit_row AS (DELETE FROM account WHERE id=",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PXO
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PXP,
Data.String.fromString
" RETURNING *) INSERT INTO audit.account SELECT CURRENT_TIMESTAMP, ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PXO
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PXQ,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PXO
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "inet")
_p_a6PXR,
Data.String.fromString
", 'remove'::audit.action, * FROM audit_row"]))
(partyId $ partyRow p) (auditWho ident) (auditIp ident))
(\[] -> ()))
dbExecute1 -- .(deleteParty 'ident 'p)
(mapQuery2
((\ _p_a6PZU _p_a6PZV _p_a6PZW ->
(BS.concat
[Data.String.fromString
"WITH audit_row AS (DELETE FROM party WHERE id=",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PZT
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PZU,
Data.String.fromString
" RETURNING *) INSERT INTO audit.party SELECT CURRENT_TIMESTAMP, ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PZT
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6PZV,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6PZT
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "inet")
_p_a6PZW,
Data.String.fromString
", 'remove'::audit.action, * FROM audit_row"]))
(partyId $ partyRow p) (auditWho ident) (auditIp ident))
(\[] -> ()))
lookupFixedParty :: Id Party -> Identity -> Maybe Party
lookupFixedParty (Id (-1)) _ = Just nobodyParty
lookupFixedParty (Id 0) i =
Just rootParty{
partyPermission = accessPermission i `max` PermissionSHARED
, partyAccess = (accessMember i > PermissionNONE) `thenUse` view i }
lookupFixedParty i a = view a `useWhen` (i == view a)
isNobodyParty :: Party -> Bool
isNobodyParty = (0 <) . unId . partyId . partyRow
-- | Given the id for a party, ensure ... and resolve the id to the full party object. The produced party has permissions
-- for the retrieving viewer baked in.
lookupParty :: (MonadDB c m, MonadHasIdentity c m) => Id Party -> m (Maybe Party)
lookupParty i = do
ident <- peek
lookupFixedParty i ident `orElseM`
dbQuery1 $(selectQuery (selectParty 'ident) "$WHERE party.id = ${i}")
getDuplicateParties :: MonadDB c m => m [PartyRow]
getDuplicateParties =
dbQuery
$(selectQuery selectPartyRow
"$WHERE exists \
\ (select * \
\ from party p2 \
\ where p2.prename = party.prename and p2.name = party.name and party.id < p2.id) ")
lookupPartyAuthorizations :: (MonadDB c m, MonadHasIdentity c m) => m [(Party, Maybe Permission)]
lookupPartyAuthorizations = do
ident <- peek
let _tenv_a6Qkm = unknownPGTypeEnv
rows <- dbQuery -- (selectQuery (selectPartyAuthorization 'ident) "WHERE party.id > 0")
(mapQuery2
(BS.concat
[Data.String.fromString
"SELECT party.id,party.name,party.prename,party.orcid,party.affiliation,party.url,account.email,authorize_view.site,authorize_view.member FROM party LEFT JOIN account USING (id) LEFT JOIN authorize_view ON party.id = authorize_view.child AND authorize_view.parent = 0 WHERE party.id > 0"])
(\
[_cid_a6Qkn,
_cname_a6Qko,
_cprename_a6Qkp,
_corcid_a6Qkq,
_caffiliation_a6Qkr,
_curl_a6Qks,
_cemail_a6Qkt,
_csite_a6Qku,
_cmember_a6Qkv]
-> (Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6Qkm
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_cid_a6Qkn,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6Qkm
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_cname_a6Qko,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6Qkm
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_cprename_a6Qkp,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6Qkm
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "bpchar")
_corcid_a6Qkq,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6Qkm
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_caffiliation_a6Qkr,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6Qkm
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_curl_a6Qks,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6Qkm
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "character varying")
_cemail_a6Qkt,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6Qkm
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "permission")
_csite_a6Qku,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6Qkm
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "permission")
_cmember_a6Qkv)))
pure
(fmap
(\ (vid_a6Qir, vname_a6Qis, vprename_a6Qit, vorcid_a6Qiu,
vaffiliation_a6Qiv, vurl_a6Qiw, vemail_a6Qix, vsite_a6Qiz,
vmember_a6QiA)
-> Model.Party.SQL.makePartyAuthorization
(Model.Party.SQL.permissionParty
(Model.Party.SQL.makeParty
(PartyRow
vid_a6Qir
vname_a6Qis
vprename_a6Qit
vorcid_a6Qiu
vaffiliation_a6Qiv
vurl_a6Qiw)
(do { cm_a6QiP <- vemail_a6Qix;
Just (Account cm_a6QiP) }))
Nothing
ident)
(do { cm_a6QiV <- vsite_a6Qiz;
cm_a6QiW <- vmember_a6QiA;
Just (Access cm_a6QiV cm_a6QiW) }))
rows)
-- | Find a party by id, populating the party's permission based on
-- a complicated set of cascading rules that determines the current viewer's
-- permissions over the party.
lookupAuthParty :: (MonadDB c m, MonadHasIdentity c m) => Id Party -> m (Maybe Party)
lookupAuthParty i = do
ident <- peek
lookupFixedParty i ident `orElseM`
dbQuery1 $(selectQuery (selectAuthParty 'ident) "$WHERE party.id = ${i}")
-- | resolve email to its party and enclosing account and site authenticated identity, possibly case insensitive
lookupSiteAuthByEmail
:: MonadDB c m
=> Bool -- ^ be case-insensitive?
-> BS.ByteString
-> m (Maybe SiteAuth)
lookupSiteAuthByEmail caseInsensitive e = do
let _tenv_a6QFG = unknownPGTypeEnv
mRow <- dbQuery1 -- (selectQuery selectSiteAuth "WHERE account.email = ${e}")
(mapQuery2
((\ _p_a6QFH ->
BS.concat
[Data.String.fromString
"SELECT party.id,party.name,party.prename,party.orcid,party.affiliation,party.url,account.email,account.password,authorize_view.site,authorize_view.member FROM party JOIN account USING (id) LEFT JOIN authorize_view ON account.id = authorize_view.child AND authorize_view.parent = 0 WHERE account.email = ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6QFG
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_p_a6QFH])
e)
(\
[_cid_a6QFI,
_cname_a6QFJ,
_cprename_a6QFK,
_corcid_a6QFM,
_caffiliation_a6QFN,
_curl_a6QFP,
_cemail_a6QFR,
_cpassword_a6QFT,
_csite_a6QFU,
_cmember_a6QFW]
-> (Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6QFG
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_cid_a6QFI,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6QFG
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_cname_a6QFJ,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6QFG
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_cprename_a6QFK,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6QFG
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "bpchar")
_corcid_a6QFM,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6QFG
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_caffiliation_a6QFN,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6QFG
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_curl_a6QFP,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6QFG
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "character varying")
_cemail_a6QFR,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6QFG
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "character varying")
_cpassword_a6QFT,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6QFG
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "permission")
_csite_a6QFU,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6QFG
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "permission")
_cmember_a6QFW)))
let r =
fmap
(\ (vid_a6QyG, vname_a6QyI, vprename_a6QyJ, vorcid_a6QyL,
vaffiliation_a6QyN, vurl_a6QyO, vemail_a6QyP, vpassword_a6QyQ,
vsite_a6QyR, vmember_a6QyS)
-> Model.Party.SQL.makeSiteAuth
(Model.Party.SQL.makeUserAccount
(Model.Party.SQL.makeAccount
(PartyRow
vid_a6QyG
vname_a6QyI
vprename_a6QyJ
vorcid_a6QyL
vaffiliation_a6QyN
vurl_a6QyO)
(Account vemail_a6QyP)))
vpassword_a6QyQ
(do { cm_a6Qz5 <- vsite_a6QyR;
cm_a6Qz6 <- vmember_a6QyS;
Just (Access cm_a6Qz5 cm_a6Qz6) }))
mRow
if caseInsensitive && isNothing r
then do
let _tenv_a6QN9 = unknownPGTypeEnv
rows <- dbQuery -- (selectQuery selectSiteAuth "WHERE lower(account.email) = lower(${e}) LIMIT 2")
(mapQuery2
((\ _p_a6QNa ->
BS.concat
[Data.String.fromString
"SELECT party.id,party.name,party.prename,party.orcid,party.affiliation,party.url,account.email,account.password,authorize_view.site,authorize_view.member FROM party JOIN account USING (id) LEFT JOIN authorize_view ON account.id = authorize_view.child AND authorize_view.parent = 0 WHERE lower(account.email) = lower(",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6QN9
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_p_a6QNa,
Data.String.fromString ") LIMIT 2"])
e)
(\
[_cid_a6QNb,
_cname_a6QNc,
_cprename_a6QNd,
_corcid_a6QNf,
_caffiliation_a6QNg,
_curl_a6QNh,
_cemail_a6QNi,
_cpassword_a6QNj,
_csite_a6QNk,
_cmember_a6QNl]
-> (Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6QN9
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_cid_a6QNb,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6QN9
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_cname_a6QNc,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6QN9
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_cprename_a6QNd,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6QN9
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "bpchar")
_corcid_a6QNf,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6QN9
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_caffiliation_a6QNg,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6QN9
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_curl_a6QNh,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6QN9
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "character varying")
_cemail_a6QNi,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6QN9
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "character varying")
_cpassword_a6QNj,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6QN9
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "permission")
_csite_a6QNk,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6QN9
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "permission")
_cmember_a6QNl)))
let a = fmap
(\ (vid_a6QLV, vname_a6QLW, vprename_a6QLX, vorcid_a6QLZ,
vaffiliation_a6QM0, vurl_a6QM1, vemail_a6QM2, vpassword_a6QM3,
vsite_a6QM4, vmember_a6QM5)
-> Model.Party.SQL.makeSiteAuth
(Model.Party.SQL.makeUserAccount
(Model.Party.SQL.makeAccount
(PartyRow
vid_a6QLV
vname_a6QLW
vprename_a6QLX
vorcid_a6QLZ
vaffiliation_a6QM0
vurl_a6QM1)
(Account vemail_a6QM2)))
vpassword_a6QM3
(do { cm_a6QMz <- vsite_a6QM4;
cm_a6QMA <- vmember_a6QM5;
Just (Access cm_a6QMz cm_a6QMA) }))
rows
return $ case a of
[x] -> Just x
_ -> Nothing
else
return r
auditAccountLogin :: (MonadHasRequest c m, MonadDB c m) => Bool -> Party -> BS.ByteString -> m ()
auditAccountLogin success who email = do
let _tenv_a6QTK = unknownPGTypeEnv
ip <- getRemoteIp
dbExecute1' -- [pgSQL|INSERT INTO audit.account (audit_action, audit_user, audit_ip, id, email) VALUES
-- (${if success then AuditActionOpen else AuditActionAttempt}, -1, ${ip}, ${partyId $ partyRow who}, ${email})|]
(mapQuery2
((\ _p_a6QTP _p_a6QTQ _p_a6QTR _p_a6QTS ->
(BS.concat
[Data.String.fromString
"INSERT INTO audit.account (audit_action, audit_user, audit_ip, id, email) VALUES\n\
\ (",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6QTK
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "audit.action")
_p_a6QTP,
Data.String.fromString ", -1, ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6QTK
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "inet")
_p_a6QTQ,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6QTK
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6QTR,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6QTK
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "character varying")
_p_a6QTS,
Data.String.fromString ")"]))
(if success then AuditActionOpen else AuditActionAttempt)
ip
(partyId $ partyRow who)
email)
(\[] -> ()))
recentAccountLogins :: MonadDB c m => Party -> m Int64
recentAccountLogins who = fromMaybe 0 <$>
dbQuery1 -- [pgSQL|!SELECT count(*) FROM audit.account WHERE audit_action = 'attempt' AND id = ${partyId $ partyRow who} AND audit_time > CURRENT_TIMESTAMP - interval '1 hour'|]
(let _tenv_a6QXO = unknownPGTypeEnv
in
mapQuery2
((\ _p_a6QXP ->
(BS.concat
[Data.String.fromString
"SELECT count(*) FROM audit.account WHERE audit_action = 'attempt' AND id = ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a6QXO
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a6QXP,
Data.String.fromString
" AND audit_time > CURRENT_TIMESTAMP - interval '1 hour'"]))
(partyId $ partyRow who))
(\ [_ccount_a6QXQ]
-> (Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6QXO
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "bigint")
_ccount_a6QXQ)))
-- | Filter criteria and result paging options
data PartyFilter = PartyFilter
{ partyFilterQuery :: Maybe String
-- ^ pattern to compare first name, last name, and possibly email
, partyFilterAuthorization :: Maybe Permission
-- ^ match on this permission level in acccessing the databrary site group's data
, partyFilterInstitution :: Maybe Bool
-- ^ either only include institutions (True) or
-- only include human parties with active account (False)
, partyFilterPaginate :: Paginate
}
instance Monoid PartyFilter where
mempty = PartyFilter Nothing Nothing Nothing def
mappend (PartyFilter q1 a1 i1 p) (PartyFilter q2 a2 i2 _) =
PartyFilter (q1 <> q2) (a1 <|> a2) (i1 <|> i2) p
partyFilter :: PartyFilter -> Identity -> BS.ByteString
partyFilter PartyFilter{..} ident = BS.concat
[ withq partyFilterAuthorization (const " JOIN authorize_view ON party.id = child AND parent = 0")
, " WHERE id > 0 AND id != ", pgLiteralRep (partyId $ partyRow staffParty)
, withq partyFilterQuery (\n -> " AND " <> queryVal <> " ILIKE " <> pgLiteralRep (wordPat n))
, withq partyFilterAuthorization (\a -> " AND site = " <> pgSafeLiteral a)
, withq partyFilterInstitution (\i -> if i then " AND account.id IS NULL" else " AND account.password IS NOT NULL")
, " ORDER BY name, prename "
, paginateSQL partyFilterPaginate
]
where
withq v f = maybe "" f v
wordPat = intercalate "%" . ("":) . (++[""]) . words
queryVal
| showEmail ident = "(COALESCE(prename || ' ', '') || name || COALESCE(' ' || email, ''))"
| otherwise = "(COALESCE(prename || ' ', '') || name)"
findParties :: (MonadHasIdentity c m, MonadDB c m) => PartyFilter -> m [Party]
findParties pf = do
let _tenv_a6R7j = unknownPGTypeEnv
ident <- peek
rows <- dbQuery $ unsafeModifyQuery -- (selectQuery (selectParty 'ident) "")
(mapQuery2
(BS.concat
-- TODO: this duplicates logic in lookupAuthorization slightly
[Data.String.fromString
"SELECT \
\ party.id,party.name,party.prename,party.orcid,party.affiliation,party.url,account.email \
\ ,COALESCE(av.site, 'NONE') \
\ FROM party \
\ LEFT JOIN account USING (id) \
\ LEFT JOIN authorize_view av \
\ ON party.id = av.child AND av.parent = 0 "])
(\
[_cid_a6R7m,
_cname_a6R7o,
_cprename_a6R7p,
_corcid_a6R7q,
_caffiliation_a6R7r,
_curl_a6R7s,
_cemail_a6R7t,
site]
-> (Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6R7j
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_cid_a6R7m,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6R7j
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_cname_a6R7o,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6R7j
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_cprename_a6R7p,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6R7j
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "bpchar")
_corcid_a6R7q,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6R7j
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_caffiliation_a6R7r,
Database.PostgreSQL.Typed.Types.pgDecodeColumn
_tenv_a6R7j
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "text")
_curl_a6R7s,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6R7j
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "character varying")
_cemail_a6R7t,
Database.PostgreSQL.Typed.Types.pgDecodeColumnNotNull
_tenv_a6R7j
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "permission")
site)))
(<> partyFilter pf ident)
pure
(fmap
(\ (vid_a6R3R, vname_a6R3S, vprename_a6R3T, vorcid_a6R3U,
vaffiliation_a6R3V, vurl_a6R3W, vemail_a6R3X, site)
-> Model.Party.SQL.permissionParty
(Model.Party.SQL.makeParty2
(PartyRow
vid_a6R3R
vname_a6R3S
vprename_a6R3T
vorcid_a6R3U
vaffiliation_a6R3V
vurl_a6R3W)
(do { cm_a6R44 <- vemail_a6R3X;
Just (Account cm_a6R44) })
(Loaded site))
Nothing
ident)
rows)
lookupAvatar :: MonadDB c m => Id Party -> m (Maybe Asset)
lookupAvatar p =
dbQuery1 $ (`Asset` coreVolume) <$> $(selectQuery selectAssetRow $ "$JOIN avatar ON asset.id = avatar.asset WHERE avatar.party = ${p} AND asset.volume = " ++ pgLiteralString (volumeId $ volumeRow coreVolume))
changeAvatar :: MonadAudit c m => Party -> Maybe Asset -> m Bool
changeAvatar p Nothing = do
let _tenv_a76io = unknownPGTypeEnv
ident <- getAuditIdentity
dbExecute1 -- (auditDelete 'ident "avatar" "party = ${partyId $ partyRow p}" Nothing)
(mapQuery2
((\ _p_a76ip _p_a76iq _p_a76ir ->
(BS.concat
[Data.String.fromString
"WITH audit_row AS (DELETE FROM avatar WHERE party = ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a76io
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a76ip,
Data.String.fromString
" RETURNING *) INSERT INTO audit.avatar SELECT CURRENT_TIMESTAMP, ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a76io
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a76iq,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a76io
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "inet")
_p_a76ir,
Data.String.fromString
", 'remove'::audit.action, * FROM audit_row"]))
(partyId $ partyRow p) (auditWho ident) (auditIp ident))
(\[] -> ()))
changeAvatar p (Just a) = do
let (_tenv_a76iP, _tenv_a76jh) = (unknownPGTypeEnv, unknownPGTypeEnv)
ident <- getAuditIdentity
(0 <) . fst <$> updateOrInsert
-- (auditUpdate 'ident "avatar" [("asset", "${assetId $ assetRow a}")] "party = ${partyId $ partyRow p}" Nothing)
(mapQuery2
((\ _p_a76iQ _p_a76iR _p_a76iS _p_a76iT ->
(BS.concat
[Data.String.fromString
"WITH audit_row AS (UPDATE avatar SET asset=",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a76iP
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a76iQ,
Data.String.fromString " WHERE party = ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a76iP
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a76iR,
Data.String.fromString
" RETURNING *) INSERT INTO audit.avatar SELECT CURRENT_TIMESTAMP, ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a76iP
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a76iS,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a76iP
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "inet")
_p_a76iT,
Data.String.fromString
", 'change'::audit.action, * FROM audit_row"]))
(assetId $ assetRow a)
(partyId $ partyRow p)
(auditWho ident)
(auditIp ident))
(\ [] -> ()))
-- (auditInsert 'ident "avatar" [("asset", "${assetId $ assetRow a}"), ("party", "${partyId $ partyRow p}")] Nothing)
(mapQuery2
((\ _p_a76ji _p_a76jj _p_a76jk _p_a76jl ->
(BS.concat
[Data.String.fromString
"WITH audit_row AS (INSERT INTO avatar (asset,party) VALUES (",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a76jh
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a76ji,
Data.String.fromString ",",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a76jh
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a76jj,
Data.String.fromString
") RETURNING *) INSERT INTO audit.avatar SELECT CURRENT_TIMESTAMP, ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a76jh
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "integer")
_p_a76jk,
Data.String.fromString ", ",
Database.PostgreSQL.Typed.Types.pgEscapeParameter
_tenv_a76jh
(Database.PostgreSQL.Typed.Types.PGTypeProxy ::
Database.PostgreSQL.Typed.Types.PGTypeName "inet")
_p_a76jl,
Data.String.fromString ", 'add'::audit.action, * FROM audit_row"]))
(assetId $ assetRow a)
(partyId $ partyRow p)
(auditWho ident)
(auditIp ident))
(\ [] -> ()))
|
databrary/databrary
|
src/Model/Party.hs
|
agpl-3.0
| 60,286
| 0
| 26
| 23,310
| 9,055
| 5,257
| 3,798
| 1,138
| 3
|
-- eidolon -- A simple gallery in Haskell and Yesod
-- Copyright (C) 2015 Amedeo Molnár
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Affero General Public License as published
-- by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
module Handler.Tag where
import Import
import qualified Data.Text as T
import System.FilePath
getTagR :: Text -> Handler Html
getTagR tag = do
tempMedia <- runDB $ selectList [] [Desc MediumTitle]
almostMedia <- mapM (\a -> do
case tag `elem` (mediumTags $ entityVal a) of
True -> return (Just a)
False -> return Nothing
) tempMedia
media <- return $ removeItem Nothing almostMedia
defaultLayout $ do
setTitle $ toHtml ("Eidolon :: Tag " `T.append` tag)
$(widgetFile "tagMedia")
|
Mic92/eidolon
|
Handler/Tag.hs
|
agpl-3.0
| 1,292
| 0
| 18
| 263
| 202
| 109
| 93
| 16
| 2
|
{-# LANGUAGE RecordWildCards, TemplateHaskell, QuasiQuotes, DataKinds #-}
module EZID.Volume
( updateEZID
) where
import Control.Arrow ((&&&))
import Control.Monad ((<=<))
import Control.Monad.IO.Class (liftIO)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import Data.Function (on)
import Data.List (deleteFirstsBy)
import Data.Maybe (fromMaybe, mapMaybe)
import Data.Time.Clock (utctDay, getCurrentTime)
import Database.PostgreSQL.Typed.Query (pgSQL)
import qualified Network.Wai as Wai
import Has
import Service.DB
import Service.Log
import Context
import Model.Time
import Model.Permission
import Model.Identity
import Model.Id
import Model.Volume
import Model.VolumeAccess
import Model.Citation
import Model.Container
import Model.Slot
import Model.Funding
import Model.Tag
import Action.Route
import Controller.Volume
import EZID.API
import EZID.DataCite
useTDB
volumeDOISuffix :: Id Volume -> BS.ByteString
volumeDOISuffix i = BSC.pack $ '.' : show i
volumeEZID :: (MonadDB c m, MonadHasIdentity c m) => Volume -> Maybe Citation -> m EZIDMeta
volumeEZID v@Volume{ volumeRow = VolumeRow{..}, ..} cite = do
top <- lookupVolumeTopContainer v
own <- lookupVolumeAccess v PermissionADMIN
fund <- lookupVolumeFunding v
link <- lookupVolumeLinks v
key <- lookupSlotKeywords (containerSlot top)
return EZIDPublic
{ ezidTarget = actionURI (Just Wai.defaultRequest) viewVolume (HTML, volumeId) []
, ezidDataCite = DataCite
{ dataCiteDOI = volumeDOI
, dataCiteTitle = volumeName
, dataCiteAuthors = map volumeAccessParty own
, dataCiteYear = dateYear (utctDay volumeCreation)
, dataCiteDescription = volumeBody
, dataCiteFunders = fund
, dataCitePublication = citationURL =<< cite
, dataCiteReferences = mapMaybe citationURL link
, dataCiteSubjects = map (tagNameBS . tagName) key
}
}
lookupVolumeDOIs :: MonadDB c m => m [(Id Volume, BS.ByteString)]
lookupVolumeDOIs = dbQuery [pgSQL|!SELECT id, doi FROM volume WHERE doi IS NOT NULL|]
addVolumeDOI :: MonadDB c m => Id Volume -> BS.ByteString -> m Bool
addVolumeDOI v d = dbExecute1 [pgSQL|UPDATE volume SET doi = ${d} WHERE id = ${v} AND doi IS NULL|]
updateVolume :: Volume -> Maybe Citation -> EZIDM Bool
updateVolume v = maybe
(maybe (return False) (addVolumeDOI $ volumeId $ volumeRow v) <=< ezidCreate (volumeDOISuffix $ volumeId $ volumeRow v))
ezidModify
(volumeDOI $ volumeRow v)
<=< volumeEZID v
removeVolume :: Id Volume -> BS.ByteString -> EZIDM Bool
removeVolume _ d = ezidModify d EZIDUnavailable
updateEZID :: BackgroundContextM (Maybe Bool)
updateEZID = runEZIDM $ do
r <- ezidStatus
if r
then do
vl <- lookupVolumesCitations
mapM_ (uncurry updateVolume) vl
dl <- lookupVolumeDOIs
mapM_ (uncurry removeVolume) $
deleteFirstsBy (on (==) fst) dl (map ((volumeId &&& fromMaybe BS.empty . volumeDOI) . volumeRow . fst) vl)
else do
t <- liftIO getCurrentTime
focusIO $ logMsg t "ezid is down"
return r
|
databrary/databrary
|
src/EZID/Volume.hs
|
agpl-3.0
| 3,064
| 0
| 22
| 557
| 915
| 489
| 426
| -1
| -1
|
-- | Line number demo.
-- Author : Andy Stewart
-- Copyright : (c) 2010 Andy Stewart <lazycat.manatee@gmail.com>
--
-- This demo show how to build your own line number gutter.
--
module Main where
import Graphics.UI.Gtk
import Graphics.UI.Gtk.SourceView
main = do
-- Init.
initGUI
-- Create window.
window <- windowNew
windowSetDefaultSize window 900 600
windowSetPosition window WinPosCenter
-- Create source view widget.
sourceView <- sourceViewNew
-- Create scroll window.
scrolledWindow <- scrolledWindowNew Nothing Nothing
-- Insert CellRendererText in source view's gutter.
gutter <- sourceViewGetGutter sourceView TextWindowLeft
cell <- cellRendererTextNew
sourceGutterInsert gutter cell 0
-- Set gutter data.
sourceGutterSetCellDataFunc gutter cell $ \ c l currentLine -> do
-- Display line number.
set (castToCellRendererText c) [cellText := show (l + 1)]
-- Highlight current line.
let color = if currentLine
then Color 65535 0 0
else Color 0 65535 0
set (castToCellRendererText c) [cellTextForegroundColor := color]
-- Set gutter size.
sourceGutterSetCellSizeFunc gutter cell $ \ c ->
-- -1 mean cell renderer will adjust width with chars dynamically.
set (castToCellRendererText c) [cellTextWidthChars := (-1)]
-- Connect and show.
scrolledWindow `containerAdd` sourceView
window `containerAdd` scrolledWindow
window `onDestroy` mainQuit
widgetShowAll window
mainGUI
|
gtk2hs/gtksourceview
|
demo/LineNumber.hs
|
lgpl-2.1
| 1,560
| 0
| 16
| 371
| 295
| 151
| 144
| 26
| 2
|
import XMonad hiding ((|||))
import XMonad.Core
import XMonad.Hooks.DynamicLog hiding (dzen)
import XMonad.Hooks.ManageDocks
import XMonad.Hooks.FadeInactive (fadeInactiveLogHook)
import XMonad.Layout hiding ((|||))
import XMonad.Layout.WindowNavigation
import XMonad.Layout.NoBorders
import XMonad.Layout.ResizableTile
import XMonad.Layout.SimpleFloat
import XMonad.Layout.Grid
import XMonad.Layout.IM
import XMonad.Layout.LayoutCombinators
import XMonad.Layout.PerWorkspace
import XMonad.Layout.LayoutHints
import qualified XMonad.Actions.GridSelect as GridSet
import Data.Char (toLower)
import Data.List (isInfixOf)
import Data.Ratio ((%))
import Text.Printf
import XMonad.Hooks.EwmhDesktops (ewmh)
import XMonad.Hooks.ManageHelpers (doFullFloat, isFullscreen)
import qualified XMonad.StackSet as W
import XMonad.Util.EZConfig
import XMonad.Util.NamedScratchpad
import XMonad.Actions.CopyWindow
import XMonad.Prompt
import XMonad.Prompt.Shell
import XMonad.Prompt.RunOrRaise
import XMonad.Config.Kde (kde4Config)
myWorkspaces = ["code","www","3","fm","bo","dia","7","tty","im"]
scratchpads = [ termScratchPad "mpsyt" "mpsyt" defaultFloating
, termScratchPad "htop" "htop" defaultFloating
, termScratchPad "alsamixer" "alsamixer" defaultFloating
, NS "goldendict" "goldendict" (className =? "GoldenDict") defaultFloating
]
termScratchPad name cmd layout = NS name
-- (printf "%s -t %s -e %s" myTerminal name cmd) -- Mate-terminal
(printf "%s -p tabtitle=%s -e %s" myTerminal name $ cmd) -- Konsole
(fmap (isInfixOf name . map toLower) title) layout
myManageHook = composeAll
[ className =? "Mate-panel" --> doFloat
, className =? "Smplayer" --> doFloat
, className =? "Goldendict" --> doFloat
, className =? "Firefox" --> doShift "www"
, className =? "Firefox-esr" --> doShift "www"
, className =? "Navigator" --> doShift "www"
, className =? "Okular" --> doShift "bo"
, className =? "Mendeleydesktop.x86_64" --> doShift "bo"
, className =? "Qtcreator" --> doShift "code"
, className =? "Evolution" --> doShift "im"
, className =? "Workrave" --> doF copyToAll
, className =? "Clementine" --> doFloat
, className =? "Slack" --> doShift "im"
, title =? "kred_cluster" --> doShift "tty"
, isFullscreen --> (doF W.focusDown <+> doFullFloat)
-- Desperate attempts to fix plasma:
, wmName =? "Desktop" --> doFloat
, className =? "plasmashell" --> doFloat
]
where wmRole = stringProperty "WM_WINDOW_ROLE"
wmName = stringProperty "WM_NAME"
-- isNotification = do
-- wm_type <- getAtom "_NET_WM_WINDOW_TYPE"
-- notification <- getAtom "_NET_WM_WINDOW_TYPE_NOTIFICATION"
-- wmType = stringProperty ""
deltaL = 3/100
defaultSize = 1/2
zoom = 1.3
--layoutIM = withIM (1%7) (Role "MainWindow#1") Full
--layoutIM = withIM (1%7) (Title "Gwenview") Full
layoutIM = myLayout
layoutTall = Tall 1 deltaL defaultSize
myLayout = layoutTall
||| (Mirror $ layoutTall)
||| Full
||| simpleFloat
bgColor1 = "#1D1F21"
fgColor1 = "#93AEC6"
bgColor2 = "#373B41"
fgColor2 = "#9B94BB"
myTerminal :: String
-- myTerminal = "mate-terminal"
myTerminal = "konsole"
spawnTerm a = spawn $ myTerminal ++ " -e " ++ a
--screenShot = spawn "scrot '%Y-%m-%d_$wx$h.png' -e 'mv $f ~/shots/'"
myKeybinds = [ ("M-<Shift>-<Return>", spawn myTerminal)
, ("M-z", GridSet.goToSelected GridSet.def)
, ("M-c", spawn myDmenu)
-- Spawn things:
, ("M-s M-d", namedScratchpadAction scratchpads "goldendict")
-- ,("M-s M-s", screenShot)
, ("M-s M-e", spawn "emacs")
, ("M-s M-t", spawn orgAgenda)
, ("M-s M-m", namedScratchpadAction scratchpads "mpsyt")
, ("M-s M-h", namedScratchpadAction scratchpads "htop")
, ("M-s M-a", namedScratchpadAction scratchpads "alsamixer")
, ("M-s M-k", spawn "kcharselect")
-- , ("<XF86AudioNext>", spawn "mpc next")
-- , ("<XF86AudioPrev>", spawn "mpc prev")
-- , ("<XF86AudioPlay>", spawn "mpc toggle")
-- 2D window navigation:
, ("M-<R>", sendMessage $ Go R)
, ("M-<L>", sendMessage $ Go L)
, ("M-<U>", sendMessage $ Go U)
, ("M-<D>", sendMessage $ Go D)
, ("M-s M-s", spawn "rofi -show ssh")
, ("M-q", spawn "quote")
] ++
[ (otherModMasks ++ "M-" ++ [key], action tag)
| (tag, key) <- zip myWorkspaces ['1' .. '9']
, (otherModMasks, action) <- [ ("", windows . W.view)
, ("S-", windows . W.shift)
, ("C-", windows . W.greedyView)
]
]
myConf = kde4Config
{ terminal = myTerminal
, workspaces = myWorkspaces
, focusFollowsMouse = True
, modMask = mod4Mask
, borderWidth = 2
, normalBorderColor = bgColor1
-- , focusedBorderColor = "#CCAA11"
, startupHook = spawn "compton"
, manageHook = namedScratchpadManageHook scratchpads
<+> myManageHook <+> manageHook kde4Config
, layoutHook = avoidStruts . smartBorders . windowNavigation $
onWorkspace "bo" (Full ||| layoutTall) $
onWorkspace "im" layoutIM $
onWorkspace "tty" (Grid ||| layoutTall) $
onWorkspace "3" (Grid ||| layoutTall)
myLayout
--, logHook = fadeInactiveLogHook 0xf0000000
} `additionalKeysP` myKeybinds
main = xmonad $ docks $ ewmh myConf
myDmenu :: String
myDmenu = "LANG=en_US.utf8 rofi -show run"
-- myDmenu = printf "$(yeganesh -x -- -b -nb '%s' -nf '%s' -sb '%s' -sf '%s')"
-- bgColor1 fgColor1 bgColor2 fgColor2
orgAgenda = "emacsclient -c --eval '(let ((org-agenda-window-setup `only-window)) (org-todo-list))'"
|
k32/dotfiles
|
xmonad.hs
|
unlicense
| 6,880
| 18
| 13
| 2,394
| 1,359
| 747
| 612
| 117
| 1
|
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module GeneticImage where
import qualified Data.Vector as V
import Diagrams.Prelude
import Diagrams.Backend.Cairo
import Diagrams.Backend.Cairo.List
import Data.Colour
import Data.Colour.SRGB
import Data.Foldable (fold)
import Data.Bits.Bitwise (fromListBE)
import Data.Word
import Control.Monad
import Control.Monad.State.Lazy
import Genetics
class GeneticImage a where
generateImage :: Chromasome -> a
persistImage :: FilePath -> Double -> Double -> a -> IO ()
imageValue :: a -> a -> IO Double
fromDisk :: FilePath -> IO (Either String a)
instance GeneticImage (Diagram Cairo R2) where
generateImage chromasome = fst $ runState fullDiagram chromasome
persistImage path x y = renderCairo path (Dims x y)
imageValue = cmp
fromDisk path = do
dImageEither <- loadImageExt path
return $ fmap image dImageEither
triangleCount :: Int
triangleCount = 200
bitCount :: Int
bitCount = (((7 * 32) + (3 * 8)) * triangleCount) + (3 * 32)
drawTriangle :: Angle ->
Angle ->
Double ->
Double ->
Colour Double ->
R2 ->
Angle ->
Diagram Cairo R2
drawTriangle a1 a2 l1 l2 c t ro = polygon (with & polyType .~ PolySides [a1, a2][l1, l2]) #
rotate ro #
translate t #
opacity 0.5 #
fc c #
lw none
integerParameter :: State (V.Vector Bool) Int
integerParameter = do
bools <- get
let (forInteger, rest) = V.splitAt 32 bools
put rest
return $ fromListBE $ V.toList forInteger
word8Parameter :: State (V.Vector Bool) Word8
word8Parameter = do
bools <- get
let (forWord, rest) = V.splitAt 8 bools
put rest
return $ fromListBE $ V.toList forWord
triangleFromBools :: State (V.Vector Bool) (Diagram Cairo R2)
triangleFromBools = triangleFromParams
<$> fmap fromIntegral integerParameter
<*> fmap fromIntegral integerParameter
<*> fmap fromIntegral integerParameter
<*> fmap fromIntegral integerParameter
<*> word8Parameter
<*> word8Parameter
<*> word8Parameter
<*> fmap fromIntegral integerParameter
<*> fmap fromIntegral integerParameter
<*> fmap fromIntegral integerParameter
where triangleFromParams a1 a2 l1 l2 r g b tx ty ro = drawTriangle (a1 @@ deg) (a2 @@ deg) l1 l2 (sRGB24 r g b) (r2 (tx, ty)) (ro @@ deg)
fullDiagram :: State (V.Vector Bool) (Diagram Cairo R2)
fullDiagram = do
redC <- fmap fromIntegral integerParameter
greenC <- fmap fromIntegral integerParameter
blueC <- fmap fromIntegral integerParameter
triangles <- replicateM triangleCount triangleFromBools
return $ fold triangles # bg (sRGB24 redC greenC blueC)
cmp :: Diagram Cairo R2 -> Diagram Cairo R2 -> IO Double
cmp base img = do
baseAlphaColours <- renderToList 100 100 base
imgAlphaColours <- renderToList 100 100 img
let difference = imgDiff baseAlphaColours imgAlphaColours
putStrLn $ "diff: " ++ show difference
return difference
imgDiff :: [[AlphaColour Double]] -> [[AlphaColour Double]] -> Double
imgDiff img1 img2 = abs $ sum $ zipWith diffPix (concat img1) (concat img2)
diffPix :: AlphaColour Double -> AlphaColour Double -> Double
diffPix a1 a2 = fullDiff
where normNaN v = if (isNaN v) then 0 else v
redF a = normNaN $ channelRed $ toSRGB (a `over` black)
greenF a = normNaN $ channelGreen $ toSRGB (a `over` black)
blueF a = normNaN $ channelBlue $ toSRGB (a `over` black)
diffRed = redF a1 - redF a2
diffGreen = greenF a1 - greenF a2
diffBlue = blueF a1 - blueF a2
fullDiff = (diffRed * diffRed) - (diffGreen * diffGreen) - (diffBlue * diffBlue)
err = show $ "Colour: " ++ show a1 ++ " red a1: " ++ show (redF a1) ++ " red a2: " ++ show (redF a2) ++ " diffRed: " ++ show diffRed ++ " diffGreen: " ++ show diffGreen ++ " diffBlue: " ++ show diffBlue
|
noelmarkham/caravaggio
|
geneticimage.hs
|
apache-2.0
| 4,495
| 0
| 18
| 1,440
| 1,357
| 679
| 678
| 98
| 2
|
module Step_3_1 where
import Slides
page = slideDeck "Chapter 3"
[ titleSlide "Chapter 3"
[ "Tuples, Types, and Maybe"
]
, codeSlide "Two Things"
"A 2-Tuple is pair of two values, the fst and the snd \
\(not a typo!):"
[ "(43, \"Bob\") -- a tuple of an Int and String"
, "(\"Bob\", 43) -- a tuple of a String and an Int"
, "(True, [1, 2, 3]) -- a tuple of a Bool and a list"
, ""
, "('x', (True, 12)) -- hmmmmm..."
]
, codeSlide "Two Things"
"When we talk about the type of a tuple, we must specify \
\the type of the two parts:"
[ "(Int, String)"
, "(String, Int)"
, "(Bool, [Int])"
, ""
, "(Char, (Bool, Int))"
]
, codeSlide "Accessing the parts"
"You can both pattern match, or use functions to access the \
\parts of a tuple:"
[ "isAdult (age, name) = age >= 18"
, ""
, "isAdult person = fst person >= 18"
]
, codeSlide "Putting them together"
"You can put them together by using parenthesis and comma:"
[ "makePerson :: Int -> String -> (Int, String)"
, "makePerson age name = (age, name)"
]
]
|
mzero/barley
|
seed/Chapter3/Step_3_1.hs
|
apache-2.0
| 1,256
| 0
| 8
| 455
| 113
| 66
| 47
| 28
| 1
|
rest a b | a<b = a
| otherwise=rest (a-b) b
ggT a 0 = a
ggT a 1 = 1
ggT a b = ggT b (rem a b)
nimm n [] =[]
nimm 0 ys = []
nimm n (x:xs) = x : (nimm ( n-1) xs)
wuwu2 x a b 20 ys = ys
wuwu2 x a b n ys | ((a+b)*0.5)^2>x = wuwu2 x a ((a+b)*0.5) (n+1) (((a+b)*0.5) : ys)
| ((a+b)*0.5)^2<x = wuwu2 x ((a+b)*0.5) b (n+1) (((a+b)*0.5) : ys)
| otherwise = ((a+b)*0.5) : ys
wuwu x | 0>x = undefined
| otherwise = wuwu2 x 0 (x+1) 0 [0,x+1]
quicksort [] = []
quicksort (head:tail) =
let
smallerNumbers = quicksort (filter (<=head) tail)
biggerNumbers = quicksort (filter (>head) tail)
in
smallerNumbers ++ [head] ++ biggerNumbers
ack 0 n = n + 1
ack n 0 = ack (n - 1) 1
ack n m = ack (n - 1) ( ack n ( m - 1 ) )
|
steffzahn/test
|
test.hs
|
apache-2.0
| 803
| 13
| 13
| 267
| 633
| 300
| 333
| 23
| 1
|
module Propellor.Property.Tor where
import Propellor
import qualified Propellor.Property.File as File
import qualified Propellor.Property.Apt as Apt
import qualified Propellor.Property.Service as Service
import Utility.FileMode
import System.Posix.Files
import Data.Char
type HiddenServiceName = String
type NodeName = String
-- | Sets up a tor bridge. (Not a relay or exit node.)
--
-- Uses port 443
isBridge :: Property NoInfo
isBridge = isBridge' []
isBridge' :: [String] -> Property NoInfo
isBridge' extraconfig = server config
`describe` "tor bridge"
where
config =
[ "BridgeRelay 1"
, "Exitpolicy reject *:*"
, "ORPort 443"
] ++ extraconfig
-- | Sets up a tor relay.
--
-- Uses port 443
isRelay :: Property NoInfo
isRelay = isRelay' []
isRelay' :: [String] -> Property NoInfo
isRelay' extraconfig = server config
`describe` "tor relay"
where
config =
[ "BridgeRelay 0"
, "Exitpolicy reject *:*"
, "ORPort 443"
] ++ extraconfig
-- | Converts a property like isBridge' or isRelay' to be a named
-- node, with a known private key.
--
-- This can be moved to a different IP without needing to wait to
-- accumulate trust.
--
-- The base property can be used to start out and then upgraded to
-- a named property later.
named :: NodeName -> ([String] -> Property NoInfo) -> Property HasInfo
named n basep = p `describe` (getDesc p ++ " " ++ n)
where
p = basep ["Nickname " ++ saneNickname n]
`requires` torPrivKey (Context ("tor " ++ n))
-- | A tor server (bridge, relay, or exit)
-- Don't use if you just want to run tor for personal use.
server :: [String] -> Property NoInfo
server extraconfig = setup
`requires` Apt.installed ["tor", "ntp"]
`describe` "tor server"
where
setup = mainConfig `File.hasContent` config
`onChange` restarted
config =
[ "SocksPort 0"
] ++ extraconfig
torPrivKey :: Context -> Property HasInfo
torPrivKey context = f `File.hasPrivContent` context
`onChange` File.ownerGroup f user user
-- install tor first, so the directory exists with right perms
`requires` Apt.installed ["tor"]
where
f = "/var/lib/tor/keys/secret_id_key"
hiddenServiceAvailable :: HiddenServiceName -> Int -> Property NoInfo
hiddenServiceAvailable hn port = hiddenServiceHostName prop
where
prop = mainConfig `File.containsLines`
[ unwords ["HiddenServiceDir", varLib </> hn]
, unwords ["HiddenServicePort", show port, "127.0.0.1:" ++ show port]
]
`describe` "hidden service available"
`onChange` Service.reloaded "tor"
hiddenServiceHostName p = adjustPropertySatisfy p $ \satisfy -> do
r <- satisfy
h <- liftIO $ readFile (varLib </> hn </> "hostname")
warningMessage $ unwords ["hidden service hostname:", h]
return r
hiddenService :: HiddenServiceName -> Int -> Property NoInfo
hiddenService hn port = mainConfig `File.containsLines`
[ unwords ["HiddenServiceDir", varLib </> hn]
, unwords ["HiddenServicePort", show port, "127.0.0.1:" ++ show port]
]
`describe` unwords ["hidden service available:", hn, show port]
`onChange` restarted
hiddenServiceData :: IsContext c => HiddenServiceName -> c -> Property HasInfo
hiddenServiceData hn context = combineProperties desc
[ installonion "hostname"
, installonion "private_key"
]
where
desc = unwords ["hidden service data available in", varLib </> hn]
installonion f = withPrivData (PrivFile $ varLib </> hn </> f) context $ \getcontent ->
property desc $ getcontent $ install $ varLib </> hn </> f
install f content = ifM (liftIO $ doesFileExist f)
( noChange
, ensureProperties
[ property desc $ makeChange $ do
createDirectoryIfMissing True (takeDirectory f)
writeFileProtected f content
, File.mode (takeDirectory f) $ combineModes
[ownerReadMode, ownerWriteMode, ownerExecuteMode]
, File.ownerGroup (takeDirectory f) user user
, File.ownerGroup f user user
]
)
restarted :: Property NoInfo
restarted = Service.restarted "tor"
mainConfig :: FilePath
mainConfig = "/etc/tor/torrc"
varLib :: FilePath
varLib = "/var/lib/tor"
varRun :: FilePath
varRun = "/var/run/tor"
user :: UserName
user = "debian-tor"
type NickName = String
-- | Convert String to a valid tor NickName.
saneNickname :: String -> NickName
saneNickname s
| null n = "unnamed"
| otherwise = n
where
legal c = isNumber c || isAsciiUpper c || isAsciiLower c
n = take 19 $ filter legal s
|
aisamanra/smaccm-propellor
|
src/Propellor/Property/Tor.hs
|
bsd-2-clause
| 4,357
| 60
| 16
| 784
| 1,208
| 652
| 556
| 100
| 1
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QBoxLayout.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:30
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QBoxLayout (
QqBoxLayout(..)
,addSpacing
,QaddStretch(..)
,addStrut
,QinsertLayout(..)
,insertSpacing
,QinsertStretch(..)
,qBoxLayout_delete
,qBoxLayout_deleteLater
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Core.Qt
import Qtc.Enums.Gui.QBoxLayout
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
instance QuserMethod (QBoxLayout ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QBoxLayout_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QBoxLayout_userMethod" qtc_QBoxLayout_userMethod :: Ptr (TQBoxLayout a) -> CInt -> IO ()
instance QuserMethod (QBoxLayoutSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QBoxLayout_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QBoxLayout ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QBoxLayout_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QBoxLayout_userMethodVariant" qtc_QBoxLayout_userMethodVariant :: Ptr (TQBoxLayout a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QBoxLayoutSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QBoxLayout_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
class QqBoxLayout x1 where
qBoxLayout :: x1 -> IO (QBoxLayout ())
instance QqBoxLayout ((QBoxLayoutDirection)) where
qBoxLayout (x1)
= withQBoxLayoutResult $
qtc_QBoxLayout (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QBoxLayout" qtc_QBoxLayout :: CLong -> IO (Ptr (TQBoxLayout ()))
instance QqBoxLayout ((QBoxLayoutDirection, QWidget t2)) where
qBoxLayout (x1, x2)
= withQBoxLayoutResult $
withObjectPtr x2 $ \cobj_x2 ->
qtc_QBoxLayout1 (toCLong $ qEnum_toInt x1) cobj_x2
foreign import ccall "qtc_QBoxLayout1" qtc_QBoxLayout1 :: CLong -> Ptr (TQWidget t2) -> IO (Ptr (TQBoxLayout ()))
instance QaddItem (QBoxLayout ()) ((QLayoutItem t1)) (IO ()) where
addItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_addItem_h cobj_x0 cobj_x1
foreign import ccall "qtc_QBoxLayout_addItem_h" qtc_QBoxLayout_addItem_h :: Ptr (TQBoxLayout a) -> Ptr (TQLayoutItem t1) -> IO ()
instance QaddItem (QBoxLayoutSc a) ((QLayoutItem t1)) (IO ()) where
addItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_addItem_h cobj_x0 cobj_x1
instance QaddLayout (QBoxLayout a) ((QLayout t1)) where
addLayout x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_addLayout cobj_x0 cobj_x1
foreign import ccall "qtc_QBoxLayout_addLayout" qtc_QBoxLayout_addLayout :: Ptr (TQBoxLayout a) -> Ptr (TQLayout t1) -> IO ()
instance QaddLayout (QBoxLayout a) ((QLayout t1, Int)) where
addLayout x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_addLayout1 cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QBoxLayout_addLayout1" qtc_QBoxLayout_addLayout1 :: Ptr (TQBoxLayout a) -> Ptr (TQLayout t1) -> CInt -> IO ()
addSpacing :: QBoxLayout a -> ((Int)) -> IO ()
addSpacing x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_addSpacing cobj_x0 (toCInt x1)
foreign import ccall "qtc_QBoxLayout_addSpacing" qtc_QBoxLayout_addSpacing :: Ptr (TQBoxLayout a) -> CInt -> IO ()
class QaddStretch x1 where
addStretch :: QBoxLayout a -> x1 -> IO ()
instance QaddStretch (()) where
addStretch x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_addStretch cobj_x0
foreign import ccall "qtc_QBoxLayout_addStretch" qtc_QBoxLayout_addStretch :: Ptr (TQBoxLayout a) -> IO ()
instance QaddStretch ((Int)) where
addStretch x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_addStretch1 cobj_x0 (toCInt x1)
foreign import ccall "qtc_QBoxLayout_addStretch1" qtc_QBoxLayout_addStretch1 :: Ptr (TQBoxLayout a) -> CInt -> IO ()
addStrut :: QBoxLayout a -> ((Int)) -> IO ()
addStrut x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_addStrut cobj_x0 (toCInt x1)
foreign import ccall "qtc_QBoxLayout_addStrut" qtc_QBoxLayout_addStrut :: Ptr (TQBoxLayout a) -> CInt -> IO ()
instance QaddWidget (QBoxLayout ()) ((QWidget t1)) (IO ()) where
addWidget x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_addWidget cobj_x0 cobj_x1
foreign import ccall "qtc_QBoxLayout_addWidget" qtc_QBoxLayout_addWidget :: Ptr (TQBoxLayout a) -> Ptr (TQWidget t1) -> IO ()
instance QaddWidget (QBoxLayoutSc a) ((QWidget t1)) (IO ()) where
addWidget x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_addWidget cobj_x0 cobj_x1
instance QaddWidget (QBoxLayout ()) ((QWidget t1, Int)) (IO ()) where
addWidget x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_addWidget1 cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QBoxLayout_addWidget1" qtc_QBoxLayout_addWidget1 :: Ptr (TQBoxLayout a) -> Ptr (TQWidget t1) -> CInt -> IO ()
instance QaddWidget (QBoxLayoutSc a) ((QWidget t1, Int)) (IO ()) where
addWidget x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_addWidget1 cobj_x0 cobj_x1 (toCInt x2)
instance QaddWidget (QBoxLayout ()) ((QWidget t1, Int, Alignment)) (IO ()) where
addWidget x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_addWidget2 cobj_x0 cobj_x1 (toCInt x2) (toCLong $ qFlags_toInt x3)
foreign import ccall "qtc_QBoxLayout_addWidget2" qtc_QBoxLayout_addWidget2 :: Ptr (TQBoxLayout a) -> Ptr (TQWidget t1) -> CInt -> CLong -> IO ()
instance QaddWidget (QBoxLayoutSc a) ((QWidget t1, Int, Alignment)) (IO ()) where
addWidget x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_addWidget2 cobj_x0 cobj_x1 (toCInt x2) (toCLong $ qFlags_toInt x3)
instance Qcount (QBoxLayout ()) (()) where
count x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_count_h cobj_x0
foreign import ccall "qtc_QBoxLayout_count_h" qtc_QBoxLayout_count_h :: Ptr (TQBoxLayout a) -> IO CInt
instance Qcount (QBoxLayoutSc a) (()) where
count x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_count_h cobj_x0
instance Qdirection (QBoxLayout a) (()) (IO (QBoxLayoutDirection)) where
direction x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_direction cobj_x0
foreign import ccall "qtc_QBoxLayout_direction" qtc_QBoxLayout_direction :: Ptr (TQBoxLayout a) -> IO CLong
instance QexpandingDirections (QBoxLayout ()) (()) where
expandingDirections x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_expandingDirections_h cobj_x0
foreign import ccall "qtc_QBoxLayout_expandingDirections_h" qtc_QBoxLayout_expandingDirections_h :: Ptr (TQBoxLayout a) -> IO CLong
instance QexpandingDirections (QBoxLayoutSc a) (()) where
expandingDirections x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_expandingDirections_h cobj_x0
instance QhasHeightForWidth (QBoxLayout ()) (()) where
hasHeightForWidth x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_hasHeightForWidth_h cobj_x0
foreign import ccall "qtc_QBoxLayout_hasHeightForWidth_h" qtc_QBoxLayout_hasHeightForWidth_h :: Ptr (TQBoxLayout a) -> IO CBool
instance QhasHeightForWidth (QBoxLayoutSc a) (()) where
hasHeightForWidth x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_hasHeightForWidth_h cobj_x0
instance QheightForWidth (QBoxLayout ()) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_heightForWidth_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QBoxLayout_heightForWidth_h" qtc_QBoxLayout_heightForWidth_h :: Ptr (TQBoxLayout a) -> CInt -> IO CInt
instance QheightForWidth (QBoxLayoutSc a) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_heightForWidth_h cobj_x0 (toCInt x1)
instance QinsertItem (QBoxLayout ()) ((Int, QLayoutItem t2)) (IO ()) where
insertItem x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QBoxLayout_insertItem cobj_x0 (toCInt x1) cobj_x2
foreign import ccall "qtc_QBoxLayout_insertItem" qtc_QBoxLayout_insertItem :: Ptr (TQBoxLayout a) -> CInt -> Ptr (TQLayoutItem t2) -> IO ()
instance QinsertItem (QBoxLayoutSc a) ((Int, QLayoutItem t2)) (IO ()) where
insertItem x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QBoxLayout_insertItem cobj_x0 (toCInt x1) cobj_x2
class QinsertLayout x1 where
insertLayout :: QBoxLayout a -> x1 -> IO ()
instance QinsertLayout ((Int, QLayout t2)) where
insertLayout x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QBoxLayout_insertLayout cobj_x0 (toCInt x1) cobj_x2
foreign import ccall "qtc_QBoxLayout_insertLayout" qtc_QBoxLayout_insertLayout :: Ptr (TQBoxLayout a) -> CInt -> Ptr (TQLayout t2) -> IO ()
instance QinsertLayout ((Int, QLayout t2, Int)) where
insertLayout x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QBoxLayout_insertLayout1 cobj_x0 (toCInt x1) cobj_x2 (toCInt x3)
foreign import ccall "qtc_QBoxLayout_insertLayout1" qtc_QBoxLayout_insertLayout1 :: Ptr (TQBoxLayout a) -> CInt -> Ptr (TQLayout t2) -> CInt -> IO ()
insertSpacing :: QBoxLayout a -> ((Int, Int)) -> IO ()
insertSpacing x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_insertSpacing cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QBoxLayout_insertSpacing" qtc_QBoxLayout_insertSpacing :: Ptr (TQBoxLayout a) -> CInt -> CInt -> IO ()
class QinsertStretch x1 where
insertStretch :: QBoxLayout a -> x1 -> IO ()
instance QinsertStretch ((Int)) where
insertStretch x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_insertStretch cobj_x0 (toCInt x1)
foreign import ccall "qtc_QBoxLayout_insertStretch" qtc_QBoxLayout_insertStretch :: Ptr (TQBoxLayout a) -> CInt -> IO ()
instance QinsertStretch ((Int, Int)) where
insertStretch x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_insertStretch1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QBoxLayout_insertStretch1" qtc_QBoxLayout_insertStretch1 :: Ptr (TQBoxLayout a) -> CInt -> CInt -> IO ()
instance QinsertWidget (QBoxLayout a) ((Int, QWidget t2)) (IO ()) where
insertWidget x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QBoxLayout_insertWidget cobj_x0 (toCInt x1) cobj_x2
foreign import ccall "qtc_QBoxLayout_insertWidget" qtc_QBoxLayout_insertWidget :: Ptr (TQBoxLayout a) -> CInt -> Ptr (TQWidget t2) -> IO ()
instance QinsertWidget (QBoxLayout a) ((Int, QWidget t2, Int)) (IO ()) where
insertWidget x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QBoxLayout_insertWidget1 cobj_x0 (toCInt x1) cobj_x2 (toCInt x3)
foreign import ccall "qtc_QBoxLayout_insertWidget1" qtc_QBoxLayout_insertWidget1 :: Ptr (TQBoxLayout a) -> CInt -> Ptr (TQWidget t2) -> CInt -> IO ()
instance QinsertWidget (QBoxLayout a) ((Int, QWidget t2, Int, Alignment)) (IO ()) where
insertWidget x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QBoxLayout_insertWidget2 cobj_x0 (toCInt x1) cobj_x2 (toCInt x3) (toCLong $ qFlags_toInt x4)
foreign import ccall "qtc_QBoxLayout_insertWidget2" qtc_QBoxLayout_insertWidget2 :: Ptr (TQBoxLayout a) -> CInt -> Ptr (TQWidget t2) -> CInt -> CLong -> IO ()
instance Qinvalidate (QBoxLayout ()) (()) where
invalidate x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_invalidate_h cobj_x0
foreign import ccall "qtc_QBoxLayout_invalidate_h" qtc_QBoxLayout_invalidate_h :: Ptr (TQBoxLayout a) -> IO ()
instance Qinvalidate (QBoxLayoutSc a) (()) where
invalidate x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_invalidate_h cobj_x0
instance QitemAt (QBoxLayout ()) ((Int)) (IO (QLayoutItem ())) where
itemAt x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_itemAt_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QBoxLayout_itemAt_h" qtc_QBoxLayout_itemAt_h :: Ptr (TQBoxLayout a) -> CInt -> IO (Ptr (TQLayoutItem ()))
instance QitemAt (QBoxLayoutSc a) ((Int)) (IO (QLayoutItem ())) where
itemAt x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_itemAt_h cobj_x0 (toCInt x1)
instance QqmaximumSize (QBoxLayout ()) (()) where
qmaximumSize x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_maximumSize_h cobj_x0
foreign import ccall "qtc_QBoxLayout_maximumSize_h" qtc_QBoxLayout_maximumSize_h :: Ptr (TQBoxLayout a) -> IO (Ptr (TQSize ()))
instance QqmaximumSize (QBoxLayoutSc a) (()) where
qmaximumSize x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_maximumSize_h cobj_x0
instance QmaximumSize (QBoxLayout ()) (()) where
maximumSize x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_maximumSize_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QBoxLayout_maximumSize_qth_h" qtc_QBoxLayout_maximumSize_qth_h :: Ptr (TQBoxLayout a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QmaximumSize (QBoxLayoutSc a) (()) where
maximumSize x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_maximumSize_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QminimumHeightForWidth (QBoxLayout ()) ((Int)) where
minimumHeightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_minimumHeightForWidth_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QBoxLayout_minimumHeightForWidth_h" qtc_QBoxLayout_minimumHeightForWidth_h :: Ptr (TQBoxLayout a) -> CInt -> IO CInt
instance QminimumHeightForWidth (QBoxLayoutSc a) ((Int)) where
minimumHeightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_minimumHeightForWidth_h cobj_x0 (toCInt x1)
instance QqminimumSize (QBoxLayout ()) (()) where
qminimumSize x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_minimumSize_h cobj_x0
foreign import ccall "qtc_QBoxLayout_minimumSize_h" qtc_QBoxLayout_minimumSize_h :: Ptr (TQBoxLayout a) -> IO (Ptr (TQSize ()))
instance QqminimumSize (QBoxLayoutSc a) (()) where
qminimumSize x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_minimumSize_h cobj_x0
instance QminimumSize (QBoxLayout ()) (()) where
minimumSize x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_minimumSize_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QBoxLayout_minimumSize_qth_h" qtc_QBoxLayout_minimumSize_qth_h :: Ptr (TQBoxLayout a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSize (QBoxLayoutSc a) (()) where
minimumSize x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_minimumSize_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QsetDirection (QBoxLayout a) ((QBoxLayoutDirection)) where
setDirection x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_setDirection cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QBoxLayout_setDirection" qtc_QBoxLayout_setDirection :: Ptr (TQBoxLayout a) -> CLong -> IO ()
instance QqsetGeometry (QBoxLayout ()) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_setGeometry_h cobj_x0 cobj_x1
foreign import ccall "qtc_QBoxLayout_setGeometry_h" qtc_QBoxLayout_setGeometry_h :: Ptr (TQBoxLayout a) -> Ptr (TQRect t1) -> IO ()
instance QqsetGeometry (QBoxLayoutSc a) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_setGeometry_h cobj_x0 cobj_x1
instance QsetGeometry (QBoxLayout ()) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QBoxLayout_setGeometry_qth_h cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QBoxLayout_setGeometry_qth_h" qtc_QBoxLayout_setGeometry_qth_h :: Ptr (TQBoxLayout a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QBoxLayoutSc a) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QBoxLayout_setGeometry_qth_h cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
instance QsetSpacing (QBoxLayout ()) ((Int)) where
setSpacing x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_setSpacing cobj_x0 (toCInt x1)
foreign import ccall "qtc_QBoxLayout_setSpacing" qtc_QBoxLayout_setSpacing :: Ptr (TQBoxLayout a) -> CInt -> IO ()
instance QsetSpacing (QBoxLayoutSc a) ((Int)) where
setSpacing x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_setSpacing cobj_x0 (toCInt x1)
instance QsetStretchFactor (QBoxLayout a) ((QLayout t1, Int)) (IO (Bool)) where
setStretchFactor x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_setStretchFactor1 cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QBoxLayout_setStretchFactor1" qtc_QBoxLayout_setStretchFactor1 :: Ptr (TQBoxLayout a) -> Ptr (TQLayout t1) -> CInt -> IO CBool
instance QsetStretchFactor (QBoxLayout a) ((QWidget t1, Int)) (IO (Bool)) where
setStretchFactor x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_setStretchFactor cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QBoxLayout_setStretchFactor" qtc_QBoxLayout_setStretchFactor :: Ptr (TQBoxLayout a) -> Ptr (TQWidget t1) -> CInt -> IO CBool
instance QqsizeHint (QBoxLayout ()) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_sizeHint_h cobj_x0
foreign import ccall "qtc_QBoxLayout_sizeHint_h" qtc_QBoxLayout_sizeHint_h :: Ptr (TQBoxLayout a) -> IO (Ptr (TQSize ()))
instance QqsizeHint (QBoxLayoutSc a) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_sizeHint_h cobj_x0
instance QsizeHint (QBoxLayout ()) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QBoxLayout_sizeHint_qth_h" qtc_QBoxLayout_sizeHint_qth_h :: Ptr (TQBoxLayout a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint (QBoxLayoutSc a) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance Qspacing (QBoxLayout ()) (()) where
spacing x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_spacing cobj_x0
foreign import ccall "qtc_QBoxLayout_spacing" qtc_QBoxLayout_spacing :: Ptr (TQBoxLayout a) -> IO CInt
instance Qspacing (QBoxLayoutSc a) (()) where
spacing x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_spacing cobj_x0
instance QtakeAt (QBoxLayout ()) ((Int)) where
takeAt x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_takeAt_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QBoxLayout_takeAt_h" qtc_QBoxLayout_takeAt_h :: Ptr (TQBoxLayout a) -> CInt -> IO (Ptr (TQLayoutItem ()))
instance QtakeAt (QBoxLayoutSc a) ((Int)) where
takeAt x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_takeAt_h cobj_x0 (toCInt x1)
qBoxLayout_delete :: QBoxLayout a -> IO ()
qBoxLayout_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_delete cobj_x0
foreign import ccall "qtc_QBoxLayout_delete" qtc_QBoxLayout_delete :: Ptr (TQBoxLayout a) -> IO ()
qBoxLayout_deleteLater :: QBoxLayout a -> IO ()
qBoxLayout_deleteLater x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_deleteLater cobj_x0
foreign import ccall "qtc_QBoxLayout_deleteLater" qtc_QBoxLayout_deleteLater :: Ptr (TQBoxLayout a) -> IO ()
instance QaddChildLayout (QBoxLayout ()) ((QLayout t1)) where
addChildLayout x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_addChildLayout cobj_x0 cobj_x1
foreign import ccall "qtc_QBoxLayout_addChildLayout" qtc_QBoxLayout_addChildLayout :: Ptr (TQBoxLayout a) -> Ptr (TQLayout t1) -> IO ()
instance QaddChildLayout (QBoxLayoutSc a) ((QLayout t1)) where
addChildLayout x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_addChildLayout cobj_x0 cobj_x1
instance QaddChildWidget (QBoxLayout ()) ((QWidget t1)) where
addChildWidget x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_addChildWidget cobj_x0 cobj_x1
foreign import ccall "qtc_QBoxLayout_addChildWidget" qtc_QBoxLayout_addChildWidget :: Ptr (TQBoxLayout a) -> Ptr (TQWidget t1) -> IO ()
instance QaddChildWidget (QBoxLayoutSc a) ((QWidget t1)) where
addChildWidget x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_addChildWidget cobj_x0 cobj_x1
instance QqalignmentRect (QBoxLayout ()) ((QRect t1)) where
qalignmentRect x0 (x1)
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_alignmentRect cobj_x0 cobj_x1
foreign import ccall "qtc_QBoxLayout_alignmentRect" qtc_QBoxLayout_alignmentRect :: Ptr (TQBoxLayout a) -> Ptr (TQRect t1) -> IO (Ptr (TQRect ()))
instance QqalignmentRect (QBoxLayoutSc a) ((QRect t1)) where
qalignmentRect x0 (x1)
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_alignmentRect cobj_x0 cobj_x1
instance QalignmentRect (QBoxLayout ()) ((Rect)) where
alignmentRect x0 (x1)
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QBoxLayout_alignmentRect_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QBoxLayout_alignmentRect_qth" qtc_QBoxLayout_alignmentRect_qth :: Ptr (TQBoxLayout a) -> CInt -> CInt -> CInt -> CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
instance QalignmentRect (QBoxLayoutSc a) ((Rect)) where
alignmentRect x0 (x1)
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QBoxLayout_alignmentRect_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h crect_ret_x crect_ret_y crect_ret_w crect_ret_h
instance QchildEvent (QBoxLayout ()) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_childEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QBoxLayout_childEvent" qtc_QBoxLayout_childEvent :: Ptr (TQBoxLayout a) -> Ptr (TQChildEvent t1) -> IO ()
instance QchildEvent (QBoxLayoutSc a) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_childEvent cobj_x0 cobj_x1
instance QindexOf (QBoxLayout ()) ((QWidget t1)) where
indexOf x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_indexOf_h cobj_x0 cobj_x1
foreign import ccall "qtc_QBoxLayout_indexOf_h" qtc_QBoxLayout_indexOf_h :: Ptr (TQBoxLayout a) -> Ptr (TQWidget t1) -> IO CInt
instance QindexOf (QBoxLayoutSc a) ((QWidget t1)) where
indexOf x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_indexOf_h cobj_x0 cobj_x1
instance QqisEmpty (QBoxLayout ()) (()) where
qisEmpty x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_isEmpty_h cobj_x0
foreign import ccall "qtc_QBoxLayout_isEmpty_h" qtc_QBoxLayout_isEmpty_h :: Ptr (TQBoxLayout a) -> IO CBool
instance QqisEmpty (QBoxLayoutSc a) (()) where
qisEmpty x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_isEmpty_h cobj_x0
instance Qlayout (QBoxLayout ()) (()) (IO (QLayout ())) where
layout x0 ()
= withQLayoutResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_layout_h cobj_x0
foreign import ccall "qtc_QBoxLayout_layout_h" qtc_QBoxLayout_layout_h :: Ptr (TQBoxLayout a) -> IO (Ptr (TQLayout ()))
instance Qlayout (QBoxLayoutSc a) (()) (IO (QLayout ())) where
layout x0 ()
= withQLayoutResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_layout_h cobj_x0
instance QwidgetEvent (QBoxLayout ()) ((QEvent t1)) where
widgetEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_widgetEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QBoxLayout_widgetEvent" qtc_QBoxLayout_widgetEvent :: Ptr (TQBoxLayout a) -> Ptr (TQEvent t1) -> IO ()
instance QwidgetEvent (QBoxLayoutSc a) ((QEvent t1)) where
widgetEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_widgetEvent cobj_x0 cobj_x1
instance Qqgeometry (QBoxLayout ()) (()) where
qgeometry x0 ()
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_geometry_h cobj_x0
foreign import ccall "qtc_QBoxLayout_geometry_h" qtc_QBoxLayout_geometry_h :: Ptr (TQBoxLayout a) -> IO (Ptr (TQRect ()))
instance Qqgeometry (QBoxLayoutSc a) (()) where
qgeometry x0 ()
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_geometry_h cobj_x0
instance Qgeometry (QBoxLayout ()) (()) where
geometry x0 ()
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_geometry_qth_h cobj_x0 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QBoxLayout_geometry_qth_h" qtc_QBoxLayout_geometry_qth_h :: Ptr (TQBoxLayout a) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
instance Qgeometry (QBoxLayoutSc a) (()) where
geometry x0 ()
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_geometry_qth_h cobj_x0 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
instance QspacerItem (QBoxLayout ()) (()) where
spacerItem x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_spacerItem_h cobj_x0
foreign import ccall "qtc_QBoxLayout_spacerItem_h" qtc_QBoxLayout_spacerItem_h :: Ptr (TQBoxLayout a) -> IO (Ptr (TQSpacerItem ()))
instance QspacerItem (QBoxLayoutSc a) (()) where
spacerItem x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_spacerItem_h cobj_x0
instance Qwidget (QBoxLayout ()) (()) where
widget x0 ()
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_widget_h cobj_x0
foreign import ccall "qtc_QBoxLayout_widget_h" qtc_QBoxLayout_widget_h :: Ptr (TQBoxLayout a) -> IO (Ptr (TQWidget ()))
instance Qwidget (QBoxLayoutSc a) (()) where
widget x0 ()
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_widget_h cobj_x0
instance QconnectNotify (QBoxLayout ()) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QBoxLayout_connectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QBoxLayout_connectNotify" qtc_QBoxLayout_connectNotify :: Ptr (TQBoxLayout a) -> CWString -> IO ()
instance QconnectNotify (QBoxLayoutSc a) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QBoxLayout_connectNotify cobj_x0 cstr_x1
instance QcustomEvent (QBoxLayout ()) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_customEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QBoxLayout_customEvent" qtc_QBoxLayout_customEvent :: Ptr (TQBoxLayout a) -> Ptr (TQEvent t1) -> IO ()
instance QcustomEvent (QBoxLayoutSc a) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_customEvent cobj_x0 cobj_x1
instance QdisconnectNotify (QBoxLayout ()) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QBoxLayout_disconnectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QBoxLayout_disconnectNotify" qtc_QBoxLayout_disconnectNotify :: Ptr (TQBoxLayout a) -> CWString -> IO ()
instance QdisconnectNotify (QBoxLayoutSc a) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QBoxLayout_disconnectNotify cobj_x0 cstr_x1
instance Qevent (QBoxLayout ()) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_event_h cobj_x0 cobj_x1
foreign import ccall "qtc_QBoxLayout_event_h" qtc_QBoxLayout_event_h :: Ptr (TQBoxLayout a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent (QBoxLayoutSc a) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_event_h cobj_x0 cobj_x1
instance QeventFilter (QBoxLayout ()) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QBoxLayout_eventFilter_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QBoxLayout_eventFilter_h" qtc_QBoxLayout_eventFilter_h :: Ptr (TQBoxLayout a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter (QBoxLayoutSc a) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QBoxLayout_eventFilter_h cobj_x0 cobj_x1 cobj_x2
instance Qreceivers (QBoxLayout ()) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QBoxLayout_receivers cobj_x0 cstr_x1
foreign import ccall "qtc_QBoxLayout_receivers" qtc_QBoxLayout_receivers :: Ptr (TQBoxLayout a) -> CWString -> IO CInt
instance Qreceivers (QBoxLayoutSc a) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QBoxLayout_receivers cobj_x0 cstr_x1
instance Qsender (QBoxLayout ()) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_sender cobj_x0
foreign import ccall "qtc_QBoxLayout_sender" qtc_QBoxLayout_sender :: Ptr (TQBoxLayout a) -> IO (Ptr (TQObject ()))
instance Qsender (QBoxLayoutSc a) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QBoxLayout_sender cobj_x0
instance QtimerEvent (QBoxLayout ()) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_timerEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QBoxLayout_timerEvent" qtc_QBoxLayout_timerEvent :: Ptr (TQBoxLayout a) -> Ptr (TQTimerEvent t1) -> IO ()
instance QtimerEvent (QBoxLayoutSc a) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QBoxLayout_timerEvent cobj_x0 cobj_x1
|
uduki/hsQt
|
Qtc/Gui/QBoxLayout.hs
|
bsd-2-clause
| 32,974
| 0
| 16
| 5,442
| 10,821
| 5,486
| 5,335
| -1
| -1
|
-- http://www.codewars.com/kata/534e01fbbb17187c7e0000c6
var spiralize = function(size) {
var ret = [];
for(var i=0; i<size; i++){
ret[i] = [];
for(var j=0; j<size; j++){
var coil = Math.min.apply(this, [i, j, size-1-i, size-1-j]);
var odd = coil % 2;
ret[i][j] = +(!odd && !(i==coil+1 && j==coil) || odd && i==coil+1 && j==coil);
}
}
return ret;
}
|
Bodigrim/katas
|
src/haskell/3-Make-a-spiral.hs
|
bsd-2-clause
| 386
| 13
| 17
| 91
| 247
| 132
| 115
| -1
| -1
|
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
module NW.Item where
import Control.Monad.Primitive
import System.Random.MWC
import NW.Affix
import NW.Effect
import NW.Random
import NW.Stats
data ItemClass
= ICGear Gear -- something you wear (armor, weapons)
| ICPotion -- something you drink to heal/get temporary effects
-- | Scroll -- one-shot magical spells
deriving (Eq, Show)
instance Variate ItemClass where
uniform rng = do
a <- uniformR (0,1 :: Int) rng
case a of
0 -> do
gear <- uniform rng
return $ ICGear gear
_ -> return ICPotion
uniformR _ _ = error "uniformR: ItemClass unsupported"
data Gear
= GArmor Armor
| GWeapon Weapon
| GAccessory Accessory -- pendants, amulets, rings, necklaces, etc.
deriving (Eq, Show)
data Armor
= Helm
| Breastplate
| Boots
| Gloves
| Shield
deriving (Eq, Enum, Show)
instance Variate Armor where
uniform rng = return
. toEnum
=<< uniformR (fromEnum Helm, fromEnum Shield) rng
uniformR _ _ = error "uniformR: Armor unsupported"
data Weapon
= Sword
| Axe
| Dagger
| Spear
| Pike
| Flail
| Staff
deriving (Eq, Enum, Show)
instance Variate Weapon where
uniform rng = return
. toEnum
=<< uniformR (fromEnum Sword, fromEnum Staff) rng
uniformR _ _ = error "uniformR: Weapon unsupported"
data Accessory
= Ring
| Necklace -- aka "Pendant", "Amulet"
| Earring
| Bracelet
deriving (Eq, Enum, Show)
instance Variate Accessory where
uniform rng = return
. toEnum
=<< uniformR (fromEnum Ring, fromEnum Bracelet) rng
uniformR _ _ = error "uniformR: Accessory unsupported"
data Item = Item
{ itemClass :: ItemClass
, itemAffixes :: [Affix]
} deriving (Eq, Show)
instance Variate Gear where
uniform rng = do
g <- uniformR (0,2 :: Int) rng
x <- case g of
0 -> return . GArmor =<< uniform rng
1 -> return . GWeapon =<< uniform rng
_ -> return . GAccessory =<< uniform rng
return x
uniformR _ _ = error "uniformR: Gear unsupported"
-- uniformR (a, b) rng
-- | a == b = return a
-- | a > b = uniformR (b, a) rng
-- | otherwise = return . toEnum =<< uniformR (fromEnum a, fromEnum b) rng
-- | Generate a random item. This function should be called when a monster dies
-- and we need to create loot.
genRandomItem :: PrimMonad m => AffixDB -> Gen (PrimState m) -> m Item
genRandomItem adb rng = do
ic <- uniform rng
affixes <- case ic of
ICGear _ -> do
-- You can have up to 2 affixes. If we pick a NAME affix, our 2nd
-- affix must be an ADJ affix. NAME affixes are generally more
-- powerful (at least, they are supposed to be more powerful), so
-- there is only a small percent chance that we'll get a NAME affix.
-- The possibilities are:
-- * 1 adj only ("steel gloves") (can't just be 'gloves' because
-- that's too barren)
-- * 1 proper noun suffix ("gloves of the bear")
-- * 1 noun suffix ("shield of doom")
-- * 1 persona ("assassin's dagger" or "dagger of the assassin")
-- * 1 name only ("daniel's gloves" or "shield of achilles")
-- For simplicity's sake, we only choose 1 affix.
ac <- uniform rng
affix <- rndSelect (filter ((== ac) . affixClass) adb) rng
mapM (rasterizeAffix rng) [affix]
-- there should be a handful of hardcoded potion types that are
-- essential to the game, regardless of the kind of game content (e.g.,
-- health potion, mega health potion, mana potion, elixir, etc>), and
-- these types should get some priority over other exotic potions
ICPotion -> return []
return $ Item
{ itemClass = ic
, itemAffixes = affixes
}
-- | The only modifier that affects the player at a variable rate is damage
-- done; all others (health, mana, defense, resistance, life steal, etc.) affect
-- the character at a constant rate. Thus, we "rasterize" any NVRange value we
-- find for damage modifiers.
rasterizeAffix :: PrimMonad m => Gen (PrimState m) -> Affix -> m Affix
rasterizeAffix rng affix@Affix{..} = do
es <- mapM (rasterizeEffect rng) affixEffects
return $ affix
{ affixEffects = es
}
-- | Only rasterize non-damage-dealing effects.
rasterizeEffect :: PrimMonad m => Gen (PrimState m) -> Effect -> m Effect
rasterizeEffect rng effect@(et, nv) = case et of
EAttribute Damage -> return effect
EAttribute (DamageE _) -> return effect
_ -> case nv of
NVRange (a, b) -> do
c <- uniformR (a, b) rng
return (et, (NVConst c))
_ -> return effect
-- | The higher the rating, the more "valuable" the item, all things equal. This
-- function is useful for at least two situations: (1) random item generation
-- and (2) item shops (merchant AI's valuation of an item).
itemRating :: Item -> Int
itemRating Item{..} = sum $ map affixRating itemAffixes
affixRating :: Affix -> Int
affixRating Affix{..} = affixClassRating + (sum $ map effectRating affixEffects)
where
affixClassRating = case affixClass of
ACAdj -> 10
ACNoun -> 20
ACNounProper -> 20
ACPersona -> 30
ACName -> 40
effectRating :: Effect -> Int
effectRating (effectType, nv) = effectTypeRating effectType * nvRating nv
effectTypeRating :: EffectType -> Int
effectTypeRating et = case et of
EAttribute Health -> 10
EAttribute Mana -> 10
EAttribute Strength -> 10
EAttribute Wisdom -> 10
EAttribute Attack -> 7
EAttribute MAttack -> 7
EAttribute Defense -> 7
EAttribute MDefense -> 7
EAttribute Damage -> 9
EAttribute (DamageE _) -> 5
EAttribute (Resist _) -> 5
EAttribute LifeSteal -> 8
EGameMechanics MagicItemFind -> 3
EGameMechanics GoldEarned -> 2
nvRating :: NumberVal -> Int
nvRating (NVConst n) = n
nvRating (NVPerc n) = n
nvRating (NVRange (a, b)) = div (sum [a..b]) $ length [a..b]
renderItem :: Item -> String
renderItem Item{..} = prefix ++ noun ++ suffix
where
noun = case itemClass of
ICGear g -> case g of
GArmor a -> show a
GWeapon w -> show w
GAccessory c -> show c
ICPotion -> "Potion"
(prefix, suffix)
| null itemAffixes = ("", "")
| otherwise = case affixClass of
ACAdj -> (affixName ++ " ", "")
ACNoun -> ("", " of " ++ affixName)
ACNounProper -> ("", " of the " ++ affixName)
ACPersona -> (affixName ++ "'s ", "") -- "Killer's" or "Assassin's"
ACName -> ("", " of " ++ affixName)
where
Affix{..} = head itemAffixes
|
listx/netherworld
|
src/NW/Item.hs
|
bsd-2-clause
| 6,319
| 32
| 19
| 1,327
| 1,698
| 875
| 823
| 155
| 14
|
{-# OPTIONS_HADDOCK hide #-}
module Data.GeoIP2.SearchTree where
import Data.Binary
import Data.Bits (shift, testBit, (.&.), (.|.))
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import Data.Int
import Data.IP (IP (..), fromIPv4, fromIPv6b)
-- | Convert byte to list of bits starting from the most significant one
byteToBits :: Int -> [Bool]
byteToBits b = map (testBit b) [7,6..0]
-- | Convert IP address to bits
ipToBits :: IP -> [Bool]
ipToBits (IPv4 addr) = concatMap byteToBits (fromIPv4 addr)
ipToBits (IPv6 addr) = concatMap byteToBits (fromIPv6b addr)
-- | Read node (2 records) given the index of a node
readNode :: BL.ByteString -> Int -> Int64 -> (Int64, Int64)
readNode mem recordbits index =
let
bytecount = fromIntegral $ recordbits `div` 4
bytes = BL.take (fromIntegral bytecount) $ BL.drop (fromIntegral $ index * bytecount) mem
numbers = concatMap BS.unpack (BL.toChunks bytes) :: [Word8]
makenum = foldl (\acc new -> fromIntegral new + 256 * acc) 0 :: [Word8] -> Word64
num = makenum numbers
-- 28 bits has a strange record format
left28 = num `shift` (-32) .|. (num .&. 0xf0000000)
in case recordbits of
28 -> (fromIntegral left28, fromIntegral (num .&. ((1 `shift` recordbits) - 1)))
_ -> (fromIntegral (num `shift` negate recordbits), fromIntegral (num .&. ((1 `shift` recordbits) - 1)))
-- | Get offset in the Data Section
getDataOffset :: Monad m => (BL.ByteString, Int64, Int) -> [Bool] -> m Int64
getDataOffset (mem, nodeCount, recordSize) startbits =
getnode startbits 0
where
getnode _ index
| index == nodeCount = fail "Information for address does not exist."
| index > nodeCount = return $ index - nodeCount - 16
getnode [] _ = fail "IP address too short????"
getnode (bit:rest) index = getnode rest nextOffset
where
(left, right) = readNode mem recordSize index
nextOffset = if bit then right else left
|
rvion/geoip2
|
Data/GeoIP2/SearchTree.hs
|
bsd-3-clause
| 2,040
| 0
| 17
| 472
| 662
| 365
| 297
| 35
| 4
|
{-
- Hacq (c) 2013 NEC Laboratories America, Inc. All rights reserved.
-
- This file is part of Hacq.
- Hacq is distributed under the 3-clause BSD license.
- See the LICENSE file for more details.
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
module Control.Monad.Quantum.PhaseShift.Binary.Kickback.Estimate (
module Control.Monad.Quantum.PhaseShift.Binary.Class,
PhaseKickbackEstimateT(..)) where
import Control.Applicative (Applicative)
import Control.Monad (when, unless)
import Control.Monad.Trans (MonadTrans(lift))
import Data.Functor ((<$>))
import qualified Data.Sequence as Seq
import Control.Monad.Memo.Class
import Control.Monad.Quantum.Class
import Control.Monad.Quantum.PhaseShift.Binary.Class
import Control.Monad.Quantum.ApproxSequence.Class (MonadApproxSequence)
import Control.Monad.Quantum.PhaseShift.Class (MonadPhaseShift)
import Control.Monad.Quantum.Adder (adder, subtractor)
import Control.Monad.Quantum.Counter.Class
import Util ((!))
newtype PhaseKickbackEstimateT c k m a = PhaseKickbackEstimateT {
-- |Run a `PhaseKickbackEstimateT`, assuming that the resource states have been prepared.
runPhaseKickbackEstimateT :: m a
} deriving (Functor, Applicative, Monad, MonadQuantumBase w, MonadToffoli w, MonadQuantum w, MonadPhaseShift w angle, MonadApproxSequence w, MonadQuantumCounter w c)
instance MonadTrans (PhaseKickbackEstimateT c k) where
lift = PhaseKickbackEstimateT
-- The following instance requires UndecidableInstances.
instance MonadMemo (Either k (Int, Integer)) m => MonadMemo k (PhaseKickbackEstimateT c k m) where
memoize k (PhaseKickbackEstimateT m) = PhaseKickbackEstimateT $
memoize (Left k) m
instance (MonadQuantum () m, MonadMemo (Either k (Int, Integer)) m) => MonadBinaryPhaseShift () (PhaseKickbackEstimateT c k m) where
applyGlobalBinaryPhase k _ | k <= 0 = return ()
applyGlobalBinaryPhase k m = PhaseKickbackEstimateT $ do
ctrls <- askCtrls
unless (null ctrls) $
memoize (Right (k, m)) $
if m > 0 then
let ml = integerToBinary m
low = take (k - 3) ml
high = take 3 $ drop (k - 3) ml in
parallels_ [
when (k >= 1 && length high >= 3 && high !! 2) $
negateGlobalPhase,
when (k >= 2 && length high >= 2 && high !! 1) $
rotateGlobalPhase90 False,
when (k >= 3 && length high >= 1 && high !! 0) $
rotateGlobalPhase45 False,
subtractor (Seq.replicate k ()) (BitConst <$> low) (BitConst False)]
else
let ml = integerToBinary (-m)
low = take (k - 3) ml
high = take 3 $ drop (k - 3) ml in
parallels_ [
when (k >= 1 && length high >= 3 && high !! 2) $
negateGlobalPhase,
when (k >= 2 && length high >= 2 && high !! 1) $
rotateGlobalPhase90 True,
when (k >= 3 && length high >= 1 && high !! 0) $
rotateGlobalPhase45 True,
adder (Seq.replicate k ()) (BitConst <$> low) (BitConst False)]
{-# INLINABLE applyGlobalBinaryPhase #-}
applyBinaryPhaseShift k m
| n <= 0 =
return ()
| n == 1 =
control (m ! 0) $
applyGlobalBinaryPhase k 1
| otherwise = compressCtrls 1 $
parallels_ [
when (k >= 1 && n >= k) $
applyZ (m ! (k - 1)),
when (k >= 2 && n >= k - 1) $
applyS (m ! (k - 2)) False,
when (k >= 3 && n >= k - 2) $
applyT (m ! (k - 3)) False,
when (k >= 4) $
subtractor (Seq.replicate k ()) (Seq.take (k - 3) m) (BitConst False)]
where
n = min k (Seq.length m)
{-# INLINABLE applyBinaryPhaseShift #-}
integerToBinary :: Integer -> [Bool]
integerToBinary 0 = []
integerToBinary m = odd m : integerToBinary (m `div` 2)
|
ti1024/hacq
|
src/Control/Monad/Quantum/PhaseShift/Binary/Kickback/Estimate.hs
|
bsd-3-clause
| 4,056
| 0
| 22
| 1,090
| 1,261
| 673
| 588
| 78
| 1
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
#if __GLASGOW_HASKELL__ >= 800
{-# OPTIONS_GHC -Wno-redundant-constraints #-}
#endif
-- | Execute commands within the properly configured Stack
-- environment.
module Stack.Exec where
import Stack.Prelude
import Stack.Types.Config
import System.Process.Log
import Data.Streaming.Process (ProcessExitedUnsuccessfully(..))
import System.Exit
import System.Process.Run (callProcess, callProcessObserveStdout, Cmd(..))
#ifdef WINDOWS
import System.Process.Read (EnvOverride)
#else
import qualified System.Process.PID1 as PID1
import System.Process.Read (EnvOverride, envHelper, preProcess)
#endif
-- | Default @EnvSettings@ which includes locals and GHC_PACKAGE_PATH
defaultEnvSettings :: EnvSettings
defaultEnvSettings = EnvSettings
{ esIncludeLocals = True
, esIncludeGhcPackagePath = True
, esStackExe = True
, esLocaleUtf8 = False
}
-- | Environment settings which do not embellish the environment
plainEnvSettings :: EnvSettings
plainEnvSettings = EnvSettings
{ esIncludeLocals = False
, esIncludeGhcPackagePath = False
, esStackExe = False
, esLocaleUtf8 = False
}
-- | Execute a process within the Stack configured environment.
--
-- Execution will not return, because either:
--
-- 1) On non-windows, execution is taken over by execv of the
-- sub-process. This allows signals to be propagated (#527)
--
-- 2) On windows, an 'ExitCode' exception will be thrown.
exec :: (MonadUnliftIO m, MonadLogger m)
=> EnvOverride -> String -> [String] -> m b
#ifdef WINDOWS
exec = execSpawn
#else
exec menv cmd0 args = do
cmd <- preProcess Nothing menv cmd0
withProcessTimeLog cmd args $
liftIO $ PID1.run cmd args (envHelper menv)
#endif
-- | Like 'exec', but does not use 'execv' on non-windows. This way, there
-- is a sub-process, which is helpful in some cases (#1306)
--
-- This function only exits by throwing 'ExitCode'.
execSpawn :: (MonadUnliftIO m, MonadLogger m)
=> EnvOverride -> String -> [String] -> m b
execSpawn menv cmd0 args = do
e <- withProcessTimeLog cmd0 args $
try (callProcess (Cmd Nothing cmd0 menv args))
liftIO $ case e of
Left (ProcessExitedUnsuccessfully _ ec) -> exitWith ec
Right () -> exitSuccess
execObserve :: (MonadUnliftIO m, MonadLogger m)
=> EnvOverride -> String -> [String] -> m String
execObserve menv cmd0 args = do
e <- withProcessTimeLog cmd0 args $
try (callProcessObserveStdout (Cmd Nothing cmd0 menv args))
case e of
Left (ProcessExitedUnsuccessfully _ ec) -> liftIO $ exitWith ec
Right s -> return s
|
MichielDerhaeg/stack
|
src/Stack/Exec.hs
|
bsd-3-clause
| 2,755
| 0
| 13
| 588
| 477
| 270
| 207
| 46
| 2
|
{-# LANGUAGE ScopedTypeVariables #-}
module Court.PluginManager
( pluginManager
) where
import Control.Concurrent
import Control.Exception
import Control.Monad
import Data.List
import System.Directory
import System.Exit
import System.FilePath
import System.IO
import System.Process
import Court.Job
import Court.Options
import Court.Plugin
import Court.Queue
import Court.Utils
pluginManager :: Options -> TVar Queue -> IO ()
pluginManager opts queueTVar = do
pluginMap <- loadPluginMapOrDie $ optPluginMapPath opts
basePath <- if isAbsolute (optDirectory opts)
then return $ optDirectory opts
else do
current <- getCurrentDirectory
return $ normalise $ current </> optDirectory opts
let pairs = pluginMapToPairs basePath pluginMap
runningPlugins <- mapM (uncurry spawnPlugin) pairs
consumePlugins queueTVar runningPlugins
loadPluginMapOrDie :: FilePath -> IO PluginMap
loadPluginMapOrDie path = do
contents <- readFile path
case reads contents of
(pluginMap,_):_ -> return pluginMap
_ -> hPutStrLn stderr ("Can't read plugin map at " ++ path) >> exitFailure
spawnPlugin :: FilePath -> Plugin -> IO RunningPlugin
spawnPlugin path plugin = do
hPutStrLn stderr $ "Spawning " ++ show plugin ++ " in " ++ path ++ " ..."
let args = pluginArguments plugin
(inR, inW) <- createPipeHandles
(outR, outW) <- createPipeHandles
processHandle <- runProcess
(pluginExecutable plugin) args (Just path) Nothing
(Just inR) (Just outW) Nothing
hClose inW
return RunningPlugin
{ runningPluginStdout = outR
, runningPluginProcess = processHandle
, runningPluginOrigin = (path, plugin)
}
consumePlugins :: TVar Queue -> [RunningPlugin] -> IO ()
consumePlugins queueTVar runningPlugins = do
runningPlugins' <- forM runningPlugins $ \runningPlugin -> do
let kill = terminateProcess $ runningPluginProcess runningPlugin
respawn = uncurry spawnPlugin $ runningPluginOrigin runningPlugin
handle (\(_ :: SomeException) -> kill >> respawn) $ do
let out = runningPluginStdout runningPlugin
checkReady <- hReady out
when checkReady $ do
line <- hGetLine out
let job = Job
{ jobProjectPath = fst $ runningPluginOrigin runningPlugin
, jobArguments = readTabSeparatedList line
}
hPutStrLn stderr $ "Job added in the queue: " ++ show job
addToQueue queueTVar job
return runningPlugin
threadDelay $ 1000 * 1000
consumePlugins queueTVar runningPlugins'
where
readTabSeparatedList :: String -> [String]
readTabSeparatedList = unfoldr $ \str ->
let (part, tabbedRest) = break (== '\t') str
arg = case reads part of
(arg',""):_ -> arg'
_ -> part
in case (str, tabbedRest) of
("",_) -> Nothing
(_,"") -> Just (arg, "")
(_,_:rest) -> Just (arg, rest)
|
thoferon/court
|
src/Court/PluginManager.hs
|
bsd-3-clause
| 2,981
| 0
| 24
| 734
| 876
| 437
| 439
| 76
| 4
|
module Physics.Bullet (module Exports) where
import Physics.Bullet.Types as Exports
import Physics.Bullet.DynamicsWorld as Exports
import Physics.Bullet.RigidBody as Exports
import Physics.Bullet.CollisionShape as Exports
import Physics.Bullet.SpringConstraint as Exports
import Physics.Bullet.PointToPointConstraint as Exports
import Physics.Bullet.GhostObject as Exports
import Physics.Bullet.CollisionObject as Exports
import Physics.Bullet.DebugDraw as Exports
|
lukexi/bullet-mini
|
src/Physics/Bullet.hs
|
bsd-3-clause
| 467
| 0
| 4
| 43
| 84
| 62
| 22
| 10
| 0
|
{-# LANGUAGE UnicodeSyntax #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Network.HsTorrent.BinaryStrict
-- Copyright : AUTHORS
-- License : BSD3
-- Maintainer : https://github.com/hstorrent
-- Stability : experimental
-- Portability : portable
--
-- This module has a single purpose, to expose 'BinaryS'.
module Network.HsTorrent.BinaryStrict where
import Data.Binary
import Data.ByteString
import qualified Data.ByteString.Lazy as BL
-- | This serves merely as a convenience class, providing wrappers to
-- work over strict 'ByteString's rather than lazy ones.
class Binary a ⇒ BinaryS a where
-- | Just like 'encode' but calls 'BL.toStrict' on the result.
encodeStrict ∷ a → ByteString
encodeStrict = BL.toStrict . encode
-- | Just like 'decode' but calls 'BL.fromStrict' first.
decodeStrict ∷ ByteString → a
decodeStrict = decode . BL.fromStrict
|
hstorrent/hstorrent
|
src/Network/HsTorrent/BinaryStrict.hs
|
bsd-3-clause
| 931
| 0
| 8
| 182
| 97
| 62
| 35
| 11
| 0
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
module Mapnik.Bindings.Expression (
parse
, unsafeNew
, unsafeNewMaybe
, toText
) where
import Mapnik.Bindings.Types
import Mapnik.Bindings.Util
import Control.Exception (try)
import Data.Text (Text)
import Data.Text.Encoding (encodeUtf8)
import Foreign.ForeignPtr (FinalizerPtr)
import Foreign.Ptr (Ptr)
import qualified Mapnik.Bindings.Cpp as C
import System.IO.Unsafe (unsafePerformIO)
C.context mapnikCtx
C.include "<string>"
C.include "<mapnik/expression.hpp>"
C.include "<mapnik/expression_string.hpp>"
C.include "<mapnik/expression_evaluator.hpp>"
C.include "util.hpp"
C.using "namespace mapnik"
-- * Expression
foreign import ccall "&hs_mapnik_destroy_Expression" destroyExpression :: FinalizerPtr Expression
unsafeNew :: (Ptr (Ptr Expression) -> IO ()) -> IO Expression
unsafeNew = mkUnsafeNew Expression destroyExpression
unsafeNewMaybe :: (Ptr (Ptr Expression) -> IO ()) -> IO (Maybe Expression)
unsafeNewMaybe = mkUnsafeNewMaybe Expression destroyExpression
parse :: Text -> Either String Expression
parse (encodeUtf8 -> s) =
unsafePerformIO $ fmap showExc $ try $ unsafeNew $ \p ->
[C.catchBlock|*$(expression_ptr **p) = new expression_ptr(parse_expression(std::string($bs-ptr:s, $bs-len:s)));|]
where
showExc = either (Left . show @MapnikError) Right
toText :: Expression -> Text
toText expr = unsafePerformIO $ newText "Expression.toText" $ \(p,len) ->
[C.block|void {
std::string s = to_expression_string(**$fptr-ptr:(expression_ptr *expr));
mallocedString(s, $(char **p), $(int *len));
}|]
|
albertov/hs-mapnik
|
bindings/src/Mapnik/Bindings/Expression.hs
|
bsd-3-clause
| 1,786
| 0
| 11
| 300
| 401
| 217
| 184
| 39
| 1
|
import Math.Graphs
import Math.Scythe
import Data.ByteString.Char8
main :: IO ()
main = putStrLn (
"Hi, and welcome to this mostly pointless example.\n" ++
"how many samples would you like to use?"
)
>> getLine >>= (\ s ->
putStrLn "how many dimensions should be sampled?"
>> getLine
>>= (randomDT (read s) . read ))
>>= (\ t ->
putStrLn "the triangulation has the following list of top-dimensional simplices"
>> (print . length) t
>> putStrLn "the resulting complex has"
>> (return . complex) t)
>>= (\ x ->
(putStrLn $ (show . length . vertices) x ++ " cells, and")
>> (putStrLn $ (show . length . edges) x ++ " relations"))
|
crvs/scythe
|
examples/delaunay.hs
|
bsd-3-clause
| 785
| 6
| 14
| 270
| 211
| 108
| 103
| 19
| 1
|
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.ST.Lazy
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : non-portable (requires universal quantification for runST)
--
-- This module presents an identical interface to "Control.Monad.ST",
-- but the underlying implementation of the state thread is /lazy/ (in
-- the sense that (@_|_ >> a@ is not necessarily equal to @_|_@).
--
-----------------------------------------------------------------------------
module Control.Monad.ST.Lazy (
-- * The 'ST' monad
ST,
runST,
fixST,
-- * Converting between strict and lazy 'ST'
strictToLazyST, lazyToStrictST,
-- * Converting 'ST' To 'IO'
RealWorld,
stToIO,
-- * Unsafe operations
unsafeInterleaveST,
unsafeIOToST
) where
import Prelude
import Control.Monad.Fix
import Control.Monad.ST (RealWorld)
import qualified Control.Monad.ST as ST
import Hugs.LazyST
instance MonadFix (ST s) where
mfix = fixST
-- ---------------------------------------------------------------------------
-- Strict <--> Lazy
unsafeIOToST :: IO a -> ST s a
unsafeIOToST = strictToLazyST . ST.unsafeIOToST
-- | A monad transformer embedding lazy state transformers in the 'IO'
-- monad. The 'RealWorld' parameter indicates that the internal state
-- used by the 'ST' computation is a special one supplied by the 'IO'
-- monad, and thus distinct from those used by invocations of 'runST'.
stToIO :: ST RealWorld a -> IO a
stToIO = ST.stToIO . lazyToStrictST
|
OS2World/DEV-UTIL-HUGS
|
libraries/Control/Monad/ST/Lazy.hs
|
bsd-3-clause
| 1,688
| 16
| 7
| 277
| 187
| 119
| 68
| 20
| 1
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Yesod.Auth.DeskCom
( YesodDeskCom(..)
, deskComCreateCreds
, DeskComCredentials
, DeskComUser(..)
, DeskComUserId(..)
, DeskComCustomField
, DeskCom
, initDeskCom
, deskComLoginRoute
, deskComMaybeLoginRoute
) where
import Control.Applicative ((<$>))
import Data.Default (Default(..))
import Data.Monoid ((<>))
import Data.Text (Text)
import Network.HTTP.Types (renderSimpleQuery)
import Yesod.Auth
import Yesod.Core
import qualified Crypto.Cipher.AES as AES
import qualified Crypto.Hash.SHA1 as SHA1
import qualified Crypto.Padding as Padding
import qualified "crypto-random" Crypto.Random
import Crypto.Hash (hmac, SHA1, Digest, hmacGetDigest)
import Data.Byteable (toBytes)
import qualified Data.Aeson as A
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Base64 as B64
import qualified Data.ByteString.Base64.URL as B64URL
import qualified Data.IORef as I
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.Time as TI
import Yesod.Auth.DeskCom.Data
-- | Type class that you need to implement in order to support
-- Desk.com remote authentication.
--
-- /Minimal complete definition:/ everything except for 'deskComTokenTimeout'.
class YesodAuthPersist master => YesodDeskCom master where
-- | The credentials needed to use Multipass. Use
-- 'deskComCreateCreds'. We recommend caching the resulting
-- 'DeskComCredentials' value on your foundation data type
-- since creating it is an expensive operation.
deskComCredentials :: HandlerT master IO DeskComCredentials
-- | Gather information that should be given to Desk.com about
-- an user. Please see 'DeskComUser' for more information
-- about what these fields mean.
--
-- Simple example:
--
-- @
-- deskComUserInfo uid = do
-- user <- runDB $ get uid
-- return 'def' { 'duName' = userName user
-- , 'duEmail' = userEmail user }
-- @
--
-- Advanced example:
--
-- @
-- deskComUserInfo uid = do
-- render <- 'getUrlRender'
-- runDB $ do
-- Just user <- get uid
-- Just org <- get (userOrganization user)
-- return 'def' { 'duName' = userName user
-- , 'duEmail' = userEmail user
-- , 'duOrganization' = Just (organizationName org)
-- , 'duRemotePhotoURL' = Just (render $ UserPhotoR uid)
-- }
-- @
--
-- /Note:/ although I don't recomend this and I don't see any
-- reason why you would do it, it /is/ possible to use
-- 'maybeAuth' instead of 'requireAuth' and login on Desk.com
-- with some sort of guest user should the user not be logged
-- in.
deskComUserInfo :: AuthId master -> HandlerT master IO DeskComUser
-- | Each time we login an user on Desk.com, we create a token.
-- This function defines how much time the token should be
-- valid before expiring. Should be greater than 0. Defaults
-- to 5 minutes.
deskComTokenTimeout :: master -> TI.NominalDiffTime
deskComTokenTimeout _ = 300 -- seconds
instance YesodDeskCom master => YesodSubDispatch DeskCom (HandlerT master IO) where
yesodSubDispatch = $(mkYesodSubDispatch resourcesDeskCom)
-- | Create the credentials data type used by this library. This
-- function is relatively expensive (uses SHA1 and AES), so
-- you'll probably want to cache its result.
deskComCreateCreds ::
T.Text -- ^ The name of your site (e.g., @\"foo\"@ if your
-- site is at @http://foo.desk.com/@).
-> T.Text -- ^ The domain of your site
-- (e.g. @\"foo.desk.com\"@).
-> T.Text -- ^ The Multipass API key, a shared secret between
-- Desk.com and your site.
-> DeskComCredentials
deskComCreateCreds site domain apiKey = DeskComCredentials site domain aesKey hmacKey
where
-- Yes, I know, Desk.com's crypto is messy.
aesKey = AES.initAES . B.take 16 . SHA1.hash . TE.encodeUtf8 $ apiKey <> site
hmacKey = TE.encodeUtf8 apiKey
-- | Credentials used to access your Desk.com's Multipass.
data DeskComCredentials =
DeskComCredentials
{ dccSite :: !T.Text
, dccDomain :: !T.Text
, dccAesKey :: !AES.AES
, dccHmacKey :: !B.ByteString -- HMAC.MacKey ?????? SHA1
}
-- | Information about a user that is given to 'DeskCom'. Please
-- see Desk.com's documentation
-- (<http://dev.desk.com/docs/portal/multipass>) in order to see
-- more details of how theses fields are interpreted.
--
-- Only 'duName' and 'duEmail' are required. We suggest using
-- 'def'.
data DeskComUser =
DeskComUser
{ duName :: Text
-- ^ User name, at least two characters. (required)
, duEmail :: Text
-- ^ E-mail address. (required)
, duUserId :: DeskComUserId
-- ^ Desk.com expects an string to be used as the ID of the
-- user on their system. Defaults to 'UseYesodAuthId'.
, duCustomFields :: [DeskComCustomField]
-- ^ Custom fields to be set.
, duRedirectTo :: Maybe Text
-- ^ When @Just url@, forces the user to be redirected to
-- @url@ after being logged in. Otherwise, the user is
-- redirected either to the page they were trying to view (if
-- any) or to your portal page at Desk.com.
} deriving (Eq, Ord, Show, Read)
-- | Fields 'duName' and 'duEmail' are required, so 'def' will be
-- 'undefined' for them.
instance Default DeskComUser where
def = DeskComUser
{ duName = req "duName"
, duEmail = req "duEmail"
, duUserId = def
, duCustomFields = []
, duRedirectTo = Nothing
}
where req fi = error $ "DeskComUser's " ++ fi ++ " is a required field."
-- | Which external ID should be given to Desk.com.
data DeskComUserId =
UseYesodAuthId
-- ^ Use the user ID from @persistent@\'s database. This is
-- the recommended and default value.
| Explicit Text
-- ^ Use this given value.
deriving (Eq, Ord, Show, Read)
-- | Default is 'UseYesodAuthId'.
instance Default DeskComUserId where
def = UseYesodAuthId
-- | The value of a custom customer field as @(key, value)@.
-- Note that you have prefix your @key@ with @\"custom_\"@.
type DeskComCustomField = (Text, Text)
----------------------------------------------------------------------
-- | Redirect the user to Desk.com such that they're already
-- logged in when they arrive. For example, you may use
-- @deskComLoginRoute@ as the login URL on Multipass config.
deskComLoginRoute :: Route DeskCom
deskComLoginRoute = DeskComLoginR
-- | If the user is logged in, redirect them to Desk.com such
-- that they're already logged in when they arrive (same as
-- 'deskComLoginRoute'). Otherwise, redirect them to Desk.com
-- without asking for credentials. For example, you may use
-- @deskComMaybeLoginRoute@ when the user clicks on a \"Support\"
-- item on a menu.
deskComMaybeLoginRoute :: Route DeskCom
deskComMaybeLoginRoute = DeskComMaybeLoginR
-- | Route used by the Desk.com remote authentication. Works
-- both when Desk.com call us and when we call them. Forces user
-- to be logged in.
getDeskComLoginR :: YesodDeskCom master
=> HandlerT DeskCom (HandlerT master IO) ()
getDeskComLoginR = lift requireAuthId >>= redirectToMultipass
-- | Same as 'getDeskComLoginR' if the user is logged in,
-- otherwise redirect to the Desk.com portal without asking for
-- credentials.
getDeskComMaybeLoginR :: YesodDeskCom master
=> HandlerT DeskCom (HandlerT master IO) ()
getDeskComMaybeLoginR = lift maybeAuthId >>= maybe redirectToPortal redirectToMultipass
-- | Redirect the user to the main Desk.com portal.
redirectToPortal :: YesodDeskCom master => HandlerT DeskCom (HandlerT master IO) ()
redirectToPortal = do
DeskComCredentials {..} <- lift deskComCredentials
redirect $ T.concat [ "http://", dccDomain, "/" ]
-- | Redirect the user to the multipass login.
redirectToMultipass :: YesodDeskCom master
=> AuthId master
-> HandlerT DeskCom (HandlerT master IO) ()
redirectToMultipass uid = do
-- Get generic info.
y <- lift getYesod
DeskComCredentials {..} <- lift deskComCredentials
-- Get the expires timestamp.
expires <- TI.addUTCTime (deskComTokenTimeout y) <$> liftIO TI.getCurrentTime
-- Get information about the currently logged user.
DeskComUser {..} <- lift (deskComUserInfo uid)
userId <- case duUserId of
UseYesodAuthId -> toPathPiece <$> lift requireAuthId
Explicit x -> return x
-- Generate an IV.
iv <- deskComRandomIV
-- Create Multipass token.
let toStrict = B.concat . BL.toChunks
deskComEncode
= fst . B.spanEnd (== 61) -- remove trailing '=' per Desk.com
. B64URL.encode -- base64url encoding
encrypt
= deskComEncode -- encode as modified base64url
. AES.encryptCBC dccAesKey iv -- encrypt with AES128-CBC
. (iv <>) -- prepend the IV
. Padding.padPKCS5 16 -- PKCS#5 padding
. toStrict . A.encode . A.object -- encode as JSON
sign
= B64.encode -- encode as normal base64 (why??? =[)
. (toBytes :: Digest SHA1 -> B.ByteString)
. hmacGetDigest
. hmac dccHmacKey -- sign using HMAC-SHA1
multipass = encrypt $
"uid" A..= userId :
"expires" A..= expires :
"customer_email" A..= duEmail :
"customer_name" A..= duName :
[ "to" A..= to | Just to <- return duRedirectTo ] ++
[ ("customer_" <> k) A..= v | (k, v) <- duCustomFields ]
signature = sign multipass
query = [("multipass", multipass), ("signature", signature)]
-- Redirect to Desk.com
redirect $ T.concat [ "http://"
, dccDomain
, "/customer/authentication/multipass/callback?"
, TE.decodeUtf8 (renderSimpleQuery False query)
]
-- | Randomly generate an IV.
deskComRandomIV :: HandlerT DeskCom (HandlerT master IO) B.ByteString
deskComRandomIV = do
var <- deskComCprngVar <$> getYesod
liftIO $ I.atomicModifyIORef var $
\g -> let (bs, g') = Crypto.Random.cprgGenerate 16 g
in (g', g' `seq` bs)
|
prowdsponsor/yesod-auth-deskcom
|
src/Yesod/Auth/DeskCom.hs
|
bsd-3-clause
| 10,559
| 0
| 19
| 2,647
| 1,563
| 909
| 654
| -1
| -1
|
{-# LANGUAGE TypeFamilies, FlexibleContexts, GeneralizedNewtypeDeriving, FlexibleInstances, NamedFieldPuns, RecordWildCards #-}
{-# LANGUAGE MultiParamTypeClasses, CPP, UnboxedTuples, MagicHash #-}
module Data.TrieMap.ReverseMap () where
import Control.Monad.Ends
import qualified Data.Monoid as M
import Data.TrieMap.TrieKey
import Data.TrieMap.Modifiers
import Data.TrieMap.ReverseMap.Dual
import Prelude hiding (foldr, foldl, foldr1, foldl1, lookup)
import GHC.Exts
#define INSTANCE(cl) (cl (TrieMap k)) => cl (TrieMap (Rev k))
instance INSTANCE(Functor) where
fmap f (RevMap m) = RevMap (f <$> m)
instance INSTANCE(Foldable) where
foldMap f (RevMap m) = M.getDual (foldMap (M.Dual . f) m)
foldr f z (RevMap m) = foldl (flip f) z m
foldl f z (RevMap m) = foldr (flip f) z m
instance INSTANCE(Traversable) where
traverse f (RevMap m) = RevMap <$> runDual (traverse (Dual . f) m)
instance INSTANCE(Subset) where
RevMap m1 <=? RevMap m2 = m1 <=? m2
instance TrieKey k => Buildable (TrieMap (Rev k)) (Rev k) where
type UStack (TrieMap (Rev k)) = UMStack k
uFold = fmap RevMap . mapFoldlKeys getRev . uFold
type AStack (TrieMap (Rev k)) = RevFold (AMStack k) k
aFold = fmap RevMap . mapFoldlKeys getRev . reverseFold . aFold
type DAStack (TrieMap (Rev k)) = RevFold (DAMStack k) k
daFold = RevMap <$> mapFoldlKeys getRev (reverseFold daFold)
#define SETOP(op) op f (RevMap m1) (RevMap m2) = RevMap (op f m1 m2)
instance INSTANCE(SetOp) where
SETOP(union)
SETOP(diff)
SETOP(isect)
instance INSTANCE(Project) where
mapMaybe f (RevMap m) = RevMap $ mapMaybe f m
mapEither f (RevMap m) = both RevMap (mapEither f) m
newtype instance TrieMap (Rev k) a = RevMap (TrieMap k a)
newtype instance Zipper (TrieMap (Rev k)) a = RHole (Hole k a)
instance INSTANCE(Zippable) where
empty = RevMap empty
clear (RHole hole) = RevMap (clear hole)
assign a (RHole hole) = RevMap (assign a hole)
instance INSTANCE(Alternatable) where
alternate (RevMap m) = do
(a, hole) <- runDualPlus (alternate m)
return (a, RHole hole)
firstHole (RevMap m) = First (fmap RHole <$> getLast (lastHole m))
lastHole (RevMap m) = Last (fmap RHole <$> getFirst (firstHole m))
instance TrieKey k => Searchable (TrieMap (Rev k)) (Rev k) where
search (Rev k) (RevMap m) = mapHole RHole $ search k m
singleZip (Rev k) = RHole (singleZip k)
singleton (Rev k) a = RevMap (singleton k a)
lookup (Rev k) (RevMap m) = lookup k m
insertWith f (Rev k) a (RevMap m) = RevMap (insertWith f k a m)
alter f (Rev k) (RevMap m) = RevMap (alter f k m)
instance Splittable (TrieMap k) => Splittable (TrieMap (Rev k)) where
before (RHole hole) = RevMap (after hole)
beforeWith a (RHole hole) = RevMap (afterWith a hole)
after (RHole hole) = RevMap (before hole)
afterWith a (RHole hole) = RevMap (beforeWith a hole)
instance (TrieKey k, Indexable (TrieMap k)) => Indexable (TrieMap (Rev k)) where
index i (RevMap m) = case index (revIndex i m) m of
(# i', a, hole #) -> (# revIndex i' a, a, RHole hole #)
where revIndex :: Sized a => Int# -> a -> Int#
revIndex i# a = getSize# a -# 1# -# i#
-- | @'TrieMap' ('Rev' k) a@ is a wrapper around a @'TrieMap' k a@ that reverses the order of the operations.
instance TrieKey k => TrieKey (Rev k) where
sizeM (RevMap m) = sizeM m
getSimpleM (RevMap m) = getSimpleM m
unifierM (Rev k') (Rev k) a = RHole <$> unifierM k' k a
unifyM (Rev k1) a1 (Rev k2) a2 = RevMap <$> unifyM k1 a1 k2 a2
{-# INLINE reverseFold #-}
reverseFold :: FromList z k a -> FromList (RevFold z k) k a
reverseFold Foldl{snoc = snoc0, begin = begin0, zero, done = done0}
= Foldl {..} where
snoc g k a = RevFold $ \ m -> case m of
Nothing -> runRevFold g (Just $ begin0 k a)
Just m -> runRevFold g (Just $ snoc0 m k a)
begin = snoc (RevFold $ maybe zero done0)
done g = runRevFold g Nothing
newtype RevFold z k a = RevFold {runRevFold :: Maybe (z a) -> TrieMap k a}
|
lowasser/TrieMap
|
Data/TrieMap/ReverseMap.hs
|
bsd-3-clause
| 3,955
| 3
| 15
| 804
| 1,693
| 855
| 838
| -1
| -1
|
{-# LANGUAGE TypeOperators #-}
module Main where
import Control.Arrow (second)
import Data.OI hiding (openFile)
import System.IO (IOMode (..), Handle)
import qualified System.IO as IO
import Prelude hiding (readFile, writeFile)
main :: IO ()
main = runInteraction pmain
{- -
pmain :: ((([String], Either (IOResult (Resource String)) b),[IOResult (Resource String)]),IOResult (Resource ())) :-> ()
pmain = inputs |/| outputs
inputs :: (([String], Either (IOResult (Resource String)) b), [IOResult (Resource String)]) :-> [IOResult (Resource String)]
inputs = args |/| choiceOIOn (const $ fileList "files") const null |/| zipWithOI inFileResource
fileList :: FilePath -> (IOResult (Resource String)) :-> [String]
fileList f = mapR id . inFileResource f
outputs :: [IOResult (Resource String)] -> IOResult (Resource ()) :-> ()
outputs = (closeR .) . outFileResource "output.txt" . concatMap (mapR textproc)
-- -}
{- -}
pmain0 = useUpR . inFileResource "input.txt"
|/| maybe (const (Failure "fail in inputing")) (outFileResource "output.txt")
|/| const . closeR
-- -}
{- -}
textproc :: String -> String
textproc = id
readFile :: FilePath -> (Handle, String) :-> String
readFile f = openFile f ReadMode |/| hGetContents
writeFile :: FilePath -> String -> (Handle, ()) :-> ()
writeFile f cs = openFile f WriteMode |/| flip hPutStr cs
openFile :: FilePath -> IOMode -> Handle :-> Handle
openFile = (iooi .) . IO.openFile
hGetContents :: Handle -> String :-> String
hGetContents = iooi . IO.hGetContents
hPutStr :: Handle -> String -> () :-> ()
hPutStr = (iooi .) . IO.hPutStr
pmain :: (([String],Either ((Handle, String), [(Handle, String)]) [(Handle, String)]), (Handle, ())) :-> ()
pmain = args |/| choiceOIOn (const $ lines . readFile "files" |/| zipWithOI readFile)
(zipWithOI readFile)
null
|/| writeFile "output.txt" . concatMap textproc
-- -}
|
nobsun/oi
|
sample/cats.hs
|
bsd-3-clause
| 1,960
| 0
| 12
| 395
| 452
| 253
| 199
| -1
| -1
|
--
-- >>> Hub.Discover <<<
--
-- 'discover' works out the default hub.
--
-- (c) 2011-2012 Chris Dornan
module Hub.Discover
( discover
) where
import qualified Control.Exception as E
import System.Directory
import System.FilePath
import System.Environment
import Hub.System
import Hub.Oops
import Hub.Hub
import Hub.Parse
import Hub.Directory
discover :: Maybe HubName -> IO Hub
discover Nothing = which_hub >>= read_hub
discover (Just hn) | hn=="^" = discover Nothing
| otherwise = read_hub (ClHS,hn)
read_hub :: (HubSource,HubName) -> IO Hub
read_hub (hs,hn) =
do hk <- checkHubName [minBound..maxBound] hn
hubExists hn
hf <- case isHubName hn==Just GlbHK of
True -> return $ globalHubPath hn
False -> userHubPath hn
dy <- defaultDirectoryPath
parse hs dy hn hf hk
which_hub :: IO (HubSource,HubName)
which_hub =
do ei <- tryIO $ getEnv "HUB"
(hs,hn) <- case ei of
Left _ -> dir_which_hub
Right s -> env_which_hub s
_ <- checkHubName [UsrHK,GlbHK] hn
return (hs,hn)
env_which_hub :: String -> IO (HubSource,HubName)
env_which_hub str =
case str of
"--dir" -> dir_which_hub
"--global" -> (,) DsHS `fmap` defaultGlobalHubName
_ -> return $ (EvHS,trim str)
dir_which_hub :: IO (HubSource,HubName)
dir_which_hub =
do ds <- (reverse.splitDirectories) `fmap` getCurrentDirectory
w_h ds
where
w_h [] = (,) DsHS `fmap` defaultGlobalHubName
w_h (d:ds) = catchIO (here (d:ds)) (\_ -> w_h ds)
here r_ds = ((,) DrHS . trim) `fmap`
readAFile (joinPath $ reverse $ ".hub":r_ds)
tryIO :: IO a -> IO (Either IOError a)
tryIO = E.try
catchIO :: IO a -> (IOError->IO a) -> IO a
catchIO = E.catch
|
Lainepress/hub-src
|
Hub/Discover.hs
|
bsd-3-clause
| 2,008
| 0
| 12
| 675
| 652
| 338
| 314
| 50
| 3
|
module Data.Baduk.Game where
import Data.Time.Clock
import Data.Time.Format
import Data.Text as T
data RankType = Dan | Kyu | Pro
deriving (Show)
data Rank = Rank Int RankType deriving (Show)
data Player = Player T.Text Rank deriving (Show)
data Color = Black | White deriving (Show)
data Margin = Time
| Resignation
| Points Double
deriving (Show)
data Result = Unfinished
| Draw
| Win Color Margin
deriving (Show)
data Move = Stone Color Int Int
| Pass Color
deriving (Show)
data Game = Game { size :: Int
, black :: Player
, white :: Player
, handicap :: Int
, komi :: Double
, time :: UTCTime
, moves :: [Move]
, result :: Result
} deriving (Show)
|
frodwith/baduk-formats
|
src/Data/Baduk/Game.hs
|
bsd-3-clause
| 952
| 0
| 9
| 419
| 239
| 145
| 94
| 29
| 0
|
module GState.Client (
KeysState(..),
ClientState(..),
newClientState
) where
import Control.Concurrent.STM (TChan, TVar, newTChanIO, newTVarIO)
import Data.Time.Clock (UTCTime(..), getCurrentTime)
import GMessages.Client (WorldMessage, PingMessage, SettingsMessage, WorldInputMessage)
import qualified GMessages.Network.ClientServer as CS
import GCommon.Objects.Objects (World, newWorld)
import GCommon.Types.Generic (ClientKey, ConnHandle)
import GOpenGL.Meshes (Mesh)
data KeysState = KeysState {
up :: Bool,
left :: Bool,
down :: Bool,
right :: Bool,
space :: Bool
}
newKeysState :: KeysState
newKeysState = KeysState False False False False False
data ClientState = ClientState {
serverHandle :: ConnHandle,
worldUpdateChan :: TChan WorldMessage,
worldInputChan :: TChan WorldInputMessage,
serverOutChan :: TChan CS.Message,
settingsSvcChan :: TChan SettingsMessage,
pingSvcChan :: TChan PingMessage,
world :: World,
playerKey :: ClientKey,
keysState :: KeysState,
shouldQuit :: TVar Bool,
menuIsOn :: TVar Bool,
lastTimeShot :: TVar UTCTime
}
newClientState :: ConnHandle -> ClientKey -> IO ClientState
newClientState connHandle key = do
worldUpdateChan' <- newTChanIO
worldInputChan' <- newTChanIO
serverOutChan' <- newTChanIO
shouldQuit' <- newTVarIO False
menuIsOn' <- newTVarIO False
settingsSvcChan' <- newTChanIO
pingSvcChan' <- newTChanIO
time <- getCurrentTime
lastTimeShot' <- newTVarIO time
return ClientState {
serverHandle = connHandle,
worldUpdateChan = worldUpdateChan',
worldInputChan = worldInputChan',
serverOutChan = serverOutChan',
settingsSvcChan = settingsSvcChan',
pingSvcChan = pingSvcChan',
world = newWorld,
playerKey = key,
keysState = newKeysState,
shouldQuit = shouldQuit',
menuIsOn = menuIsOn',
lastTimeShot = lastTimeShot'
}
|
cernat-catalin/haskellGame
|
src/GState/Client.hs
|
bsd-3-clause
| 2,081
| 0
| 10
| 525
| 474
| 277
| 197
| 56
| 1
|
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Distance.CA.Rules
( rules ) where
import Data.String
import Prelude
import Duckling.Dimensions.Types
import Duckling.Distance.Helpers
import qualified Duckling.Distance.Types as TDistance
import Duckling.Types
ruleLatentDistKm :: Rule
ruleLatentDistKm = Rule
{ name = "<latent dist> km"
, pattern =
[ dimension Distance
, regex "(k|qu)(il(o|ò|ó))?m?(etre)?s?"
]
, prod = \tokens -> case tokens of
(Token Distance dd:_) ->
Just $ Token Distance $ withUnit TDistance.Kilometre dd
_ -> Nothing
}
ruleDistMeters :: Rule
ruleDistMeters = Rule
{ name = "<dist> meters"
, pattern =
[ dimension Distance
, regex "m(etres?)?"
]
, prod = \tokens -> case tokens of
(Token Distance dd:_) ->
Just $ Token Distance $ withUnit TDistance.Metre dd
_ -> Nothing
}
ruleDistCentimeters :: Rule
ruleDistCentimeters = Rule
{ name = "<dist> centimeters"
, pattern =
[ dimension Distance
, regex "(cm|cent(í|i)m(etres?))"
]
, prod = \tokens -> case tokens of
(Token Distance dd:_) ->
Just $ Token Distance $ withUnit TDistance.Centimetre dd
_ -> Nothing
}
ruleDistMiles :: Rule
ruleDistMiles = Rule
{ name = "<dist> miles"
, pattern =
[ dimension Distance
, regex "milles?"
]
, prod = \tokens -> case tokens of
(Token Distance dd:_) ->
Just $ Token Distance $ withUnit TDistance.Mile dd
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleDistCentimeters
, ruleDistMeters
, ruleDistMiles
, ruleLatentDistKm
]
|
facebookincubator/duckling
|
Duckling/Distance/CA/Rules.hs
|
bsd-3-clause
| 1,842
| 0
| 13
| 441
| 451
| 255
| 196
| 56
| 2
|
-- |
-- Module : Network.HTTP.Signature
-- Copyright : Alain O'Dea 2014
-- License : BSD3
--
-- Maintainer : alain.odea@gmail.com
-- Stability : experimental
-- Portability : unknown
--
-- Implementation of Joyent's HTTP Signature Scheme
-- http://tools.ietf.org/html/draft-cavage-http-signatures-00
module Network.HTTP.Signature
(
) where
sign :: KeyID -> Algorithm -> Headers -> Authorization
sign keyId algorithm headers = undefined
newtype KeyId = String
newtype Algorithm = String
type Headers = [Header]
newtype Header = (String, String)
|
AlainODea-haskell/http-signature
|
Network/HTTP/Signature.hs
|
bsd-3-clause
| 570
| 1
| 10
| 102
| 77
| 50
| 27
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
import Control.Concurrent (forkIO)
import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)
import Crypto.Hash.MD5 (hash)
import Data.Binary.Get (runGet, getWord64le)
import Data.ByteString (ByteString)
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Data.List (sortBy)
import Data.IntMap.Strict (fromList, elems)
import Data.Word (Word8, Word64)
import GHC.IO.Handle (hClose)
import System.Process (createProcess, CreateProcess(std_out), shell
, StdStream(CreatePipe), rawSystem
, interruptProcessGroupOf)
import System.Exit (ExitCode(ExitSuccess))
import Test.HUnit
target1 :: [[Word8]]
target1 = [
[60, 53, 84, 138, 217, 94, 88, 23, 39, 242, 219, 35, 12, 157, 165, 181, 255, 143, 83, 247, 162, 16, 31, 209, 190,
171, 115, 65, 38, 41, 21, 245, 236, 46, 121, 62, 166, 233, 44, 154, 153, 145, 230, 49, 128, 216, 173, 29, 241, 119,
64, 229, 194, 103, 131, 110, 26, 197, 218, 59, 204, 56, 27, 34, 141, 221, 149, 239, 192, 195, 24, 155, 170, 183, 11
, 254, 213, 37, 137, 226, 75, 203, 55, 19, 72, 248, 22, 129, 33, 175, 178, 10, 198, 71, 77, 36, 113, 167, 48, 2,
117, 140, 142, 66, 199, 232, 243, 32, 123, 54, 51, 82, 57, 177, 87, 251, 150, 196, 133, 5, 253, 130, 8, 184, 14,
152, 231, 3, 186, 159, 76, 89, 228, 205, 156, 96, 163, 146, 18, 91, 132, 85, 80, 109, 172, 176, 105, 13, 50, 235,
127, 0, 189, 95, 98, 136, 250, 200, 108, 179, 211, 214, 106, 168, 78, 79, 74, 210, 30, 73, 201, 151, 208, 114, 101,
174, 92, 52, 120, 240, 15, 169, 220, 182, 81, 224, 43, 185, 40, 99, 180, 17, 212, 158, 42, 90, 9, 191, 45, 6, 25, 4
, 222, 67, 126, 1, 116, 124, 206, 69, 61, 7, 68, 97, 202, 63, 244, 20, 28, 58, 93, 134, 104, 144, 227, 147, 102,
118, 135, 148, 47, 238, 86, 112, 122, 70, 107, 215, 100, 139, 223, 225, 164, 237, 111, 125, 207, 160, 187, 246, 234
, 161, 188, 193, 249, 252],
[151, 205, 99, 127, 201, 119, 199, 211, 122, 196, 91, 74, 12, 147, 124, 180, 21, 191, 138, 83, 217, 30, 86, 7, 70,
200, 56, 62, 218, 47, 168, 22, 107, 88, 63, 11, 95, 77, 28, 8, 188, 29, 194, 186, 38, 198, 33, 230, 98, 43, 148,
110, 177, 1, 109, 82, 61, 112, 219, 59, 0, 210, 35, 215, 50, 27, 103, 203, 212, 209, 235, 93, 84, 169, 166, 80, 130
, 94, 164, 165, 142, 184, 111, 18, 2, 141, 232, 114, 6, 131, 195, 139, 176, 220, 5, 153, 135, 213, 154, 189, 238
, 174, 226, 53, 222, 146, 162, 236, 158, 143, 55, 244, 233, 96, 173, 26, 206, 100, 227, 49, 178, 34, 234, 108,
207, 245, 204, 150, 44, 87, 121, 54, 140, 118, 221, 228, 155, 78, 3, 239, 101, 64, 102, 17, 223, 41, 137, 225, 229,
66, 116, 171, 125, 40, 39, 71, 134, 13, 193, 129, 247, 251, 20, 136, 242, 14, 36, 97, 163, 181, 72, 25, 144, 46,
175, 89, 145, 113, 90, 159, 190, 15, 183, 73, 123, 187, 128, 248, 252, 152, 24, 197, 68, 253, 52, 69, 117, 57, 92,
104, 157, 170, 214, 81, 60, 133, 208, 246, 172, 23, 167, 160, 192, 76, 161, 237, 45, 4, 58, 10, 182, 65, 202, 240,
185, 241, 79, 224, 132, 51, 42, 126, 105, 37, 250, 149, 32, 243, 231, 67, 179, 48, 9, 106, 216, 31, 249, 19, 85,
254, 156, 115, 255, 120, 75, 16]]
target2 :: [[Word8]]
target2 = [
[124, 30, 170, 247, 27, 127, 224, 59, 13, 22, 196, 76, 72, 154, 32, 209, 4, 2, 131, 62, 101, 51, 230, 9, 166, 11, 99
, 80, 208, 112, 36, 248, 81, 102, 130, 88, 218, 38, 168, 15, 241, 228, 167, 117, 158, 41, 10, 180, 194, 50, 204,
243, 246, 251, 29, 198, 219, 210, 195, 21, 54, 91, 203, 221, 70, 57, 183, 17, 147, 49, 133, 65, 77, 55, 202, 122,
162, 169, 188, 200, 190, 125, 63, 244, 96, 31, 107, 106, 74, 143, 116, 148, 78, 46, 1, 137, 150, 110, 181, 56, 95,
139, 58, 3, 231, 66, 165, 142, 242, 43, 192, 157, 89, 175, 109, 220, 128, 0, 178, 42, 255, 20, 214, 185, 83, 160,
253, 7, 23, 92, 111, 153, 26, 226, 33, 176, 144, 18, 216, 212, 28, 151, 71, 206, 222, 182, 8, 174, 205, 201, 152,
240, 155, 108, 223, 104, 239, 98, 164, 211, 184, 34, 193, 14, 114, 187, 40, 254, 12, 67, 93, 217, 6, 94, 16, 19, 82
, 86, 245, 24, 197, 134, 132, 138, 229, 121, 5, 235, 238, 85, 47, 103, 113, 179, 69, 250, 45, 135, 156, 25, 61,
75, 44, 146, 189, 84, 207, 172, 119, 53, 123, 186, 120, 171, 68, 227, 145, 136, 100, 90, 48, 79, 159, 149, 39, 213,
236, 126, 52, 60, 225, 199, 105, 73, 233, 252, 118, 215, 35, 115, 64, 37, 97, 129, 161, 177, 87, 237, 141, 173, 191
, 163, 140, 234, 232, 249],
[117, 94, 17, 103, 16, 186, 172, 127, 146, 23, 46, 25, 168, 8, 163, 39, 174, 67, 137, 175, 121, 59, 9, 128, 179, 199
, 132, 4, 140, 54, 1, 85, 14, 134, 161, 238, 30, 241, 37, 224, 166, 45, 119, 109, 202, 196, 93, 190, 220, 69, 49
, 21, 228, 209, 60, 73, 99, 65, 102, 7, 229, 200, 19, 82, 240, 71, 105, 169, 214, 194, 64, 142, 12, 233, 88, 201
, 11, 72, 92, 221, 27, 32, 176, 124, 205, 189, 177, 246, 35, 112, 219, 61, 129, 170, 173, 100, 84, 242, 157, 26,
218, 20, 33, 191, 155, 232, 87, 86, 153, 114, 97, 130, 29, 192, 164, 239, 90, 43, 236, 208, 212, 185, 75, 210, 0,
81, 227, 5, 116, 243, 34, 18, 182, 70, 181, 197, 217, 95, 183, 101, 252, 248, 107, 89, 136, 216, 203, 68, 91, 223,
96, 141, 150, 131, 13, 152, 198, 111, 44, 222, 125, 244, 76, 251, 158, 106, 24, 42, 38, 77, 2, 213, 207, 249, 147,
113, 135, 245, 118, 193, 47, 98, 145, 66, 160, 123, 211, 165, 78, 204, 80, 250, 110, 162, 48, 58, 10, 180, 55, 231,
79, 149, 74, 62, 50, 148, 143, 206, 28, 15, 57, 159, 139, 225, 122, 237, 138, 171, 36, 56, 115, 63, 144, 154, 6,
230, 133, 215, 41, 184, 22, 104, 254, 234, 253, 187, 226, 247, 188, 156, 151, 40, 108, 51, 83, 178, 52, 3, 31, 255,
195, 53, 235, 126, 167, 120]]
getTable :: ByteString -> [Word8]
getTable key = do
let s = L.fromStrict $ hash key
a = runGet getWord64le s
table = [0..255]
map fromIntegral $ sortTable 1 a table
sortTable :: Word64 -> Word64 -> [Word64] -> [Word64]
sortTable 1024 _ table = table
sortTable i a table = sortTable (i+1) a $ sortBy cmp table
where
cmp x y = compare (a `mod` (x + i)) (a `mod` (y + i))
main :: IO ()
main = do
runTestTT tests
(_, Just p1_out, _, p1_hdl) <-
createProcess (shell "cabal run ssserver") { std_out = CreatePipe }
(_, Just p2_out, _, p2_hdl) <-
createProcess (shell "cabal run sslocal") { std_out = CreatePipe }
wait1 <- newEmptyMVar
wait2 <- newEmptyMVar
forkIO $ readOut p1_out wait1
forkIO $ readOut p2_out wait2
takeMVar wait1
takeMVar wait2
code <- rawSystem "curl" [ "http://www.example.com/"
, "-v"
, "-L"
, "--socks5-hostname"
, "127.0.0.1:1080"
]
putStrLn $ if code == ExitSuccess then "test passed"
else "test failed"
hClose p1_out
hClose p2_out
interruptProcessGroupOf p1_hdl
interruptProcessGroupOf p2_hdl
where
toDecrypt t = elems $ fromList $ zip (map fromIntegral t) [0..255]
table1 = getTable "foobar!"
decryptTable1 = toDecrypt table1
table2 = getTable "barfoo!"
decryptTable2 = toDecrypt table2
tests = TestList [ table1 ~?= head target1
, decryptTable1 ~?= last target1
, table2 ~?= head target2
, decryptTable2 ~?= last target2
]
readOut h wait = do
line <- S.hGetLine h
let (s, _) = S.breakSubstring "starting" line
if S.null s then putMVar wait ()
else readOut h wait
|
fishky/shadowsocks-haskell
|
test.hs
|
mit
| 7,794
| 0
| 13
| 2,252
| 3,897
| 2,490
| 1,407
| 113
| 3
|
module TestLayer where
import Test.Hspec
import Test.QuickCheck
import AI.Neuron
import AI.Layer
testLayer :: IO ()
testLayer = hspec $
describe "Layer" $
it "should be able to pass tests" $
1 `shouldBe` 1
|
jbarrow/LambdaNet
|
test/TestLayer.hs
|
mit
| 221
| 0
| 9
| 48
| 63
| 35
| 28
| 10
| 1
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.StorageGateway.CreateStorediSCSIVolume
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- This operation creates a volume on a specified gateway. This operation
-- is supported only for the gateway-stored volume architecture.
--
-- The size of the volume to create is inferred from the disk size. You can
-- choose to preserve existing data on the disk, create volume from an
-- existing snapshot, or create an empty volume. If you choose to create an
-- empty gateway volume, then any existing data on the disk is erased.
--
-- In the request you must specify the gateway and the disk information on
-- which you are creating the volume. In response, AWS Storage Gateway
-- creates the volume and returns volume information such as the volume
-- Amazon Resource Name (ARN), its size, and the iSCSI target ARN that
-- initiators can use to connect to the volume target.
--
-- /See:/ <http://docs.aws.amazon.com/storagegateway/latest/APIReference/API_CreateStorediSCSIVolume.html AWS API Reference> for CreateStorediSCSIVolume.
module Network.AWS.StorageGateway.CreateStorediSCSIVolume
(
-- * Creating a Request
createStorediSCSIVolume
, CreateStorediSCSIVolume
-- * Request Lenses
, csscsivSnapshotId
, csscsivGatewayARN
, csscsivDiskId
, csscsivPreserveExistingData
, csscsivTargetName
, csscsivNetworkInterfaceId
-- * Destructuring the Response
, createStorediSCSIVolumeResponse
, CreateStorediSCSIVolumeResponse
-- * Response Lenses
, csscsivrsTargetARN
, csscsivrsVolumeARN
, csscsivrsVolumeSizeInBytes
, csscsivrsResponseStatus
) where
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
import Network.AWS.StorageGateway.Types
import Network.AWS.StorageGateway.Types.Product
-- | A JSON object containing one or more of the following fields:
--
-- - CreateStorediSCSIVolumeInput$DiskId
-- - CreateStorediSCSIVolumeInput$NetworkInterfaceId
-- - CreateStorediSCSIVolumeInput$PreserveExistingData
-- - CreateStorediSCSIVolumeInput$SnapshotId
-- - CreateStorediSCSIVolumeInput$TargetName
--
-- /See:/ 'createStorediSCSIVolume' smart constructor.
data CreateStorediSCSIVolume = CreateStorediSCSIVolume'
{ _csscsivSnapshotId :: !(Maybe Text)
, _csscsivGatewayARN :: !Text
, _csscsivDiskId :: !Text
, _csscsivPreserveExistingData :: !Bool
, _csscsivTargetName :: !Text
, _csscsivNetworkInterfaceId :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateStorediSCSIVolume' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'csscsivSnapshotId'
--
-- * 'csscsivGatewayARN'
--
-- * 'csscsivDiskId'
--
-- * 'csscsivPreserveExistingData'
--
-- * 'csscsivTargetName'
--
-- * 'csscsivNetworkInterfaceId'
createStorediSCSIVolume
:: Text -- ^ 'csscsivGatewayARN'
-> Text -- ^ 'csscsivDiskId'
-> Bool -- ^ 'csscsivPreserveExistingData'
-> Text -- ^ 'csscsivTargetName'
-> Text -- ^ 'csscsivNetworkInterfaceId'
-> CreateStorediSCSIVolume
createStorediSCSIVolume pGatewayARN_ pDiskId_ pPreserveExistingData_ pTargetName_ pNetworkInterfaceId_ =
CreateStorediSCSIVolume'
{ _csscsivSnapshotId = Nothing
, _csscsivGatewayARN = pGatewayARN_
, _csscsivDiskId = pDiskId_
, _csscsivPreserveExistingData = pPreserveExistingData_
, _csscsivTargetName = pTargetName_
, _csscsivNetworkInterfaceId = pNetworkInterfaceId_
}
-- | The snapshot ID (e.g. \"snap-1122aabb\") of the snapshot to restore as
-- the new stored volume. Specify this field if you want to create the
-- iSCSI storage volume from a snapshot otherwise do not include this
-- field. To list snapshots for your account use
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSnapshots.html DescribeSnapshots>
-- in the /Amazon Elastic Compute Cloud API Reference/.
csscsivSnapshotId :: Lens' CreateStorediSCSIVolume (Maybe Text)
csscsivSnapshotId = lens _csscsivSnapshotId (\ s a -> s{_csscsivSnapshotId = a});
-- | Undocumented member.
csscsivGatewayARN :: Lens' CreateStorediSCSIVolume Text
csscsivGatewayARN = lens _csscsivGatewayARN (\ s a -> s{_csscsivGatewayARN = a});
-- | The unique identifier for the gateway local disk that is configured as a
-- stored volume. Use
-- <http://docs.aws.amazon.com/storagegateway/latest/userguide/API_ListLocalDisks.html ListLocalDisks>
-- to list disk IDs for a gateway.
csscsivDiskId :: Lens' CreateStorediSCSIVolume Text
csscsivDiskId = lens _csscsivDiskId (\ s a -> s{_csscsivDiskId = a});
-- | Specify this field as true if you want to preserve the data on the local
-- disk. Otherwise, specifying this field as false creates an empty volume.
--
-- /Valid Values/: true, false
csscsivPreserveExistingData :: Lens' CreateStorediSCSIVolume Bool
csscsivPreserveExistingData = lens _csscsivPreserveExistingData (\ s a -> s{_csscsivPreserveExistingData = a});
-- | The name of the iSCSI target used by initiators to connect to the target
-- and as a suffix for the target ARN. For example, specifying 'TargetName'
-- as /myvolume/ results in the target ARN of
-- arn:aws:storagegateway:us-east-1:111122223333:gateway\/mygateway\/target\/iqn.1997-05.com.amazon:myvolume.
-- The target name must be unique across all volumes of a gateway.
csscsivTargetName :: Lens' CreateStorediSCSIVolume Text
csscsivTargetName = lens _csscsivTargetName (\ s a -> s{_csscsivTargetName = a});
-- | The network interface of the gateway on which to expose the iSCSI
-- target. Only IPv4 addresses are accepted. Use DescribeGatewayInformation
-- to get a list of the network interfaces available on a gateway.
--
-- /Valid Values/: A valid IP address.
csscsivNetworkInterfaceId :: Lens' CreateStorediSCSIVolume Text
csscsivNetworkInterfaceId = lens _csscsivNetworkInterfaceId (\ s a -> s{_csscsivNetworkInterfaceId = a});
instance AWSRequest CreateStorediSCSIVolume where
type Rs CreateStorediSCSIVolume =
CreateStorediSCSIVolumeResponse
request = postJSON storageGateway
response
= receiveJSON
(\ s h x ->
CreateStorediSCSIVolumeResponse' <$>
(x .?> "TargetARN") <*> (x .?> "VolumeARN") <*>
(x .?> "VolumeSizeInBytes")
<*> (pure (fromEnum s)))
instance ToHeaders CreateStorediSCSIVolume where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("StorageGateway_20130630.CreateStorediSCSIVolume" ::
ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON CreateStorediSCSIVolume where
toJSON CreateStorediSCSIVolume'{..}
= object
(catMaybes
[("SnapshotId" .=) <$> _csscsivSnapshotId,
Just ("GatewayARN" .= _csscsivGatewayARN),
Just ("DiskId" .= _csscsivDiskId),
Just
("PreserveExistingData" .=
_csscsivPreserveExistingData),
Just ("TargetName" .= _csscsivTargetName),
Just
("NetworkInterfaceId" .=
_csscsivNetworkInterfaceId)])
instance ToPath CreateStorediSCSIVolume where
toPath = const "/"
instance ToQuery CreateStorediSCSIVolume where
toQuery = const mempty
-- | A JSON object containing the following fields:
--
-- /See:/ 'createStorediSCSIVolumeResponse' smart constructor.
data CreateStorediSCSIVolumeResponse = CreateStorediSCSIVolumeResponse'
{ _csscsivrsTargetARN :: !(Maybe Text)
, _csscsivrsVolumeARN :: !(Maybe Text)
, _csscsivrsVolumeSizeInBytes :: !(Maybe Integer)
, _csscsivrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateStorediSCSIVolumeResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'csscsivrsTargetARN'
--
-- * 'csscsivrsVolumeARN'
--
-- * 'csscsivrsVolumeSizeInBytes'
--
-- * 'csscsivrsResponseStatus'
createStorediSCSIVolumeResponse
:: Int -- ^ 'csscsivrsResponseStatus'
-> CreateStorediSCSIVolumeResponse
createStorediSCSIVolumeResponse pResponseStatus_ =
CreateStorediSCSIVolumeResponse'
{ _csscsivrsTargetARN = Nothing
, _csscsivrsVolumeARN = Nothing
, _csscsivrsVolumeSizeInBytes = Nothing
, _csscsivrsResponseStatus = pResponseStatus_
}
-- | he Amazon Resource Name (ARN) of the volume target that includes the
-- iSCSI name that initiators can use to connect to the target.
csscsivrsTargetARN :: Lens' CreateStorediSCSIVolumeResponse (Maybe Text)
csscsivrsTargetARN = lens _csscsivrsTargetARN (\ s a -> s{_csscsivrsTargetARN = a});
-- | The Amazon Resource Name (ARN) of the configured volume.
csscsivrsVolumeARN :: Lens' CreateStorediSCSIVolumeResponse (Maybe Text)
csscsivrsVolumeARN = lens _csscsivrsVolumeARN (\ s a -> s{_csscsivrsVolumeARN = a});
-- | The size of the volume in bytes.
csscsivrsVolumeSizeInBytes :: Lens' CreateStorediSCSIVolumeResponse (Maybe Integer)
csscsivrsVolumeSizeInBytes = lens _csscsivrsVolumeSizeInBytes (\ s a -> s{_csscsivrsVolumeSizeInBytes = a});
-- | The response status code.
csscsivrsResponseStatus :: Lens' CreateStorediSCSIVolumeResponse Int
csscsivrsResponseStatus = lens _csscsivrsResponseStatus (\ s a -> s{_csscsivrsResponseStatus = a});
|
fmapfmapfmap/amazonka
|
amazonka-storagegateway/gen/Network/AWS/StorageGateway/CreateStorediSCSIVolume.hs
|
mpl-2.0
| 10,311
| 0
| 14
| 2,042
| 1,178
| 712
| 466
| 145
| 1
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.ElasticTranscoder.CancelJob
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- The CancelJob operation cancels an unfinished job.
--
-- You can only cancel a job that has a status of 'Submitted'. To prevent a
-- pipeline from starting to process a job while you\'re getting the job
-- identifier, use UpdatePipelineStatus to temporarily pause the pipeline.
--
-- /See:/ <http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/CancelJob.html AWS API Reference> for CancelJob.
module Network.AWS.ElasticTranscoder.CancelJob
(
-- * Creating a Request
cancelJob
, CancelJob
-- * Request Lenses
, cjId
-- * Destructuring the Response
, cancelJobResponse
, CancelJobResponse
-- * Response Lenses
, canrsResponseStatus
) where
import Network.AWS.ElasticTranscoder.Types
import Network.AWS.ElasticTranscoder.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | The 'CancelJobRequest' structure.
--
-- /See:/ 'cancelJob' smart constructor.
newtype CancelJob = CancelJob'
{ _cjId :: Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CancelJob' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cjId'
cancelJob
:: Text -- ^ 'cjId'
-> CancelJob
cancelJob pId_ =
CancelJob'
{ _cjId = pId_
}
-- | The identifier of the job that you want to cancel.
--
-- To get a list of the jobs (including their 'jobId') that have a status
-- of 'Submitted', use the ListJobsByStatus API action.
cjId :: Lens' CancelJob Text
cjId = lens _cjId (\ s a -> s{_cjId = a});
instance AWSRequest CancelJob where
type Rs CancelJob = CancelJobResponse
request = delete elasticTranscoder
response
= receiveEmpty
(\ s h x ->
CancelJobResponse' <$> (pure (fromEnum s)))
instance ToHeaders CancelJob where
toHeaders = const mempty
instance ToPath CancelJob where
toPath CancelJob'{..}
= mconcat ["/2012-09-25/jobs/", toBS _cjId]
instance ToQuery CancelJob where
toQuery = const mempty
-- | The response body contains a JSON object. If the job is successfully
-- canceled, the value of 'Success' is 'true'.
--
-- /See:/ 'cancelJobResponse' smart constructor.
newtype CancelJobResponse = CancelJobResponse'
{ _canrsResponseStatus :: Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CancelJobResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'canrsResponseStatus'
cancelJobResponse
:: Int -- ^ 'canrsResponseStatus'
-> CancelJobResponse
cancelJobResponse pResponseStatus_ =
CancelJobResponse'
{ _canrsResponseStatus = pResponseStatus_
}
-- | The response status code.
canrsResponseStatus :: Lens' CancelJobResponse Int
canrsResponseStatus = lens _canrsResponseStatus (\ s a -> s{_canrsResponseStatus = a});
|
fmapfmapfmap/amazonka
|
amazonka-elastictranscoder/gen/Network/AWS/ElasticTranscoder/CancelJob.hs
|
mpl-2.0
| 3,723
| 0
| 13
| 771
| 448
| 277
| 171
| 57
| 1
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-}
-- |
-- Module : Statistics.Types
-- Copyright : (c) 2009 Bryan O'Sullivan
-- License : BSD3
--
-- Maintainer : bos@serpentine.com
-- Stability : experimental
-- Portability : portable
--
-- Data types common used in statistics
module Statistics.Types
( -- * Confidence level
CL
-- ** Accessors
, confidenceLevel
, significanceLevel
-- ** Constructors
, mkCL
, mkCLE
, mkCLFromSignificance
, mkCLFromSignificanceE
-- ** Constants and conversion to nσ
, cl90
, cl95
, cl99
-- *** Normal approximation
, nSigma
, nSigma1
, getNSigma
, getNSigma1
-- * p-value
, PValue
-- ** Accessors
, pValue
-- ** Constructors
, mkPValue
, mkPValueE
-- * Estimates and upper/lower limits
, Estimate(..)
, NormalErr(..)
, ConfInt(..)
, UpperLimit(..)
, LowerLimit(..)
-- ** Constructors
, estimateNormErr
, (±)
, estimateFromInterval
, estimateFromErr
-- ** Accessors
, confidenceInterval
, asymErrors
, Scale(..)
-- * Other
, Sample
, WeightedSample
, Weights
) where
import Control.Monad ((<=<), liftM2, liftM3)
import Control.DeepSeq (NFData(..))
import Data.Aeson (FromJSON(..), ToJSON)
import Data.Binary (Binary(..))
import Data.Data (Data,Typeable)
import Data.Maybe (fromMaybe)
import Data.Vector.Unboxed (Unbox)
import Data.Vector.Unboxed.Deriving (derivingUnbox)
import GHC.Generics (Generic)
#if __GLASGOW_HASKELL__ == 704
import qualified Data.Vector.Generic
import qualified Data.Vector.Generic.Mutable
#endif
import Statistics.Internal
import Statistics.Types.Internal
import Statistics.Distribution
import Statistics.Distribution.Normal
----------------------------------------------------------------
-- Data type for confidence level
----------------------------------------------------------------
-- |
-- Confidence level. In context of confidence intervals it's
-- probability of said interval covering true value of measured
-- value. In context of statistical tests it's @1-α@ where α is
-- significance of test.
--
-- Since confidence level are usually close to 1 they are stored as
-- @1-CL@ internally. There are two smart constructors for @CL@:
-- 'mkCL' and 'mkCLFromSignificance' (and corresponding variant
-- returning @Maybe@). First creates @CL@ from confidence level and
-- second from @1 - CL@ or significance level.
--
-- >>> cl95
-- mkCLFromSignificance 0.05
--
-- Prior to 0.14 confidence levels were passed to function as plain
-- @Doubles@. Use 'mkCL' to convert them to @CL@.
newtype CL a = CL a
deriving (Eq, Typeable, Data, Generic)
instance Show a => Show (CL a) where
showsPrec n (CL p) = defaultShow1 "mkCLFromSignificance" p n
instance (Num a, Ord a, Read a) => Read (CL a) where
readPrec = defaultReadPrecM1 "mkCLFromSignificance" mkCLFromSignificanceE
instance (Binary a, Num a, Ord a) => Binary (CL a) where
put (CL p) = put p
get = maybe (fail errMkCL) return . mkCLFromSignificanceE =<< get
instance (ToJSON a) => ToJSON (CL a)
instance (FromJSON a, Num a, Ord a) => FromJSON (CL a) where
parseJSON = maybe (fail errMkCL) return . mkCLFromSignificanceE <=< parseJSON
instance NFData a => NFData (CL a) where
rnf (CL a) = rnf a
-- |
-- >>> cl95 > cl90
-- True
instance Ord a => Ord (CL a) where
CL a < CL b = a > b
CL a <= CL b = a >= b
CL a > CL b = a < b
CL a >= CL b = a <= b
max (CL a) (CL b) = CL (min a b)
min (CL a) (CL b) = CL (max a b)
-- | Create confidence level from probability β or probability
-- confidence interval contain true value of estimate. Will throw
-- exception if parameter is out of [0,1] range
--
-- >>> mkCL 0.95 -- same as cl95
-- mkCLFromSignificance 0.05
mkCL :: (Ord a, Num a) => a -> CL a
mkCL
= fromMaybe (error "Statistics.Types.mkCL: probability is out if [0,1] range")
. mkCLE
-- | Same as 'mkCL' but returns @Nothing@ instead of error if
-- parameter is out of [0,1] range
--
-- >>> mkCLE 0.95 -- same as cl95
-- Just (mkCLFromSignificance 0.05)
mkCLE :: (Ord a, Num a) => a -> Maybe (CL a)
mkCLE p
| p >= 0 && p <= 1 = Just $ CL (1 - p)
| otherwise = Nothing
-- | Create confidence level from probability α or probability that
-- confidence interval does not contain true value of estimate. Will
-- throw exception if parameter is out of [0,1] range
--
-- >>> mkCLFromSignificance 0.05 -- same as cl95
-- mkCLFromSignificance 0.05
mkCLFromSignificance :: (Ord a, Num a) => a -> CL a
mkCLFromSignificance = fromMaybe (error errMkCL) . mkCLFromSignificanceE
-- | Same as 'mkCLFromSignificance' but returns @Nothing@ instead of error if
-- parameter is out of [0,1] range
--
-- >>> mkCLFromSignificanceE 0.05 -- same as cl95
-- Just (mkCLFromSignificance 0.05)
mkCLFromSignificanceE :: (Ord a, Num a) => a -> Maybe (CL a)
mkCLFromSignificanceE p
| p >= 0 && p <= 1 = Just $ CL p
| otherwise = Nothing
errMkCL :: String
errMkCL = "Statistics.Types.mkPValCL: probability is out if [0,1] range"
-- | Get confidence level. This function is subject to rounding
-- errors. If @1 - CL@ is needed use 'significanceLevel' instead
confidenceLevel :: (Num a) => CL a -> a
confidenceLevel (CL p) = 1 - p
-- | Get significance level.
significanceLevel :: CL a -> a
significanceLevel (CL p) = p
-- | 90% confidence level
cl90 :: Fractional a => CL a
cl90 = CL 0.10
-- | 95% confidence level
cl95 :: Fractional a => CL a
cl95 = CL 0.05
-- | 99% confidence level
cl99 :: Fractional a => CL a
cl99 = CL 0.01
----------------------------------------------------------------
-- Data type for p-value
----------------------------------------------------------------
-- | Newtype wrapper for p-value.
newtype PValue a = PValue a
deriving (Eq,Ord, Typeable, Data, Generic)
instance Show a => Show (PValue a) where
showsPrec n (PValue p) = defaultShow1 "mkPValue" p n
instance (Num a, Ord a, Read a) => Read (PValue a) where
readPrec = defaultReadPrecM1 "mkPValue" mkPValueE
instance (Binary a, Num a, Ord a) => Binary (PValue a) where
put (PValue p) = put p
get = maybe (fail errMkPValue) return . mkPValueE =<< get
instance (ToJSON a) => ToJSON (PValue a)
instance (FromJSON a, Num a, Ord a) => FromJSON (PValue a) where
parseJSON = maybe (fail errMkPValue) return . mkPValueE <=< parseJSON
instance NFData a => NFData (PValue a) where
rnf (PValue a) = rnf a
-- | Construct PValue. Throws error if argument is out of [0,1] range.
--
mkPValue :: (Ord a, Num a) => a -> PValue a
mkPValue = fromMaybe (error errMkPValue) . mkPValueE
-- | Construct PValue. Returns @Nothing@ if argument is out of [0,1] range.
mkPValueE :: (Ord a, Num a) => a -> Maybe (PValue a)
mkPValueE p
| p >= 0 && p <= 1 = Just $ PValue p
| otherwise = Nothing
-- | Get p-value
pValue :: PValue a -> a
pValue (PValue p) = p
-- | P-value expressed in sigma. This is convention widely used in
-- experimental physics. N sigma confidence level corresponds to
-- probability within N sigma of normal distribution.
--
-- Note that this correspondence is for normal distribution. Other
-- distribution will have different dependency. Also experimental
-- distribution usually only approximately normal (especially at
-- extreme tails).
nSigma :: Double -> PValue Double
nSigma n
| n > 0 = PValue $ 2 * cumulative standard (-n)
| otherwise = error "Statistics.Extra.Error.nSigma: non-positive number of sigma"
-- | P-value expressed in sigma for one-tail hypothesis. This correspond to
-- probability of obtaining value less than @N·σ@.
nSigma1 :: Double -> PValue Double
nSigma1 n
| n > 0 = PValue $ cumulative standard (-n)
| otherwise = error "Statistics.Extra.Error.nSigma1: non-positive number of sigma"
-- | Express confidence level in sigmas
getNSigma :: PValue Double -> Double
getNSigma (PValue p) = negate $ quantile standard (p / 2)
-- | Express confidence level in sigmas for one-tailed hypothesis.
getNSigma1 :: PValue Double -> Double
getNSigma1 (PValue p) = negate $ quantile standard p
errMkPValue :: String
errMkPValue = "Statistics.Types.mkPValue: probability is out if [0,1] range"
----------------------------------------------------------------
-- Point estimates
----------------------------------------------------------------
-- |
-- A point estimate and its confidence interval. It's parametrized by
-- both error type @e@ and value type @a@. This module provides two
-- types of error: 'NormalErr' for normally distributed errors and
-- 'ConfInt' for error with normal distribution. See their
-- documentation for more details.
--
-- For example @144 ± 5@ (assuming normality) could be expressed as
--
-- > Estimate { estPoint = 144
-- > , estError = NormalErr 5
-- > }
--
-- Or if we want to express @144 + 6 - 4@ at CL95 we could write:
--
-- > Estimate { estPoint = 144
-- > , estError = ConfInt
-- > { confIntLDX = 4
-- > , confIntUDX = 6
-- > , confIntCL = cl95
-- > }
--
-- Prior to statistics 0.14 @Estimate@ data type used following definition:
--
-- > data Estimate = Estimate {
-- > estPoint :: {-# UNPACK #-} !Double
-- > , estLowerBound :: {-# UNPACK #-} !Double
-- > , estUpperBound :: {-# UNPACK #-} !Double
-- > , estConfidenceLevel :: {-# UNPACK #-} !Double
-- > }
--
-- Now type @Estimate ConfInt Double@ should be used instead. Function
-- 'estimateFromInterval' allow to easily construct estimate from same inputs.
data Estimate e a = Estimate
{ estPoint :: !a
-- ^ Point estimate.
, estError :: !(e a)
-- ^ Confidence interval for estimate.
} deriving (Eq, Read, Show, Generic
#if __GLASGOW_HASKELL__ >= 708
, Typeable, Data
#endif
)
instance (Binary (e a), Binary a) => Binary (Estimate e a) where
get = liftM2 Estimate get get
put (Estimate ep ee) = put ep >> put ee
instance (FromJSON (e a), FromJSON a) => FromJSON (Estimate e a)
instance (ToJSON (e a), ToJSON a) => ToJSON (Estimate e a)
instance (NFData (e a), NFData a) => NFData (Estimate e a) where
rnf (Estimate x dx) = rnf x `seq` rnf dx
-- |
-- Normal errors. They are stored as 1σ errors which corresponds to
-- 68.8% CL. Since we can recalculate them to any confidence level if
-- needed we don't store it.
newtype NormalErr a = NormalErr
{ normalError :: a
}
deriving (Eq, Read, Show, Typeable, Data, Generic)
instance Binary a => Binary (NormalErr a) where
get = fmap NormalErr get
put = put . normalError
instance FromJSON a => FromJSON (NormalErr a)
instance ToJSON a => ToJSON (NormalErr a)
instance NFData a => NFData (NormalErr a) where
rnf (NormalErr x) = rnf x
-- | Confidence interval. It assumes that confidence interval forms
-- single interval and isn't set of disjoint intervals.
data ConfInt a = ConfInt
{ confIntLDX :: !a
-- ^ Lower error estimate, or distance between point estimate and
-- lower bound of confidence interval.
, confIntUDX :: !a
-- ^ Upper error estimate, or distance between point estimate and
-- upper bound of confidence interval.
, confIntCL :: !(CL Double)
-- ^ Confidence level corresponding to given confidence interval.
}
deriving (Read,Show,Eq,Typeable,Data,Generic)
instance Binary a => Binary (ConfInt a) where
get = liftM3 ConfInt get get get
put (ConfInt l u cl) = put l >> put u >> put cl
instance FromJSON a => FromJSON (ConfInt a)
instance ToJSON a => ToJSON (ConfInt a)
instance NFData a => NFData (ConfInt a) where
rnf (ConfInt x y _) = rnf x `seq` rnf y
----------------------------------------
-- Constructors
-- | Create estimate with normal errors
estimateNormErr :: a -- ^ Point estimate
-> a -- ^ 1σ error
-> Estimate NormalErr a
estimateNormErr x dx = Estimate x (NormalErr dx)
-- | Synonym for 'estimateNormErr'
(±) :: a -- ^ Point estimate
-> a -- ^ 1σ error
-> Estimate NormalErr a
(±) = estimateNormErr
-- | Create estimate with asymmetric error.
estimateFromErr
:: a -- ^ Central estimate
-> (a,a) -- ^ Lower and upper errors. Both should be
-- positive but it's not checked.
-> CL Double -- ^ Confidence level for interval
-> Estimate ConfInt a
estimateFromErr x (ldx,udx) cl = Estimate x (ConfInt ldx udx cl)
-- | Create estimate with asymmetric error.
estimateFromInterval
:: Num a
=> a -- ^ Point estimate. Should lie within
-- interval but it's not checked.
-> (a,a) -- ^ Lower and upper bounds of interval
-> CL Double -- ^ Confidence level for interval
-> Estimate ConfInt a
estimateFromInterval x (lx,ux) cl
= Estimate x (ConfInt (x-lx) (ux-x) cl)
----------------------------------------
-- Accessors
-- | Get confidence interval
confidenceInterval :: Num a => Estimate ConfInt a -> (a,a)
confidenceInterval (Estimate x (ConfInt ldx udx _))
= (x - ldx, x + udx)
-- | Get asymmetric errors
asymErrors :: Estimate ConfInt a -> (a,a)
asymErrors (Estimate _ (ConfInt ldx udx _)) = (ldx,udx)
-- | Data types which could be multiplied by constant.
class Scale e where
scale :: (Ord a, Num a) => a -> e a -> e a
instance Scale NormalErr where
scale a (NormalErr e) = NormalErr (abs a * e)
instance Scale ConfInt where
scale a (ConfInt l u cl) | a >= 0 = ConfInt (a*l) (a*u) cl
| otherwise = ConfInt (-a*u) (-a*l) cl
instance Scale e => Scale (Estimate e) where
scale a (Estimate x dx) = Estimate (a*x) (scale a dx)
----------------------------------------------------------------
-- Upper/lower limit
----------------------------------------------------------------
-- | Upper limit. They are usually given for small non-negative values
-- when it's not possible detect difference from zero.
data UpperLimit a = UpperLimit
{ upperLimit :: !a
-- ^ Upper limit
, ulConfidenceLevel :: !(CL Double)
-- ^ Confidence level for which limit was calculated
} deriving (Eq, Read, Show, Typeable, Data, Generic)
instance Binary a => Binary (UpperLimit a) where
get = liftM2 UpperLimit get get
put (UpperLimit l cl) = put l >> put cl
instance FromJSON a => FromJSON (UpperLimit a)
instance ToJSON a => ToJSON (UpperLimit a)
instance NFData a => NFData (UpperLimit a) where
rnf (UpperLimit x cl) = rnf x `seq` rnf cl
-- | Lower limit. They are usually given for large quantities when
-- it's not possible to measure them. For example: proton half-life
data LowerLimit a = LowerLimit {
lowerLimit :: !a
-- ^ Lower limit
, llConfidenceLevel :: !(CL Double)
-- ^ Confidence level for which limit was calculated
} deriving (Eq, Read, Show, Typeable, Data, Generic)
instance Binary a => Binary (LowerLimit a) where
get = liftM2 LowerLimit get get
put (LowerLimit l cl) = put l >> put cl
instance FromJSON a => FromJSON (LowerLimit a)
instance ToJSON a => ToJSON (LowerLimit a)
instance NFData a => NFData (LowerLimit a) where
rnf (LowerLimit x cl) = rnf x `seq` rnf cl
----------------------------------------------------------------
-- Deriving unbox instances
----------------------------------------------------------------
derivingUnbox "CL"
[t| forall a. Unbox a => CL a -> a |]
[| \(CL a) -> a |]
[| CL |]
derivingUnbox "PValue"
[t| forall a. Unbox a => PValue a -> a |]
[| \(PValue a) -> a |]
[| PValue |]
derivingUnbox "Estimate"
[t| forall a e. (Unbox a, Unbox (e a)) => Estimate e a -> (a, e a) |]
[| \(Estimate x dx) -> (x,dx) |]
[| \(x,dx) -> (Estimate x dx) |]
derivingUnbox "NormalErr"
[t| forall a. Unbox a => NormalErr a -> a |]
[| \(NormalErr a) -> a |]
[| NormalErr |]
derivingUnbox "ConfInt"
[t| forall a. Unbox a => ConfInt a -> (a, a, CL Double) |]
[| \(ConfInt a b c) -> (a,b,c) |]
[| \(a,b,c) -> ConfInt a b c |]
derivingUnbox "UpperLimit"
[t| forall a. Unbox a => UpperLimit a -> (a, CL Double) |]
[| \(UpperLimit a b) -> (a,b) |]
[| \(a,b) -> UpperLimit a b |]
derivingUnbox "LowerLimit"
[t| forall a. Unbox a => LowerLimit a -> (a, CL Double) |]
[| \(LowerLimit a b) -> (a,b) |]
[| \(a,b) -> LowerLimit a b |]
|
bos/statistics
|
Statistics/Types.hs
|
bsd-2-clause
| 17,017
| 0
| 11
| 4,099
| 3,802
| 2,065
| 1,737
| -1
| -1
|
-- | When there aren't enough registers to hold all the vregs we have to spill
-- some of those vregs to slots on the stack. This module is used modify the
-- code to use those slots.
module RegAlloc.Graph.Spill (
regSpill,
SpillStats(..),
accSpillSL
) where
import RegAlloc.Liveness
import Instruction
import Reg
import Cmm hiding (RegSet)
import BlockId
import Hoopl
import MonadUtils
import State
import Unique
import UniqFM
import UniqSet
import UniqSupply
import Outputable
import Platform
import Data.List
import Data.Maybe
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
-- | Spill all these virtual regs to stack slots.
--
-- TODO: See if we can split some of the live ranges instead of just globally
-- spilling the virtual reg. This might make the spill cleaner's job easier.
--
-- TODO: On CISCy x86 and x86_64 we don't nessesarally have to add a mov instruction
-- when making spills. If an instr is using a spilled virtual we may be able to
-- address the spill slot directly.
--
regSpill
:: Instruction instr
=> Platform
-> [LiveCmmDecl statics instr] -- ^ the code
-> UniqSet Int -- ^ available stack slots
-> UniqSet VirtualReg -- ^ the regs to spill
-> UniqSM
([LiveCmmDecl statics instr]
-- code with SPILL and RELOAD meta instructions added.
, UniqSet Int -- left over slots
, SpillStats ) -- stats about what happened during spilling
regSpill platform code slotsFree regs
-- Not enough slots to spill these regs.
| sizeUniqSet slotsFree < sizeUniqSet regs
= pprPanic "regSpill: out of spill slots!"
( text " regs to spill = " <> ppr (sizeUniqSet regs)
$$ text " slots left = " <> ppr (sizeUniqSet slotsFree))
| otherwise
= do
-- Allocate a slot for each of the spilled regs.
let slots = take (sizeUniqSet regs) $ nonDetEltsUFM slotsFree
let regSlotMap = listToUFM
$ zip (nonDetEltsUFM regs) slots
-- This is non-deterministic but we do not
-- currently support deterministic code-generation.
-- See Note [Unique Determinism and code generation]
-- Grab the unique supply from the monad.
us <- getUniqueSupplyM
-- Run the spiller on all the blocks.
let (code', state') =
runState (mapM (regSpill_top platform regSlotMap) code)
(initSpillS us)
return ( code'
, minusUniqSet slotsFree (mkUniqSet slots)
, makeSpillStats state')
-- | Spill some registers to stack slots in a top-level thing.
regSpill_top
:: Instruction instr
=> Platform
-> RegMap Int
-- ^ map of vregs to slots they're being spilled to.
-> LiveCmmDecl statics instr
-- ^ the top level thing.
-> SpillM (LiveCmmDecl statics instr)
regSpill_top platform regSlotMap cmm
= case cmm of
CmmData{}
-> return cmm
CmmProc info label live sccs
| LiveInfo static firstId mLiveVRegsOnEntry liveSlotsOnEntry <- info
-> do
-- We should only passed Cmms with the liveness maps filled in,
-- but we'll create empty ones if they're not there just in case.
let liveVRegsOnEntry = fromMaybe mapEmpty mLiveVRegsOnEntry
-- The liveVRegsOnEntry contains the set of vregs that are live
-- on entry to each basic block. If we spill one of those vregs
-- we remove it from that set and add the corresponding slot
-- number to the liveSlotsOnEntry set. The spill cleaner needs
-- this information to erase unneeded spill and reload instructions
-- after we've done a successful allocation.
let liveSlotsOnEntry' :: BlockMap IntSet
liveSlotsOnEntry'
= mapFoldWithKey patchLiveSlot
liveSlotsOnEntry liveVRegsOnEntry
let info'
= LiveInfo static firstId
(Just liveVRegsOnEntry)
liveSlotsOnEntry'
-- Apply the spiller to all the basic blocks in the CmmProc.
sccs' <- mapM (mapSCCM (regSpill_block platform regSlotMap)) sccs
return $ CmmProc info' label live sccs'
where -- Given a BlockId and the set of registers live in it,
-- if registers in this block are being spilled to stack slots,
-- then record the fact that these slots are now live in those blocks
-- in the given slotmap.
patchLiveSlot
:: BlockId -> RegSet
-> BlockMap IntSet -> BlockMap IntSet
patchLiveSlot blockId regsLive slotMap
= let
-- Slots that are already recorded as being live.
curSlotsLive = fromMaybe IntSet.empty
$ mapLookup blockId slotMap
moreSlotsLive = IntSet.fromList
$ catMaybes
$ map (lookupUFM regSlotMap)
$ nonDetEltsUFM regsLive
-- See Note [Unique Determinism and code generation]
slotMap'
= mapInsert blockId (IntSet.union curSlotsLive moreSlotsLive)
slotMap
in slotMap'
-- | Spill some registers to stack slots in a basic block.
regSpill_block
:: Instruction instr
=> Platform
-> UniqFM Int -- ^ map of vregs to slots they're being spilled to.
-> LiveBasicBlock instr
-> SpillM (LiveBasicBlock instr)
regSpill_block platform regSlotMap (BasicBlock i instrs)
= do instrss' <- mapM (regSpill_instr platform regSlotMap) instrs
return $ BasicBlock i (concat instrss')
-- | Spill some registers to stack slots in a single instruction.
-- If the instruction uses registers that need to be spilled, then it is
-- prefixed (or postfixed) with the appropriate RELOAD or SPILL meta
-- instructions.
regSpill_instr
:: Instruction instr
=> Platform
-> UniqFM Int -- ^ map of vregs to slots they're being spilled to.
-> LiveInstr instr
-> SpillM [LiveInstr instr]
regSpill_instr _ _ li@(LiveInstr _ Nothing)
= do return [li]
regSpill_instr platform regSlotMap
(LiveInstr instr (Just _))
= do
-- work out which regs are read and written in this instr
let RU rlRead rlWritten = regUsageOfInstr platform instr
-- sometimes a register is listed as being read more than once,
-- nub this so we don't end up inserting two lots of spill code.
let rsRead_ = nub rlRead
let rsWritten_ = nub rlWritten
-- if a reg is modified, it appears in both lists, want to undo this..
let rsRead = rsRead_ \\ rsWritten_
let rsWritten = rsWritten_ \\ rsRead_
let rsModify = intersect rsRead_ rsWritten_
-- work out if any of the regs being used are currently being spilled.
let rsSpillRead = filter (\r -> elemUFM r regSlotMap) rsRead
let rsSpillWritten = filter (\r -> elemUFM r regSlotMap) rsWritten
let rsSpillModify = filter (\r -> elemUFM r regSlotMap) rsModify
-- rewrite the instr and work out spill code.
(instr1, prepost1) <- mapAccumLM (spillRead regSlotMap) instr rsSpillRead
(instr2, prepost2) <- mapAccumLM (spillWrite regSlotMap) instr1 rsSpillWritten
(instr3, prepost3) <- mapAccumLM (spillModify regSlotMap) instr2 rsSpillModify
let (mPrefixes, mPostfixes) = unzip (prepost1 ++ prepost2 ++ prepost3)
let prefixes = concat mPrefixes
let postfixes = concat mPostfixes
-- final code
let instrs' = prefixes
++ [LiveInstr instr3 Nothing]
++ postfixes
return $ instrs'
-- | Add a RELOAD met a instruction to load a value for an instruction that
-- writes to a vreg that is being spilled.
spillRead
:: Instruction instr
=> UniqFM Int
-> instr
-> Reg
-> SpillM (instr, ([LiveInstr instr'], [LiveInstr instr']))
spillRead regSlotMap instr reg
| Just slot <- lookupUFM regSlotMap reg
= do (instr', nReg) <- patchInstr reg instr
modify $ \s -> s
{ stateSpillSL = addToUFM_C accSpillSL (stateSpillSL s) reg (reg, 0, 1) }
return ( instr'
, ( [LiveInstr (RELOAD slot nReg) Nothing]
, []) )
| otherwise = panic "RegSpill.spillRead: no slot defined for spilled reg"
-- | Add a SPILL meta instruction to store a value for an instruction that
-- writes to a vreg that is being spilled.
spillWrite
:: Instruction instr
=> UniqFM Int
-> instr
-> Reg
-> SpillM (instr, ([LiveInstr instr'], [LiveInstr instr']))
spillWrite regSlotMap instr reg
| Just slot <- lookupUFM regSlotMap reg
= do (instr', nReg) <- patchInstr reg instr
modify $ \s -> s
{ stateSpillSL = addToUFM_C accSpillSL (stateSpillSL s) reg (reg, 1, 0) }
return ( instr'
, ( []
, [LiveInstr (SPILL nReg slot) Nothing]))
| otherwise = panic "RegSpill.spillWrite: no slot defined for spilled reg"
-- | Add both RELOAD and SPILL meta instructions for an instruction that
-- both reads and writes to a vreg that is being spilled.
spillModify
:: Instruction instr
=> UniqFM Int
-> instr
-> Reg
-> SpillM (instr, ([LiveInstr instr'], [LiveInstr instr']))
spillModify regSlotMap instr reg
| Just slot <- lookupUFM regSlotMap reg
= do (instr', nReg) <- patchInstr reg instr
modify $ \s -> s
{ stateSpillSL = addToUFM_C accSpillSL (stateSpillSL s) reg (reg, 1, 1) }
return ( instr'
, ( [LiveInstr (RELOAD slot nReg) Nothing]
, [LiveInstr (SPILL nReg slot) Nothing]))
| otherwise = panic "RegSpill.spillModify: no slot defined for spilled reg"
-- | Rewrite uses of this virtual reg in an instr to use a different
-- virtual reg.
patchInstr
:: Instruction instr
=> Reg -> instr -> SpillM (instr, Reg)
patchInstr reg instr
= do nUnique <- newUnique
-- The register we're rewriting is suppoed to be virtual.
-- If it's not then something has gone horribly wrong.
let nReg
= case reg of
RegVirtual vr
-> RegVirtual (renameVirtualReg nUnique vr)
RegReal{}
-> panic "RegAlloc.Graph.Spill.patchIntr: not patching real reg"
let instr' = patchReg1 reg nReg instr
return (instr', nReg)
patchReg1
:: Instruction instr
=> Reg -> Reg -> instr -> instr
patchReg1 old new instr
= let patchF r
| r == old = new
| otherwise = r
in patchRegsOfInstr instr patchF
-- Spiller monad --------------------------------------------------------------
-- | State monad for the spill code generator.
type SpillM a
= State SpillS a
-- | Spill code generator state.
data SpillS
= SpillS
{ -- | Unique supply for generating fresh vregs.
stateUS :: UniqSupply
-- | Spilled vreg vs the number of times it was loaded, stored.
, stateSpillSL :: UniqFM (Reg, Int, Int) }
-- | Create a new spiller state.
initSpillS :: UniqSupply -> SpillS
initSpillS uniqueSupply
= SpillS
{ stateUS = uniqueSupply
, stateSpillSL = emptyUFM }
-- | Allocate a new unique in the spiller monad.
newUnique :: SpillM Unique
newUnique
= do us <- gets stateUS
case takeUniqFromSupply us of
(uniq, us')
-> do modify $ \s -> s { stateUS = us' }
return uniq
-- | Add a spill/reload count to a stats record for a register.
accSpillSL :: (Reg, Int, Int) -> (Reg, Int, Int) -> (Reg, Int, Int)
accSpillSL (r1, s1, l1) (_, s2, l2)
= (r1, s1 + s2, l1 + l2)
-- Spiller stats --------------------------------------------------------------
-- | Spiller statistics.
-- Tells us what registers were spilled.
data SpillStats
= SpillStats
{ spillStoreLoad :: UniqFM (Reg, Int, Int) }
-- | Extract spiller statistics from the spiller state.
makeSpillStats :: SpillS -> SpillStats
makeSpillStats s
= SpillStats
{ spillStoreLoad = stateSpillSL s }
instance Outputable SpillStats where
ppr stats
= pprUFM (spillStoreLoad stats)
(vcat . map (\(r, s, l) -> ppr r <+> int s <+> int l))
|
olsner/ghc
|
compiler/nativeGen/RegAlloc/Graph/Spill.hs
|
bsd-3-clause
| 13,426
| 0
| 16
| 4,674
| 2,451
| 1,262
| 1,189
| 225
| 2
|
{-# Language PatternGuards #-}
module Blub
( blub
, foo
, bar
) where
import Control.Applicative
(r, t, z)
import Data.Text hiding (isInfixOf)
import Ugah.Blub
( a
, b
, c
)
f :: Int -> Int
f = (+ 3)
r :: Int -> Int
r =
|
dan-t/hsimport
|
tests/inputFiles/SymbolTest35.hs
|
bsd-3-clause
| 248
| 1
| 6
| 76
| 89
| 56
| 33
| -1
| -1
|
module Graphics.Gnuplot.Private.Frame where
import qualified Graphics.Gnuplot.Private.Plot as Plot
import qualified Graphics.Gnuplot.Private.FrameOptionSet as OptionSet
import qualified Graphics.Gnuplot.Private.Display as Display
import qualified Graphics.Gnuplot.Private.Graph as Graph
import Data.Monoid (Monoid, mappend, )
data T graph =
Cons {
option :: OptionSet.T graph,
plot :: Plot.T graph
}
instance Graph.C graph => Display.C (T graph) where
toScript frame =
(Plot.optionsToScript $ option frame)
`mappend`
(Plot.toScript $ plot frame)
|
wavewave/gnuplot
|
src/Graphics/Gnuplot/Private/Frame.hs
|
bsd-3-clause
| 591
| 0
| 10
| 108
| 157
| 97
| 60
| 15
| 0
|
{-# LANGUAGE TypeFamilies, FlexibleContexts #-}
module Futhark.Representation.AST.Annotations
( Annotations (..)
, module Futhark.Representation.AST.RetType
)
where
import Futhark.Representation.AST.Syntax.Core
import Futhark.Representation.AST.RetType
import Futhark.Representation.AST.Attributes.Types
class (Show (LetAttr l), Show (ExpAttr l), Show (BodyAttr l), Show (FParamAttr l), Show (LParamAttr l), Show (RetType l), Show (Op l),
Eq (LetAttr l), Eq (ExpAttr l), Eq (BodyAttr l), Eq (FParamAttr l), Eq (LParamAttr l), Eq (RetType l), Eq (Op l),
Ord (LetAttr l), Ord (ExpAttr l), Ord (BodyAttr l), Ord (FParamAttr l), Ord (LParamAttr l), Ord (RetType l), Ord (Op l),
IsRetType (RetType l),
Typed (FParamAttr l), Typed (LParamAttr l), Typed (LetAttr l),
DeclTyped (FParamAttr l))
=> Annotations l where
-- | Annotation for every let-pattern element.
type LetAttr l :: *
type LetAttr l = Type
-- | Annotation for every expression.
type ExpAttr l :: *
type ExpAttr l = ()
-- | Annotation for every body.
type BodyAttr l :: *
type BodyAttr l = ()
-- | Annotation for every (non-lambda) function parameter.
type FParamAttr l :: *
type FParamAttr l = DeclType
-- | Annotation for every lambda function parameter.
type LParamAttr l :: *
type LParamAttr l = Type
-- | The type of expressions and function calls.
type RetType l :: *
type RetType l = ExtRetType
-- | Extensible operation.
type Op l :: *
type Op l = ()
|
CulpaBS/wbBach
|
src/Futhark/Representation/AST/Annotations.hs
|
bsd-3-clause
| 1,530
| 0
| 8
| 336
| 498
| 278
| 220
| 28
| 0
|
{-# OPTIONS -Wall #-}
module Claris (
module ClarisDef,
module ClarisTrans
) where
import ClarisDef
import ClarisTrans
|
nushio3/Paraiso
|
attic/Protoclaris/Claris.hs
|
bsd-3-clause
| 127
| 0
| 4
| 25
| 21
| 15
| 6
| 6
| 0
|
{-# OPTIONS -Wall -Werror #-}
module Main where
import Data.Time.Calendar.Julian
import Data.Time.Calendar.WeekDate
import Data.Time.Calendar
showers :: [(String,Day -> String)]
showers = [
("MJD",show . toModifiedJulianDay),
("Gregorian",showGregorian),
("Julian",showJulian),
("ISO 8601",showWeekDate)
]
days :: [Day]
days = [
fromGregorian 0 12 31,
fromJulian 1752 9 2,
fromGregorian 1752 9 14,
fromGregorian 2005 1 23
]
main :: IO ()
main = mapM_ (\day -> do
mapM_ (\(name,shower) -> putStr (" == " ++ name ++ " " ++ (shower day))) showers
putStrLn ""
) days
|
takano-akio/time
|
test/TestCalendars.hs
|
bsd-3-clause
| 582
| 20
| 17
| 102
| 241
| 137
| 104
| 22
| 1
|
module B1.Data.Direction
( Direction(..)
) where
data Direction = North | South | West | East
|
madjestic/b1
|
src/B1/Data/Direction.hs
|
bsd-3-clause
| 100
| 0
| 5
| 22
| 32
| 21
| 11
| 3
| 0
|
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE ExplicitNamespaces #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MonoLocalBinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE UndecidableInstances #-}
module Overflow
( prop_sequential_overflow
, prop_parallel_overflow
, prop_nparallel_overflow
) where
import Control.Concurrent
(threadDelay)
import Control.Concurrent.MVar
import Control.Monad
import Data.Int
import GHC.Generics
(Generic, Generic1)
import Prelude
import System.Random
(randomRIO)
import Test.QuickCheck
import Test.QuickCheck.Monadic
(monadicIO)
import Test.StateMachine
import Test.StateMachine.DotDrawing
import qualified Test.StateMachine.Types.Rank2 as Rank2
------------------------------------------------------------------------
-- The Model is a set of references of Int8. Command BackAndForth picks a random reference and adds a
-- constant number (in an atomic way) and then substract the same number (in an atomic way).
-- If there are enough threads (4 in this case) the result can overflow.
data Command r
= Create
| Check (Reference (Opaque (MVar Int8)) r)
| BackAndForth Int (Reference (Opaque (MVar Int8)) r)
deriving stock (Eq, Generic1)
deriving anyclass (Rank2.Functor, Rank2.Foldable, Rank2.Traversable, CommandNames)
deriving stock instance Show (Command Symbolic)
deriving stock instance Read (Command Symbolic)
deriving stock instance Show (Command Concrete)
data Response r
= Created (Reference (Opaque (MVar Int8)) r)
| IsNegative Bool
| Unit
deriving stock (Eq, Generic1)
deriving anyclass (Rank2.Foldable)
deriving stock instance Show (Response Symbolic)
deriving stock instance Read (Response Symbolic)
deriving stock instance Show (Response Concrete)
newtype Model r = Model [(Reference (Opaque (MVar Int8)) r, Int8)]
deriving stock (Generic, Show)
getVars :: Model r -> [Reference (Opaque (MVar Int8)) r]
getVars (Model ls) = fst <$> ls
instance ToExpr (Model Symbolic)
instance ToExpr (Model Concrete)
initModel :: Model r
initModel = Model []
transition :: Model r -> Command r -> Response r -> Model r
transition m@(Model model) cmd resp = case (cmd, resp) of
(Create, Created var) -> Model ((var, 0) : model)
(Check _, IsNegative _) -> m
(BackAndForth _ _, Unit) -> m
_ -> error "impossible to transition!"
precondition :: Model Symbolic -> Command Symbolic -> Logic
precondition m cmd = case cmd of
Create -> Top
Check var -> var `member` getVars m
BackAndForth _ var -> var `member` getVars m
postcondition :: Model Concrete -> Command Concrete -> Response Concrete -> Logic
postcondition _ cmd resp = case (cmd, resp) of
(Create, Created _) -> Top
(Check _, IsNegative bl) -> bl .== False
(BackAndForth _ _, Unit) -> Top
_ -> Bot
semantics :: Command Concrete -> IO (Response Concrete)
semantics cmd = case cmd of
Create -> Created <$> (reference . Opaque <$> newMVar 0)
Check var -> do
val <- readMVar (opaque var)
return $ IsNegative $ val < 0
BackAndForth n var -> do
modifyMVar_ (opaque var) $ \x -> return $ x + fromIntegral n
threadDelay =<< randomRIO (0, 5000)
modifyMVar_ (opaque var) $ \x -> return $ x - fromIntegral n
return Unit
mock :: Model Symbolic -> Command Symbolic -> GenSym (Response Symbolic)
mock _ cmd = case cmd of
Create -> Created <$> genSym
Check _var -> return $ IsNegative False
BackAndForth _ _ -> return $ Unit
generator :: Model Symbolic -> Maybe (Gen (Command Symbolic))
generator (Model []) = Just (return Create)
generator m = Just $ frequency
[ (1, return Create)
, (3, genBackAndForth m)
, (3, genCheck m)
]
genCheck :: Model Symbolic -> Gen (Command Symbolic)
genCheck m =
Check <$> elements (getVars m)
genBackAndForth :: Model Symbolic -> Gen (Command Symbolic)
genBackAndForth m = do
-- The upper limit here must have the property 2 * n < 128 <= 3 * n, so that
-- there is a counter example for >= 4 threads.
-- The lower limit only affects how fast a counterexample will be found.
n <- choose (30,60)
BackAndForth n <$> elements (getVars m)
shrinker :: Model Symbolic -> Command Symbolic -> [Command Symbolic]
shrinker _ (BackAndForth n var) = [ BackAndForth n' var | n' <- shrink n ]
shrinker _ _ = []
sm :: StateMachine Model Command IO Response
sm = StateMachine initModel transition precondition postcondition
Nothing generator shrinker semantics mock noCleanup
prop_sequential_overflow :: Property
prop_sequential_overflow = forAllCommands sm Nothing $ \cmds -> monadicIO $ do
(hist, _model, res) <- runCommands sm cmds
prettyCommands sm hist (res === Ok)
prop_parallel_overflow :: Property
prop_parallel_overflow = forAllParallelCommands sm Nothing $ \cmds -> monadicIO $
prettyParallelCommandsWithOpts cmds opts =<< runParallelCommands sm cmds
where opts = Just $ GraphOptions "overflow-test-output.png" Png
prop_nparallel_overflow :: Int -> Property
prop_nparallel_overflow np = forAllNParallelCommands sm np $ \cmds -> monadicIO $
prettyNParallelCommandsWithOpts cmds opts =<< runNParallelCommands sm cmds
where opts = Just $ GraphOptions ("overflow-" ++ show np ++ "-test-output.png") Png
|
advancedtelematic/quickcheck-state-machine-model
|
test/Overflow.hs
|
bsd-3-clause
| 5,766
| 0
| 13
| 1,367
| 1,645
| 846
| 799
| 121
| 4
|
{-| Implementation of the Ganeti Query2 node group queries.
-}
{-
Copyright (C) 2012, 2013 Google Inc.
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 Ganeti.Query.Group
(fieldsMap) where
import Ganeti.Config
import Ganeti.Objects
import Ganeti.Query.Language
import Ganeti.Query.Common
import Ganeti.Query.Types
import Ganeti.Utils (niceSort)
groupFields :: FieldList NodeGroup NoDataRuntime
groupFields =
[ (FieldDefinition "alloc_policy" "AllocPolicy" QFTText
"Allocation policy for group",
FieldSimple (rsNormal . groupAllocPolicy), QffNormal)
, (FieldDefinition "custom_diskparams" "CustomDiskParameters" QFTOther
"Custom disk parameters",
FieldSimple (rsNormal . groupDiskparams), QffNormal)
, (FieldDefinition "custom_ipolicy" "CustomInstancePolicy" QFTOther
"Custom instance policy limitations",
FieldSimple (rsNormal . groupIpolicy), QffNormal)
, (FieldDefinition "custom_ndparams" "CustomNDParams" QFTOther
"Custom node parameters",
FieldSimple (rsNormal . groupNdparams), QffNormal)
, (FieldDefinition "diskparams" "DiskParameters" QFTOther
"Disk parameters (merged)",
FieldConfig (\cfg -> rsNormal . getGroupDiskParams cfg), QffNormal)
, (FieldDefinition "ipolicy" "InstancePolicy" QFTOther
"Instance policy limitations (merged)",
FieldConfig (\cfg ng -> rsNormal (getGroupIpolicy cfg ng)), QffNormal)
, (FieldDefinition "name" "Group" QFTText "Group name",
FieldSimple (rsNormal . groupName), QffNormal)
, (FieldDefinition "ndparams" "NDParams" QFTOther "Node parameters",
FieldConfig (\cfg ng -> rsNormal (getGroupNdParams cfg ng)), QffNormal)
, (FieldDefinition "node_cnt" "Nodes" QFTNumber "Number of nodes",
FieldConfig (\cfg -> rsNormal . length . getGroupNodes cfg . groupUuid),
QffNormal)
, (FieldDefinition "node_list" "NodeList" QFTOther "List of nodes",
FieldConfig (\cfg -> rsNormal . map nodeName .
getGroupNodes cfg . groupUuid), QffNormal)
, (FieldDefinition "pinst_cnt" "Instances" QFTNumber
"Number of primary instances",
FieldConfig
(\cfg -> rsNormal . length . fst . getGroupInstances cfg . groupUuid),
QffNormal)
, (FieldDefinition "pinst_list" "InstanceList" QFTOther
"List of primary instances",
FieldConfig (\cfg -> rsNormal . niceSort . map instName . fst .
getGroupInstances cfg . groupUuid), QffNormal)
] ++
map buildNdParamField allNDParamFields ++
timeStampFields ++
uuidFields "Group" ++
serialFields "Group" ++
tagsFields
-- | The group fields map.
fieldsMap :: FieldMap NodeGroup NoDataRuntime
fieldsMap = fieldListToFieldMap groupFields
|
kawamuray/ganeti
|
src/Ganeti/Query/Group.hs
|
gpl-2.0
| 3,357
| 0
| 19
| 627
| 607
| 328
| 279
| 55
| 1
|
module Cypher (cypher) where
import Data.Bits
import qualified Data.ByteString.Lazy as B
import Types
cypher :: Word8 -> B.ByteString -> B.ByteString
cypher x = B.map go
where go 0 = 0
go 255 = 255
go n | n == x = n
| n == xor x 255 = n
| otherwise = xor x n
|
colinba/tip-toi-reveng
|
src/Cypher.hs
|
mit
| 320
| 0
| 11
| 117
| 124
| 64
| 60
| 11
| 3
|
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable,
FlexibleInstances, NoImplicitPrelude, TypeFamilies #-}
{-# OPTIONS -Wall #-}
-- | library for hydrodynamic variables.
-- the notations are specified to Builder Vec2 Int
-- at the moment. and non-hydro-relevant utility functions
-- are defined.
-- but this limitation will be lifted and modules will be separated
-- once everything is working well.
module Hydro(Real, Dim, B, BR, BGR, bind,
delta, kGamma, Hydrable(..), Hydro,
soundSpeed' ,
bindPrimitive, bindConserved) where
import qualified Algebra.Additive as Additive
import qualified Algebra.Field as Field
import qualified Algebra.Ring as Ring
import Control.Applicative
import Control.Monad hiding (forM, mapM)
import Data.Tensor.TypeLevel
import Data.Foldable
import Data.Traversable
import Language.Paraiso.Annotation (Annotation)
import Language.Paraiso.OM.Builder
import Language.Paraiso.OM.Realm
import Language.Paraiso.OM.Value as Val
import Language.Paraiso.Prelude
import NumericPrelude hiding ((&&), (||), (++), mapM)
----------------------------------------------------------------
-- Binder monad utilities
----------------------------------------------------------------
type Real = Double
type Dim = Vec2
type B a = Builder Dim Int Annotation a
type BR = B (Value TArray Real)
type BGR = B (Value TScalar Real)
--bind :: B a -> B (B a)
--bind = fmap return
----------------------------------------------------------------
-- Hydro utility functions.
----------------------------------------------------------------
delta :: (Eq a, Ring.C b) => a -> a -> b
delta i j = if i==j then Ring.one else Additive.zero
kGamma :: Field.C a => a
kGamma = fromRational' $ 5/3
-- | sound speed as a standalone function.
soundSpeed' :: BR -> BR -> BR
soundSpeed' dens0 pres0 = sqrt (kGamma * pres0 / dens0)
bindPrimitive :: BR -> Dim BR -> BR -> B (Hydro BR)
bindPrimitive density0 velocity0 pressure0 =
bindHydro $ PrimitiveVar density0 velocity0 pressure0
bindConserved :: BR -> Dim BR -> BR -> B (Hydro BR)
bindConserved density0 momentum0 energy0 =
bindHydro $ ConservedVar density0 momentum0 energy0
bindHydro :: (Hydrable a) => a -> B (Hydro BR)
bindHydro x = do
densityBound <- bind $ density x
velocityBound <- mapM bind $ velocity x
pressureBound <- bind $ pressure x
momentumBound <- mapM bind $ momentum x
energyBound <- bind $ energy x
enthalpyBound <- bind $ enthalpy x
densityFluxBound <- mapM bind $ densityFlux x
momentumFluxBound <- mapM (mapM bind) $ momentumFlux x
energyFluxBound <- mapM bind $ energyFlux x
soundSpeedBound <- bind $ soundSpeed x
kineticEnergyBound <- bind $ kineticEnergy x
internalEnergyBound <- bind $ internalEnergy x
return Hydro{
densityHydro = densityBound,
velocityHydro = velocityBound,
pressureHydro = pressureBound,
momentumHydro = momentumBound,
energyHydro = energyBound,
enthalpyHydro = enthalpyBound,
densityFluxHydro = densityFluxBound,
momentumFluxHydro = momentumFluxBound,
energyFluxHydro = energyFluxBound,
soundSpeedHydro = soundSpeedBound,
kineticEnergyHydro = kineticEnergyBound,
internalEnergyHydro = internalEnergyBound
}
class Hydrable a where
density :: a -> BR
velocity :: a -> Dim BR
velocity x =
compose (\i -> momentum x !i / density x)
pressure :: a -> BR
pressure x = (kGamma-1) * internalEnergy x
momentum :: a -> Dim BR
momentum x =
compose (\i -> density x * velocity x !i)
energy :: a -> BR
energy x = kineticEnergy x + 1/(kGamma-1) * pressure x
enthalpy :: a -> BR
enthalpy x = energy x + pressure x
densityFlux :: a -> Dim BR
densityFlux x = momentum x
momentumFlux :: a -> Dim (Dim BR)
momentumFlux x =
compose (\i -> compose (\j ->
momentum x !i * velocity x !j + pressure x * delta i j))
energyFlux :: a -> Dim BR
energyFlux x =
compose (\i -> enthalpy x * velocity x !i)
soundSpeed :: a -> BR
soundSpeed x = soundSpeed' (density x) (pressure x)
kineticEnergy :: a -> BR
kineticEnergy x = 0.5 * contract (\i -> velocity x !i * momentum x !i)
internalEnergy :: a -> BR
internalEnergy x = energy x - kineticEnergy x
data Hydro a = Hydro
{densityHydro::a, velocityHydro::Dim a, pressureHydro::a,
momentumHydro::Dim a, energyHydro::a, enthalpyHydro::a,
densityFluxHydro::Dim a, momentumFluxHydro::Dim (Dim a),
energyFluxHydro::Dim a, soundSpeedHydro::a,
kineticEnergyHydro::a, internalEnergyHydro::a}
deriving (Functor, Foldable, Traversable)
instance Hydrable (Hydro BR) where
density = densityHydro; velocity = velocityHydro; pressure = pressureHydro;
momentum = momentumHydro; energy = energyHydro; enthalpy = enthalpyHydro;
densityFlux = densityFluxHydro; momentumFlux = momentumFluxHydro;
energyFlux = energyFluxHydro; soundSpeed = soundSpeedHydro;
kineticEnergy = kineticEnergyHydro; internalEnergy = internalEnergyHydro;
instance Applicative Hydro where
pure x = Hydro
{densityHydro = x, velocityHydro = pure x, pressureHydro = x,
momentumHydro = pure x, energyHydro = x, enthalpyHydro = x,
densityFluxHydro = pure x, momentumFluxHydro = pure (pure x),
energyFluxHydro = pure x, soundSpeedHydro = x,
kineticEnergyHydro = x, internalEnergyHydro = x}
hf <*> hx = Hydro
{densityHydro = densityHydro hf $ densityHydro hx,
pressureHydro = pressureHydro hf $ pressureHydro hx,
energyHydro = energyHydro hf $ energyHydro hx,
enthalpyHydro = enthalpyHydro hf $ enthalpyHydro hx,
soundSpeedHydro = soundSpeedHydro hf $ soundSpeedHydro hx,
kineticEnergyHydro = kineticEnergyHydro hf $ kineticEnergyHydro hx,
internalEnergyHydro = internalEnergyHydro hf $ internalEnergyHydro hx,
velocityHydro = velocityHydro hf <*> velocityHydro hx,
momentumHydro = momentumHydro hf <*> momentumHydro hx,
densityFluxHydro = densityFluxHydro hf <*> densityFluxHydro hx,
energyFluxHydro = energyFluxHydro hf <*> energyFluxHydro hx,
momentumFluxHydro =
compose(\i -> compose(\j -> (momentumFluxHydro hf!i!j)
(momentumFluxHydro hx!i!j)))
-- in other words,
-- (<*>)((<*>) <$> momentumFluxHydro hf) $ momentumFluxHydro hx
}
data PrimitiveVar = PrimitiveVar
{densityPrim::BR, velocityPrim::Dim BR, pressurePrim::BR}
instance Hydrable PrimitiveVar where
density = densityPrim; velocity = velocityPrim; pressure = pressurePrim
data ConservedVar = ConservedVar
{densityCsvd::BR, momentumCsvd::Dim BR, energyCsvd::BR}
instance Hydrable ConservedVar where
density = densityCsvd; momentum = momentumCsvd; energy = energyCsvd
|
drmaruyama/Paraiso
|
examples/Hydro/Hydro.hs
|
bsd-3-clause
| 7,029
| 0
| 18
| 1,608
| 1,923
| 1,047
| 876
| 137
| 2
|
--
-- Copyright (c) 2011 Citrix Systems, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
{-# LANGUAGE FlexibleInstances,UndecidableInstances #-}
module Tools.Log where
import Control.Monad
import Control.Monad.Trans
import qualified Control.Exception as E
import System.Posix.Syslog
import System.Posix.IO
class Log m where
debug :: String -> m ()
warn :: String -> m ()
fatal :: String -> m ()
info :: String -> m ()
instance (MonadIO m) => Log m where
debug = liftIO . syslog Debug
warn = liftIO . syslog Warning
fatal = liftIO . syslog Error
info = liftIO . syslog Info
-- Run the specified IO action logging stdout/stderr to the specified logfile
withStdOutLog :: FilePath -> IO a -> IO a
withStdOutLog logfile f =
do logfd <- openlog
nullfd <- openDevNull ReadOnly defaultFileFlags
dupTo nullfd stdInput
dupTo logfd stdOutput
dupTo stdOutput stdError
closeFd logfd
closeFd nullfd
f
where
o_creat = Just 1 --openFd treats (Just x) as O_CREAT
openlog =
do r <- E.try $ openFd logfile WriteOnly o_creat $ defaultFileFlags { trunc = True }
case r of
Right fd -> return fd
Left (ex :: E.SomeException) -> openDevNull WriteOnly $ defaultFileFlags { append = True }
openDevNull mode flags =
do r <- E.try $ openFd "/dev/null" mode Nothing flags
case r of
Right fd -> return fd
Left (ex :: E.SomeException) -> error "could not open /dev/null"
|
jean-edouard/manager
|
disksync/Tools/Log.hs
|
gpl-2.0
| 2,242
| 0
| 15
| 575
| 445
| 228
| 217
| -1
| -1
|
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.UserHooks
-- Copyright : Isaac Jones 2003-2005
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This defines the API that @Setup.hs@ scripts can use to customise the way
-- the build works. This module just defines the 'UserHooks' type. The
-- predefined sets of hooks that implement the @Simple@, @Make@ and @Configure@
-- build systems are defined in "Distribution.Simple". The 'UserHooks' is a big
-- record of functions. There are 3 for each action, a pre, post and the action
-- itself. There are few other miscellaneous hooks, ones to extend the set of
-- programs and preprocessors and one to override the function used to read the
-- @.cabal@ file.
--
-- This hooks type is widely agreed to not be the right solution. Partly this
-- is because changes to it usually break custom @Setup.hs@ files and yet many
-- internal code changes do require changes to the hooks. For example we cannot
-- pass any extra parameters to most of the functions that implement the
-- various phases because it would involve changing the types of the
-- corresponding hook. At some point it will have to be replaced.
module Distribution.Simple.UserHooks (
UserHooks(..), Args,
emptyUserHooks,
) where
import Distribution.PackageDescription
import Distribution.Simple.Program
import Distribution.Simple.Command
import Distribution.Simple.PreProcess
import Distribution.Simple.Setup
import Distribution.Simple.LocalBuildInfo
type Args = [String]
-- | Hooks allow authors to add specific functionality before and after a
-- command is run, and also to specify additional preprocessors.
--
-- * WARNING: The hooks interface is under rather constant flux as we try to
-- understand users needs. Setup files that depend on this interface may
-- break in future releases.
data UserHooks = UserHooks {
-- | Used for @.\/setup test@
runTests :: Args -> Bool -> PackageDescription -> LocalBuildInfo -> IO (),
-- | Read the description file
readDesc :: IO (Maybe GenericPackageDescription),
-- | Custom preprocessors in addition to and overriding 'knownSuffixHandlers'.
hookedPreProcessors :: [ PPSuffixHandler ],
-- | These programs are detected at configure time. Arguments for them are
-- added to the configure command.
hookedPrograms :: [Program],
-- |Hook to run before configure command
preConf :: Args -> ConfigFlags -> IO HookedBuildInfo,
-- |Over-ride this hook to get different behavior during configure.
confHook :: (GenericPackageDescription, HookedBuildInfo)
-> ConfigFlags -> IO LocalBuildInfo,
-- |Hook to run after configure command
postConf :: Args -> ConfigFlags -> PackageDescription -> LocalBuildInfo -> IO (),
-- |Hook to run before build command. Second arg indicates verbosity level.
preBuild :: Args -> BuildFlags -> IO HookedBuildInfo,
-- |Over-ride this hook to get different behavior during build.
buildHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> BuildFlags -> IO (),
-- |Hook to run after build command. Second arg indicates verbosity level.
postBuild :: Args -> BuildFlags -> PackageDescription -> LocalBuildInfo -> IO (),
-- |Hook to run before repl command. Second arg indicates verbosity level.
preRepl :: Args -> ReplFlags -> IO HookedBuildInfo,
-- |Over-ride this hook to get different behavior during interpretation.
replHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> ReplFlags -> [String] -> IO (),
-- |Hook to run after repl command. Second arg indicates verbosity level.
postRepl :: Args -> ReplFlags -> PackageDescription -> LocalBuildInfo -> IO (),
-- |Hook to run before clean command. Second arg indicates verbosity level.
preClean :: Args -> CleanFlags -> IO HookedBuildInfo,
-- |Over-ride this hook to get different behavior during clean.
cleanHook :: PackageDescription -> () -> UserHooks -> CleanFlags -> IO (),
-- |Hook to run after clean command. Second arg indicates verbosity level.
postClean :: Args -> CleanFlags -> PackageDescription -> () -> IO (),
-- |Hook to run before copy command
preCopy :: Args -> CopyFlags -> IO HookedBuildInfo,
-- |Over-ride this hook to get different behavior during copy.
copyHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> CopyFlags -> IO (),
-- |Hook to run after copy command
postCopy :: Args -> CopyFlags -> PackageDescription -> LocalBuildInfo -> IO (),
-- |Hook to run before install command
preInst :: Args -> InstallFlags -> IO HookedBuildInfo,
-- |Over-ride this hook to get different behavior during install.
instHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> InstallFlags -> IO (),
-- |Hook to run after install command. postInst should be run
-- on the target, not on the build machine.
postInst :: Args -> InstallFlags -> PackageDescription -> LocalBuildInfo -> IO (),
-- |Hook to run before sdist command. Second arg indicates verbosity level.
preSDist :: Args -> SDistFlags -> IO HookedBuildInfo,
-- |Over-ride this hook to get different behavior during sdist.
sDistHook :: PackageDescription -> Maybe LocalBuildInfo -> UserHooks -> SDistFlags -> IO (),
-- |Hook to run after sdist command. Second arg indicates verbosity level.
postSDist :: Args -> SDistFlags -> PackageDescription -> Maybe LocalBuildInfo -> IO (),
-- |Hook to run before register command
preReg :: Args -> RegisterFlags -> IO HookedBuildInfo,
-- |Over-ride this hook to get different behavior during registration.
regHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> RegisterFlags -> IO (),
-- |Hook to run after register command
postReg :: Args -> RegisterFlags -> PackageDescription -> LocalBuildInfo -> IO (),
-- |Hook to run before unregister command
preUnreg :: Args -> RegisterFlags -> IO HookedBuildInfo,
-- |Over-ride this hook to get different behavior during unregistration.
unregHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> RegisterFlags -> IO (),
-- |Hook to run after unregister command
postUnreg :: Args -> RegisterFlags -> PackageDescription -> LocalBuildInfo -> IO (),
-- |Hook to run before hscolour command. Second arg indicates verbosity level.
preHscolour :: Args -> HscolourFlags -> IO HookedBuildInfo,
-- |Over-ride this hook to get different behavior during hscolour.
hscolourHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> HscolourFlags -> IO (),
-- |Hook to run after hscolour command. Second arg indicates verbosity level.
postHscolour :: Args -> HscolourFlags -> PackageDescription -> LocalBuildInfo -> IO (),
-- |Hook to run before haddock command. Second arg indicates verbosity level.
preHaddock :: Args -> HaddockFlags -> IO HookedBuildInfo,
-- |Over-ride this hook to get different behavior during haddock.
haddockHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> HaddockFlags -> IO (),
-- |Hook to run after haddock command. Second arg indicates verbosity level.
postHaddock :: Args -> HaddockFlags -> PackageDescription -> LocalBuildInfo -> IO (),
-- |Hook to run before test command.
preTest :: Args -> TestFlags -> IO HookedBuildInfo,
-- |Over-ride this hook to get different behavior during test.
testHook :: Args -> PackageDescription -> LocalBuildInfo -> UserHooks -> TestFlags -> IO (),
-- |Hook to run after test command.
postTest :: Args -> TestFlags -> PackageDescription -> LocalBuildInfo -> IO (),
-- |Hook to run before bench command.
preBench :: Args -> BenchmarkFlags -> IO HookedBuildInfo,
-- |Over-ride this hook to get different behavior during bench.
benchHook :: Args -> PackageDescription -> LocalBuildInfo -> UserHooks -> BenchmarkFlags -> IO (),
-- |Hook to run after bench command.
postBench :: Args -> BenchmarkFlags -> PackageDescription -> LocalBuildInfo -> IO ()
}
{-# DEPRECATED runTests "Please use the new testing interface instead!" #-}
-- |Empty 'UserHooks' which do nothing.
emptyUserHooks :: UserHooks
emptyUserHooks
= UserHooks {
runTests = ru,
readDesc = return Nothing,
hookedPreProcessors = [],
hookedPrograms = [],
preConf = rn,
confHook = (\_ _ -> return (error "No local build info generated during configure. Over-ride empty configure hook.")),
postConf = ru,
preBuild = rn',
buildHook = ru,
postBuild = ru,
preRepl = \_ _ -> return emptyHookedBuildInfo,
replHook = \_ _ _ _ _ -> return (),
postRepl = ru,
preClean = rn,
cleanHook = ru,
postClean = ru,
preCopy = rn,
copyHook = ru,
postCopy = ru,
preInst = rn,
instHook = ru,
postInst = ru,
preSDist = rn,
sDistHook = ru,
postSDist = ru,
preReg = rn,
regHook = ru,
postReg = ru,
preUnreg = rn,
unregHook = ru,
postUnreg = ru,
preHscolour = rn,
hscolourHook = ru,
postHscolour = ru,
preHaddock = rn,
haddockHook = ru,
postHaddock = ru,
preTest = rn',
testHook = \_ -> ru,
postTest = ru,
preBench = rn',
benchHook = \_ -> ru,
postBench = ru
}
where rn args _ = noExtraFlags args >> return emptyHookedBuildInfo
rn' _ _ = return emptyHookedBuildInfo
ru _ _ _ _ = return ()
|
tolysz/prepare-ghcjs
|
spec-lts8/cabal/Cabal/Distribution/Simple/UserHooks.hs
|
bsd-3-clause
| 9,687
| 0
| 15
| 2,152
| 1,545
| 890
| 655
| 105
| 1
|
--------------------------------------------------------------------------------
-- | An item is a combination of some content and its 'Identifier'. This way, we
-- can still use the 'Identifier' to access metadata.
{-# LANGUAGE DeriveDataTypeable #-}
module Hakyll.Core.Item
( Item (..)
, itemSetBody
, withItemBody
) where
--------------------------------------------------------------------------------
import Control.Applicative ((<$>), (<*>))
import Data.Binary (Binary (..))
import Data.Foldable (Foldable (..))
import Data.Traversable (Traversable (..))
import Data.Typeable (Typeable)
import Prelude hiding (foldr)
--------------------------------------------------------------------------------
import Hakyll.Core.Compiler.Internal
import Hakyll.Core.Identifier
--------------------------------------------------------------------------------
data Item a = Item
{ itemIdentifier :: Identifier
, itemBody :: a
} deriving (Show, Typeable)
--------------------------------------------------------------------------------
instance Functor Item where
fmap f (Item i x) = Item i (f x)
--------------------------------------------------------------------------------
instance Foldable Item where
foldr f z (Item _ x) = f x z
--------------------------------------------------------------------------------
instance Traversable Item where
traverse f (Item i x) = Item i <$> f x
--------------------------------------------------------------------------------
instance Binary a => Binary (Item a) where
put (Item i x) = put i >> put x
get = Item <$> get <*> get
--------------------------------------------------------------------------------
itemSetBody :: a -> Item b -> Item a
itemSetBody x (Item i _) = Item i x
--------------------------------------------------------------------------------
-- | Perform a compiler action on the item body. This is the same as 'traverse',
-- but looks less intimidating.
--
-- > withItemBody = traverse
withItemBody :: (a -> Compiler b) -> Item a -> Compiler (Item b)
withItemBody = traverse
|
oldmanmike/hakyll
|
src/Hakyll/Core/Item.hs
|
bsd-3-clause
| 2,289
| 0
| 9
| 481
| 411
| 232
| 179
| 30
| 1
|
{-# LANGUAGE OverloadedStrings #-}
-- TODO this is a duplicate
module SpawnModel where
import GameInitModel(CarId)
import Data.Aeson ((.:), (.:?), decode, encode, (.=), object, FromJSON(..), ToJSON(..), Value(..))
import Control.Applicative ((<$>), (<*>))
import Control.Monad (liftM)
-- Spawn
data Spawn = Spawn {
msgType :: String,
dataVal :: CarId,
gameId :: String
} deriving (Show)
instance FromJSON Spawn where
parseJSON (Object v) =
Spawn <$>
(v .: "msgType") <*>
(v .: "data") <*>
(v .: "gameId")
parseSpawn json = (decode json :: Maybe Spawn)
|
nietaki/HWO-2014---the-What-What-What
|
other_languages/haskell/SpawnModel.hs
|
apache-2.0
| 595
| 0
| 10
| 124
| 203
| 126
| 77
| 18
| 1
|
module MultiModuleIn1 where
f :: [Int] -> Int
f ((y : ys))
= case ys of
ys@[] -> (head ys) + (head (tail ys))
ys@(b_1 : b_2) -> (head ys) + (head (tail ys))
f ((y : ys)) = (head ys) + (head (tail ys))
|
kmate/HaRe
|
old/testing/introCase/MultiModuleIn1AST.hs
|
bsd-3-clause
| 234
| 0
| 12
| 78
| 149
| 80
| 69
| 7
| 2
|
{-# LANGUAGE BangPatterns #-}
module Main where
import Control.DeepSeq
import Control.Exception (evaluate)
import Control.Monad.Trans (liftIO)
import Criterion.Config
import Criterion.Main
import Data.List (foldl')
import qualified Data.Map as M
import qualified LookupGE_Map as M
import Data.Maybe (fromMaybe)
import Prelude hiding (lookup)
main :: IO ()
main = do
defaultMainWith
defaultConfig
(liftIO . evaluate $ rnf [m_even, m_odd, m_large])
[b f | b <- benches, f <- funs1]
where
m_even = M.fromAscList elems_even :: M.Map Int Int
m_odd = M.fromAscList elems_odd :: M.Map Int Int
m_large = M.fromAscList elems_large :: M.Map Int Int
bound = 2^10
elems_even = zip evens evens
elems_odd = zip odds odds
elems_large = zip large large
evens = [2,4..bound]
odds = [1,3..bound]
large = [1,100..50*bound]
benches =
[ \(n,fun) -> bench (n++" present") $ nf (fge fun evens) m_even
, \(n,fun) -> bench (n++" absent") $ nf (fge fun evens) m_odd
, \(n,fun) -> bench (n++" far") $ nf (fge fun odds) m_large
, \(n,fun) -> bench (n++" !present") $ nf (fge2 fun evens) m_even
, \(n,fun) -> bench (n++" !absent") $ nf (fge2 fun evens) m_odd
, \(n,fun) -> bench (n++" !far") $ nf (fge2 fun odds) m_large
]
funs1 = [ ("GE split", M.lookupGE1)
, ("GE caseof", M.lookupGE2)
, ("GE Twan", M.lookupGE3)
, ("GE Milan", M.lookupGE4) ]
fge :: (Int -> M.Map Int Int -> Maybe (Int,Int)) -> [Int] -> M.Map Int Int -> (Int,Int)
fge fun xs m = foldl' (\n k -> fromMaybe n (fun k m)) (0,0) xs
-- forcing values inside tuples!
fge2 :: (Int -> M.Map Int Int -> Maybe (Int,Int)) -> [Int] -> M.Map Int Int -> (Int,Int)
fge2 fun xs m = foldl' (\n@(!_, !_) k -> fromMaybe n (fun k m)) (0,0) xs
|
DavidAlphaFox/ghc
|
libraries/containers/benchmarks/LookupGE/Map.hs
|
bsd-3-clause
| 1,870
| 0
| 12
| 493
| 826
| 455
| 371
| 43
| 1
|
module Types where
import Data.Time (UTCTime)
data RefreshMessage = RefreshNowM | RefreshEachM Int | RefreshTimeM
data SignalFromUI = RefreshEach Int
data SignalToUI =
Refreshing |
DoneRefreshing |
NewHeadline {title::String, link::String, date::UTCTime} |
Error String
|
singpolyma/haskades-headlines
|
src/Types.hs
|
isc
| 278
| 8
| 8
| 42
| 84
| 51
| 33
| 9
| 0
|
{-# LANGUAGE OverloadedStrings #-}
module Stock.Markdown
( encode
) where
import Data.List
import Data.Maybe
-- debug
import Control.Monad
import Debug.Trace
import Test.Hspec
-------------------- NEED TO REFACTORING
-------------------- INCOMPLETE
sample = "# SampleText\n\nHello, World\n\n+ Contents\n - Apple\n - Orange\n+ Other\n - Foo\n - Bar\n\nEnjoy!\n"
sample2 = "#Hello\nWorl"
sample3 = "#Hello\n- World\n-World?\n + World\n- Yes\n yes fooo!!\n\nFoo"
sample4 = "\n\n\n"
data MValue = MValue [MValue]
| MString String
| MCode String
| MHeader Int String
| MDisc { mdiscLevel :: Int, mdiscValue :: [MValue] }
| MDiscStr String
deriving (Show, Eq)
data MParser = MParser { mparserValues :: [MValue], mparserLeft :: String }
| MError String String
deriving (Show, Eq)
tp = "# unpi\n- List\n- Foobar\n + Unpee\n\nふぉお"
encode = toMD . toMValue
toMD (MValue vals) = concat $ map toMD vals
toMD (MString str) = str ++ "<br />"
toMD (MHeader lv val) = concat ["<h", show lv, ">", val, "</h", show lv, ">"]
toMD (MDisc lv vals) = concat ["<ul>", concat $ map toMD vals, "</ul>"]
toMD (MDiscStr val) = concat ["<li>", val, "</li>"]
toMValue :: String -> MValue
toMValue str = MValue $ mparserValues . parse . parser $ str
parser :: String -> MParser
parser = MParser []
parse :: MParser -> MParser
parse ps@(MParser vals str)
| str == [] = MParser (reverse vals) str
| head str == '\n' = parse . skipChar $ ps
| head str == '#' = parse . takeHeader $ ps
| head str `elem` ['-', '+', '*'] = parse . takeDiscs $ ps
| head str == ' ' = parse . skipChar $ ps
| otherwise = parse . takeStrLn $ ps
skipChar :: MParser -> MParser
skipChar (MParser vals str) = MParser vals (tail str)
takeStrLn :: MParser -> MParser
takeStrLn (MParser vals str) = MParser (mstring:vals) (drop (length string) str)
where string = takeWhile (/='\n') str
mstring = MString string
takeHeader :: MParser -> MParser
takeHeader (MParser vals str) = MParser (header:vals) left
where level = length $ takeWhile (=='#') str
content = dropWhile (\ch -> ch == '#' || ch == ' ') . takeWhile (/='\n') $ str
header = MHeader level content
left = dropWhile (/='\n') str
takeDiscs :: MParser -> MParser
takeDiscs (MParser vals str) = MParser ( (parseDiscs 1 discLines) :vals) left
where strLines = lines str
discLines = takeWhile isDisc $ strLines
left = concat $ drop (length discLines) strLines
isDisc :: String -> Bool
isDisc line = maybe False (\h -> h `elem` ['-','+','*']) headM
where headM = listToMaybe (dropWhile (==' ') . takeWhile (/= '\n') $ line)
parseDiscs :: Int -> [String] -> MValue
parseDiscs level strs = MDisc level (fold 0 [] False)
where disclevel line = (+1) $ (length . takeWhile (==' ') $ line) `div` 4
cutValue :: String -> MValue
cutValue line = let value = dropWhile (`elem` ['-','+','*',' ']) line
in MDiscStr value
nextSamelevel cursor = let next = listToMaybe $
filter (\(i, lv) -> lv == level && i > cursor) $ zip [0..] $ map disclevel strs
in maybe (length strs) fst next
fold :: Int -> [MValue] -> Bool -> [MValue]
fold cursor parsed inlower
| cursor == length strs = parsed
| otherwise = if disclevel (strs !! cursor) == level
then fold (cursor + 1) (parsed ++ [cutValue $ (strs !! cursor)]) False
else if inlower
then fold (cursor + 1) parsed False
else fold (cursor + 1)
(parsed ++ (parseDiscs (level+1)
(drop cursor $ take (nextSamelevel cursor) $ strs )):[]
) True
t = hspec spec
spec = do
describe "parseDiscs" $ do
it "parseDiscs" $ do
parseDiscs 1 ["- Fruits", " + Apple", " + Orange", "- Animal", " + Cat", " + Dog"]
`shouldBe` MDisc 1 [MDiscStr "Fruits", MDisc 2 [MDiscStr "Apple", MDiscStr "Orange"], MDiscStr "Animal"
,MDisc 2 [MDiscStr "Cat", MDiscStr "Dog"]]
describe "parse" $ do
sequence_ $ map (\(input, expected) -> do
it (input ++ " -> " ++ show expected) $ do
parse (parser input) `shouldBe` (MParser expected "")) cases
cases =
[("Hello, World", [MString "Hello, World"])
,(nl ["Hello", "World?"], [MString "Hello", MString "World?"])
,("# title", [MHeader 1 "title"])
,("## title", [MHeader 2 "title"])
,("### title", [MHeader 3 "title"])
,(nl ["# title", "content"], [MHeader 1 "title", MString "content"] )
,(nl ["# title", "content", "### title2"], [MHeader 1 "title", MString "content", MHeader 3 "title2"] )
,(nl ["- Apple","- Orange", "- Banana"], [MDisc 1 [MDiscStr "Apple",MDiscStr "Orange",MDiscStr "Banana"]])
,(nl ["- Fruits", " + Apple", " + Orange", "- Animal", " + Cat", " + Dog"],
[MDisc 1 [MDiscStr "Fruits", MDisc 2 [MDiscStr "Apple", MDiscStr "Orange"], MDiscStr "Animal"
,MDisc 2 [MDiscStr "Cat", MDiscStr "Dog"]]])
]
where nl = concat . intersperse "\n" :: [String] -> String
|
tattsun/stock
|
src/Stock/Markdown.hs
|
mit
| 5,435
| 0
| 22
| 1,598
| 1,931
| 1,028
| 903
| 105
| 3
|
{-# LANGUAGE DeriveDataTypeable #-}
-- | Module for accessing minified flot code (<http://www.flotcharts.org/>).
-- As an example:
--
-- > import qualified Language.Javascript.Flot as Flot
-- >
-- > main = do
-- > putStrLn $ "Flot version " ++ show Flot.version ++ " source:"
-- > putStrLn =<< readFile =<< Flot.file Flot.Flot
--
-- This package installs data files containing the Flot sources, which must be available at runtime.
-- If you want to produce an executable with no dependency on associated data files, you can use the
-- @file-embed@ library (<https://hackage.haskell.org/package/file-embed>):
--
-- > {-# LANGUAGE TemplateHaskell #-}
-- >
-- > import Data.FileEmbed
-- > import qualified Data.ByteString as BS
-- > import qualified Language.Javascript.Flot as Flot
-- > import Language.Haskell.TH.Syntax
-- >
-- > main = print flotContents
-- >
-- > flotContents :: BS.ByteString
-- > flotContents = $(embedFile =<< runIO (Flot.file Flot.Flot))
module Language.Javascript.Flot(
Flot(..), version, file
) where
import qualified Paths_js_flot as Paths
import Data.Version
import Data.Data
import Data.Char
-- | The Flot code to obtain. Use 'Flot' for the base system and the other values
-- for the various addins shipped with Flot.
data Flot
= Flot
| FlotCanvas
| FlotCategories
| FlotCrosshair
| FlotErrorbars
| FlotFillbetween
| FlotImage
| FlotNavigate
| FlotPie
| FlotResize
| FlotSelection
| FlotStack
| FlotSymbol
| FlotThreshold
| FlotTime
deriving (Eq,Ord,Show,Read,Bounded,Enum,Data,Typeable)
-- | A local file containing the minified Flot code for 'version'.
file :: Flot -> IO FilePath
file = Paths.getDataFileName . name
name :: Flot -> String
name Flot = "jquery.flot.min.js"
name x = "jquery.flot." ++ map toLower (drop 4 $ show x) ++ ".min.js"
-- | The version of Flot provided by this package. Not necessarily the version of this package,
-- but the versions will match in the first three digits.
version :: Version
version = Version (take 3 $ versionBranch Paths.version) []
|
ndmitchell/js-flot
|
src/Language/Javascript/Flot.hs
|
mit
| 2,107
| 0
| 10
| 412
| 263
| 162
| 101
| 31
| 1
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.ByteString.Internal
import Data.Either.Combinators
import Data.Tape
import Language.BrainHask
import Options.Applicative
import System.Directory
import System.IO
data Options = Options
{ _input :: String
, _optimize :: Bool
, _ast :: Bool }
options :: Parser Options
options = Options
<$> argument str (metavar "FILENAME")
<*> switch (short 'o' <> long "optimize" <> help "Try to optimize")
<*> switch (short 'a' <> long "ast" <> help "Print the AST")
readInput :: FilePath -> IO (Either String String)
readInput fn = doesFileExist fn >>= \b ->
if b then Right <$> readFile fn
else return $ Left $ fn ++ " does not exist"
initMachine :: IO Machine
initMachine = do
hSetBuffering stdin NoBuffering
hSetBuffering stdout NoBuffering
return $ Machine machineMemory machineIO
where
machineMemory = tapeOf 0
machineIO = MachineIO (putStr "\n> " >> (c2w <$> getChar)) (putStr . map w2c)
main :: IO ()
main = do
(Options input o a) <- execParser opts
machine <- initMachine
string <- readInput input
let program = string >>= mapLeft show . parseBF
go o a machine program
where
opts = info ( helper <*> options )
( fullDesc <> progDesc "Brainfuck interpreter" )
go _ _ (Machine _ (MachineIO _ wf)) ( Left errorMsg ) = wf $ map c2w errorMsg
go o a machine@(Machine _ (MachineIO _ wf)) ( Right program )
| o && a = wf . map c2w . show $ optimize program
| o = interpretBF machine $ optimize program
| a = wf . map c2w . show $ program
| otherwise = interpretBF machine program
|
damianfral/BrainHask
|
src/Main.hs
|
mit
| 1,983
| 0
| 12
| 634
| 591
| 293
| 298
| 47
| 2
|
module ArbitraryIdentity where
import Test.QuickCheck
data Identity a =
Identity a
deriving (Eq, Show)
identityGen :: Arbitrary a => Gen (Identity a)
identityGen = do
a <- arbitrary
return (Identity a)
instance Arbitrary a => Arbitrary (Identity a) where
arbitrary = identityGen
identityGenInt :: Gen (Identity Int)
identityGenInt = identityGen
|
NickAger/LearningHaskell
|
HaskellProgrammingFromFirstPrinciples/Chapter14/Arbitrary/src/ArbitraryIdentity.hs
|
mit
| 360
| 0
| 9
| 65
| 120
| 62
| 58
| 13
| 1
|
module Y2020.M08.D21.Solution where
import Y2020.M08.D19.Solution (dicts)
import Y2020.M08.D20.Solution (allWords)
{--
Gimme a hint? ... or two?
So, we have the words (all 1-word words, so: NO NEW ZEALAND FOR MEEEEH!) *cries*
*ahem*
So, we have the words, we have the word lengths (from the day before).
Now.
What happens when we get a hint, or two, or some?
Say you get a hint, for example: "The fourth letter is an 'e'."
How do you model hints? How do you incorporate hints into choosing your words?
Today's Haskell problem: model hints and use them to narrow your word-search.
--}
import Prelude hiding (Word)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
type Letter = Char
type Index = Int
type Length = Int
data Hint = Hint (Index, Letter)
type Word = String
type WordList = Map Int (Set Word)
wordLengths :: Set Word -> WordList
wordLengths = foldl (alterer f) Map.empty
where f Nothing = Set.singleton
f (Just set) = flip Set.insert set
alterer f map val =
let len = length val
base = Map.lookup len map
in Map.insert len (f base val) map
{--
>>> Map.map length . wordLengths <$> allWords dicts
{(1,26),(2,139),(3,1294),(4,4994),(5,9972),(6,17462),(7,23713),(8,29842),...}
... it'd be nice if the printer curtailed long evaluations, ... like most
prolog systems do. #justsayin
--}
chooseFrom :: Length -> [Hint] -> WordList -> Set Word
chooseFrom len hints = maybe Set.empty (cf' hints) . Map.lookup len
cf' :: [Hint] -> Set Word -> Set Word
cf' hints = Set.filter (all' (map hintFilter hints))
hintFilter :: Hint -> Word -> Bool
hintFilter (Hint (pos, letter)) = (== letter) . (!! pos)
all' :: [a -> Bool] -> a -> Bool -- so: a 'dual' of `all`
all' [] _ = True
all' (h:t) wrd = h wrd && all' t wrd
{--
And we've already loaded our word lists from the solution to
Y2020.M08.D19.Exercise
What do you get for chooseFrom 5 [] <$> wordList?
What do you get from chooseFrom 5 [Hint (3,'e')] <$> wordList?
What do you get from chooseFrom 5 [Hint (3,'e'), Hint (1,'l')] <$> wordList?
where wordList = wordLengths <$> allWords dicts
>>> length <$> wordList
24
>>> chooseFrom 5 [] <$> wordList
{"aalii","aaron","abaca","aback","abaff","abaft","abama","abase",...}
>>> length it
9934
>>> chooseFrom 5 [Hint (3,'e')] <$> wordList
{"abbey","abies","abler","abner","abnet","abret","achen","acher",...}
>>> length it
1335
>>> chooseFrom 5 [Hint (3,'e'), Hint(1,'l')] <$> wordList
{"albee","alces","alder","alfet","alien","alkes","allen",...}
>>> length it
53
--}
|
geophf/1HaskellADay
|
exercises/HAD/Y2020/M08/D21/Solution.hs
|
mit
| 2,614
| 0
| 12
| 495
| 465
| 255
| 210
| 31
| 2
|
{-# htermination genericLength :: [b] -> (Ratio Int) #-}
import List
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/List_genericLength_4.hs
|
mit
| 69
| 0
| 3
| 11
| 5
| 3
| 2
| 1
| 0
|
{-# OPTIONS_HADDOCK hide #-}
module Graphics.Gloss.Internals.Render.Common where
import Graphics.Gloss.Internals.Interface.Backend
import Graphics.Rendering.OpenGL (($=))
import qualified Graphics.Rendering.OpenGL.GL as GL
import Unsafe.Coerce
import Data.IORef
-- | The OpenGL library doesn't seem to provide a nice way convert
-- a Float to a GLfloat, even though they're the same thing
-- under the covers.
--
-- Using realToFrac is too slow, as it doesn't get fused in at
-- least GHC 6.12.1
--
gf :: Float -> GL.GLfloat
{-# INLINE gf #-}
gf x = unsafeCoerce x
-- | Used for similar reasons to above
gsizei :: Int -> GL.GLsizei
{-# INLINE gsizei #-}
gsizei x = unsafeCoerce x
-- | Perform a rendering action setting up the coords first
renderAction
:: Backend a
=> IORef a
-> IO ()
-> IO ()
renderAction backendRef action
= do
GL.matrixMode $= GL.Projection
GL.preservingMatrix
$ do
-- setup the co-ordinate system
GL.loadIdentity
(sizeX, sizeY) <- getWindowDimensions backendRef
let (sx, sy) = (fromIntegral sizeX / 2, fromIntegral sizeY / 2)
GL.ortho (-sx) sx (-sy) sy 0 (-100)
-- draw the world
GL.matrixMode $= GL.Modelview 0
action
GL.matrixMode $= GL.Projection
GL.matrixMode $= GL.Modelview 0
|
gscalzo/HaskellTheHardWay
|
gloss-try/gloss-master/gloss/Graphics/Gloss/Internals/Render/Common.hs
|
mit
| 1,254
| 32
| 8
| 236
| 307
| 178
| 129
| 31
| 1
|
myProduct :: [Integer] -> Integer
myProduct [] = 0
myProduct (x:xs) = x * product(xs)
myProduct' :: [Integer] -> Integer
myProduct' [] = 0
myProduct' l = foldr(*) 1 l
myStar :: (Num a, Eq a) => a -> a -> a
myStar 0 _ = 0
myStar _ 0 = 0
myStar x y = x * y
myProduct'' :: [Integer] -> Integer
myProduct'' = foldr(myStar) 1
|
gscalzo/HaskellTheHardWay
|
scala/3_7.hs
|
mit
| 325
| 0
| 7
| 72
| 174
| 92
| 82
| 12
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Frinfo.Config where
import qualified Data.Text as T
type Color = T.Text
headphoneColor :: Color
headphoneColor = "#ea8b2a"
emailColor :: Color
emailColor = "#ffffff"
ramColor :: Color
ramColor = "#e86f0c"
cpuColor :: Color
cpuColor = "#487ff7"
clockColor :: Color
clockColor = "#ffbd55"
unameColor :: Color
unameColor = "#6eadd8"
uptimeColor :: Color
uptimeColor = "#05aa8b"
upColor :: Color
upColor = "#cc0000"
songIcon :: T.Text
songIcon = "/home/arguggi/dotfiles/icons/xbm8x8/phones.xbm"
emailIcon :: T.Text
emailIcon = "/home/arguggi/dotfiles/icons/stlarch/mail7.xbm"
upSpeedIcon :: T.Text
upSpeedIcon = "/home/arguggi/dotfiles/icons/xbm8x8/net_up_03.xbm"
downSpeedIcon :: T.Text
downSpeedIcon = "/home/arguggi/dotfiles/icons/xbm8x8/net_down_03.xbm"
unameIcon :: T.Text
unameIcon = "/home/arguggi/dotfiles/icons/xbm8x8/arch_10x10.xbm"
-- | Default text for an empty MVar in 'Frinfo.Scripts.getSong'
noSongPlaying :: T.Text
noSongPlaying = "No Song Playing"
-- | Default text for an empty MVar in 'Frinfo.Scripts.getUnreadEmails'
noEmails :: T.Text
noEmails = " 0"
-- | Folder where offlineimap saves all the emails
mailFolder :: T.Text
mailFolder = "/home/arguggi/Mail/"
-- | Network interface stats file
netStatFile :: String
netStatFile = "/proc/net/dev"
-- | Cpu activity stats file
cpuStatFile :: String
cpuStatFile = "/proc/stat"
-- | Ram stats file
ramStatFile :: String
ramStatFile = "/proc/meminfo"
-- | Cpu fan rpm file
rpmStatFile :: String
rpmStatFile = "/sys/class/hwmon/hwmon0/fan1_input"
-- | Log exceptions to this file
crashFileName :: String
crashFileName = "frinfo.log"
-- | Battery file
batteryFile :: String
batteryFile = "/sys/class/power_supply/BAT0/capacity"
-- | CPU Temp file
cpuTempFile :: String
--cpuTempFile = "/sys/class/thermal/thermal_zone0/temp"
cpuTempFile = "/sys/bus/platform/devices/it87.656/hwmon/hwmon0/temp1_input"
|
Arguggi/Frinfo
|
src/Frinfo/Config.hs
|
mit
| 1,927
| 0
| 5
| 254
| 280
| 173
| 107
| 50
| 1
|
{-# LANGUAGE ForeignFunctionInterface #-}
module Commands.Backends.OSX.Bindings.Raw where
import Commands.Backends.OSX.Types
import Foreign.C.String (CString)
import Foreign.C.Types (CUShort (..), CULLong (..)) -- https://ghc.haskell.org/trac/ghc/ticket/5610
-- import Data.Word (Word32)
foreign import ccall safe "objc_actor.h currentApplicationPath" objc_currentApplicationPath
:: IO CString
foreign import ccall safe "objc_actor.h pressKey" objc_pressKey
:: CGEventFlags
-> CGKeyCode
-> IO ()
-- foreign import ccall safe "objc_actor.h clickMouse" objc_clickMouse
-- :: CGEventType
-- -> CGEventFlags
-- -> CGEventType
-- -> CGMouseButton
-- -> Word32
-- -> IO ()
foreign import ccall safe "objc_actor.h getClipboard" objc_getClipboard
:: IO CString
foreign import ccall safe "objc_actor.h setClipboard" objc_setClipboard
:: CString
-> IO ()
foreign import ccall safe "objc_actor.h openURL" objc_openURL
:: CString
-> IO ()
|
sboosali/commands-backends-osx9
|
sources/Commands/Backends/OSX/Bindings/Raw.hs
|
mit
| 1,011
| 0
| 9
| 193
| 166
| 100
| 66
| 19
| 0
|
module Y2018.M10.D24.Solution where
import Data.Char
import Control.Monad.State
{--
Today, let's go a little Turing Tarpit.
https://esolangs.org/wiki/Brainfuck
Create an interpreter (or compiler, if you prefer) for the following BF
instructions:
>
<
+
-
.
[
]
See the above link for the meaning of these instructions. Also, I'm ignoring
input for now, because I just don't like it. Modify the memory directly instead
of input.
You need a memory pointer, right? Do you need a program counter?
Let's build an interpreter today with the non-looping elements and look
at building a compiler tomorrow, including the looping elements.
--}
data BFState = BF { ptr :: Int, mem :: [Int] }
instance Show BFState where
show (BF idx mem) = "BF { @" ++ show idx ++ ", " ++ show (take 10 mem) ++ " }"
-- of course, you can't see the machine's state. That's cheating.
-- given the initial state of the machine to be this:
start :: BFState
start = BF 0 ([72,101,108,108,111,44,32,119,111,114,108,100,33,10] ++ repeat 0)
-- what does the following bf program do?
type BFProgram = String
bfprogram1 :: BFProgram
bfprogram1 = ".>.>.>.>.>.>.>.>.>.>.>.>.>"
-- write a bf program that zeros out an initial state up to the first zero
-- encountered, ... given that the memory cell under ptr is not zero
bfprogram2 :: BFProgram
bfprogram2 = "----------"
-- Of course, the loop falls through if the pointer is at a 0-cell, anyway.
ten :: BFState
ten = BF 0 (10:repeat 0)
-- what is the state of ten after running it through bfprogram2?
-- so, of course, we need an interpreter (or a compiler) that runs bf programs:
bfinterpreter :: BFProgram -> StateT BFState IO ()
bfinterpreter program = mapM_ interpret program >> lift (putStrLn "")
-- Maybe we'll look at factorial tomorrow? Maybe by writing a program that
-- writes BF programs?
type BF_OP_CODE = Char
interpret :: BF_OP_CODE -> StateT BFState IO ()
interpret '.' = get >>= \st@(BF i lst) -> lift (putChar (chr (head (drop i lst))))
interpret '<' = get >>= \ (BF idx lst) -> put $ BF ((if idx == 0 then id else pred) idx) lst
interpret '>' = get >>= \ (BF idx lst) -> put $ BF (succ idx) lst
interpret '+' = get >>= \ (BF idx (h:t)) -> put $ BF idx ((if h == 255 then id else succ) h:t)
interpret '-' = get >>= \(BF idx (h:t)) -> put $ BF idx ((if h ==0 then id else pred) h:t)
{--
>>> runStateT (bfinterpreter bfprogram1) start
Hello, world!
((),BF { @13, [72,101,108,108,111,44,32,119,111,114] })
>>> runStateT (bfinterpreter bfprogram2) start
((),BF { @0, [62,101,108,108,111,44,32,119,111,114] })
>>> runStateT (bfinterpreter bfprogram2) ten
((),BF { @0, [0,0,0,0,0,0,0,0,0,0] })
--}
|
geophf/1HaskellADay
|
exercises/HAD/Y2018/M10/D24/Solution.hs
|
mit
| 2,656
| 0
| 15
| 490
| 579
| 318
| 261
| 24
| 4
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
module Servant.Server.Internal.Handler where
import Prelude ()
import Prelude.Compat
import Control.Monad.Base
(MonadBase (..))
import Control.Monad.Catch
(MonadCatch, MonadMask, MonadThrow)
import Control.Monad.Error.Class
(MonadError)
import Control.Monad.IO.Class
(MonadIO)
import Control.Monad.Trans.Control
(MonadBaseControl (..))
import Control.Monad.Trans.Except
(ExceptT, runExceptT)
import GHC.Generics
(Generic)
import Servant.Server.Internal.ServerError
(ServerError)
newtype Handler a = Handler { runHandler' :: ExceptT ServerError IO a }
deriving
( Functor, Applicative, Monad, MonadIO, Generic
, MonadError ServerError
, MonadThrow, MonadCatch, MonadMask
)
instance MonadBase IO Handler where
liftBase = Handler . liftBase
instance MonadBaseControl IO Handler where
type StM Handler a = Either ServerError a
-- liftBaseWith :: (RunInBase Handler IO -> IO a) -> Handler a
liftBaseWith f = Handler (liftBaseWith (\g -> f (g . runHandler')))
-- restoreM :: StM Handler a -> Handler a
restoreM st = Handler (restoreM st)
runHandler :: Handler a -> IO (Either ServerError a)
runHandler = runExceptT . runHandler'
|
zoomhub/zoomhub
|
vendor/servant/servant-server/src/Servant/Server/Internal/Handler.hs
|
mit
| 1,616
| 0
| 13
| 489
| 326
| 191
| 135
| 37
| 1
|
module Y2021.M03.D11.Exercise where
import Data.Map (Map)
{--
Today's #haskell problem, we're going to provide unique identifier for words.
This is very computer-science-y, and Haskell is well-suited to take on this
problem.
For example, variables, bound or unbound ('free'), are named 'foo,' 'bar,'
and 'quux' in your program ...
RIGHT? DON'T YOU NAME ALL YOUR VARIABLES THOSE NAMES, AND NOT 'i' and 'x'
BECAUSE THIS ISN'T FORTRAN, FOLKS, I HATE TO BREAK IT TO YOU!
*whew* I'm glad I kept my cool there. O.o
So, given a list of words, provide a set of unique identifiers for them.
--}
uniqueIds :: Ord a => [a] -> Map a Integer
uniqueIds = undefined
-- give a set of unique ids for the following
names :: [String]
names = words "Tom Dick Harry"
|
geophf/1HaskellADay
|
exercises/HAD/Y2021/M03/D11/Exercise.hs
|
mit
| 756
| 0
| 7
| 140
| 65
| 38
| 27
| 6
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Hampc.CSS (layoutCss) where
import Prelude hiding ((**))
import Clay
import Data.Text.Lazy (Text)
layoutCss :: Text
layoutCss = renderWith pretty [] $ do
body ? minHeight (px 2000)
element "a:focus" ? outlineStyle none
element ".starter-template" ? marginTop (px 100)
element ".navbar-form" |> ".form-group" |> "input" ? marginRight (px 5)
element ".slider-selection" ? background (rgb 186 186 186)
element "#volumebar" ? height (px 15)
element "#progressbar" ? do
width $ pct 80
height $ px 15
marginTop $ px 3
element "#title" ? fontSize (px 35)
element "#time" ? fontSize (px 24)
element "#album,#artist" ? fontSize (px 18)
element "#btnstream" ? marginTop (px 5)
element "#streamurl" ? display displayNone
element "#notify" ? display displayNone
element "#panelBrowse" ? display displayNone
element "#panelSettings" ? display displayNone
element "table" ** "th:first-child,th:last-child,td:first-child,td:last-child" ? width (px 30)
element "table" ** "th:nth-child(3),td:nth-child(3)" ? textAlign (alignSide sideRight)
|
apirogov/hampc
|
Hampc/CSS.hs
|
mit
| 1,134
| 0
| 12
| 211
| 389
| 174
| 215
| 27
| 1
|
import Graphics.Gloss
win = InWindow "" (400, 300) (10, 10)
main = display win white (Circle 50)
|
dominicprior/gloss-demo
|
demo1.hs
|
mit
| 97
| 0
| 7
| 17
| 48
| 26
| 22
| 3
| 1
|
-- |
-- Module : Data.Markup.Types
-- Copyright : (c) Athan L. Clark
-- License : MIT
--
-- Maintainer : Athan L. Clark <athan.clark@gmail.com>
-- Stability : experimental
-- Portability : GHC
module Data.Markup.Types where
data Inline = Inline
deriving Show
data Remote = Remote
deriving Show
data Locally = Locally
deriving Show
|
athanclark/markup
|
src/Data/Markup/Types.hs
|
mit
| 364
| 0
| 5
| 87
| 45
| 31
| 14
| 7
| 0
|
-- | Conversions for sequents.
module Conversions (Conv(..), convMP, antC, conclC, notC
,thenC, allC, failC
,orElseC, tryC
,depthC
,symC) where
import Control.Monad
import Data.Maybe
import Bootstrap hiding (matchMP, matchMPInst, concl, sequent)
import Sequent
-- | Conversions wrap functions which take terms and derive equations. Each
-- equation has an lhs which is the original term.
newtype Conv a = Conv { applyC :: Term a -> [Sequent a] }
-- | Use a conversion to rewrite a sequent
convMP :: (Ord a, Show a) => Conv a -> Sequent a -> [Sequent a]
convMP c thm = do eq <- applyC c (concl thm)
let (l,r) = destEq (concl eq)
pure (mp (mp (inst2 l r (sequent eqMP)) eq) thm)
-- | Apply a conversion to the antcedent of a conditional
antC :: (Ord a, Show a) => Conv a -> Conv a
antC (Conv c) = Conv f
where f (p :=>: q) =
c p >>= maybeToList . matchMPInst (const q) (sequent substLeft)
f _ = []
-- | Apply a conversion to the consequent of a conditional
conclC :: (Ord a, Show a) => Conv a -> Conv a
conclC (Conv c) = Conv f
where f (p :=>: q) =
c q >>= maybeToList . matchMPInst (const p) (sequent substRight)
f _ = []
-- | Apply a conversion to the body of a negation
notC :: (Ord a, Show a) => Conv a -> Conv a
notC (Conv c) = Conv f
where f (Not p) = c p >>= \eq ->
let (l,r) = destEq (concl eq) in
pure (mp (inst2 l r (sequent substNot)) eq)
f _ = []
-- | Apply one conversion after another
thenC :: (Ord a,Show a) => Conv a -> Conv a -> Conv a
thenC c c' = Conv f
where f t = do thm <- applyC c t
let (x,y) = destEq (concl thm)
thm' <- applyC c' y
let (y',z) = destEq (concl thm')
unless (y == y') (error ("Sequent thenC"))
pure (mp (mp (inst3 x y z (sequent trans)) thm) thm')
-- | The zero for orConv and identity for thenConv: always succeeds
allC :: Conv a
allC = Conv (\t -> return $ inst1 t (sequent reflEq))
-- | The identity for orConv and zero for thenConv: always fails
failC :: Conv a
failC = Conv (const [])
-- | Try the first conversion. If it produces no results, try the second.
orElseC :: Ord a => Conv a -> Conv a -> Conv a
orElseC c c' = Conv (\tm ->
let thms = applyC c tm in
if null thms then applyC c' tm else thms)
-- | Try a conversion. If it produces no results, do the trivial conversion.
tryC :: Ord a => Conv a -> Conv a
tryC = (`orElseC` allC)
-- | Apply a conversion bottom-up.
depthC :: (Ord a, Show a) => Conv a -> Conv a
depthC c = tryC (antC (depthC c))
`thenC` tryC (conclC (depthC c))
`thenC` tryC (notC (depthC c))
`thenC` tryC c
-- | A conversion to switch the lhs and rhs of an equation.
symC :: Eq a => Conv a
symC = Conv c
where c (Not ((p :=>: q) :=>: Not (r :=>: s))) | p == s && q == r =
return $ inst2 p q (sequent symEq)
c _ = []
|
Chattered/proplcf
|
Conversions.hs
|
mit
| 3,130
| 0
| 17
| 1,015
| 1,180
| 601
| 579
| 58
| 2
|
module Main where
import System.IO
import System.FilePath
import Parse --(parse0, showAST)
import Checker (check, countLines)
import TreeWalker (writeToFile)
import Data.List
import Data.Char
-- compile takes a string that represents a file path so it can read that file.
-- gives the string to parse0 to get an AST, then gets the AST checked by check. if check finds errors it will stop here.
-- if the code is OK, it will generate code and an output file.
compile :: FilePath -> IO()
compile input = do
putStr "\nCompiling started:\n"
h <- openFile input ReadMode
contents <- hGetContents h
let ast = parse0 contents
check ast
let fileNameH = takeFileName input
let fileNameP = if isSuffixOf ".txt" fileNameH
then take ((length fileNameH)-4) fileNameH
else takeFileName input
let fileName = [toUpper (head fileNameP)] ++ tail fileNameP
outh <- openFile ("Output/" ++ fileName ++ ".hs") WriteMode
hPutStrLn outh (writeToFile [ast] fileName)
hClose outh
putStr "Compiling done!\n"
putStr ("Number of lines compiled: " ++ show (Checker.countLines ast) ++ "\n")
-- also takes a string that represents a file path. will parse the file and then print the AST on the standard web page 2.
drawTree :: FilePath -> IO()
drawTree input = do
h <- openFile input ReadMode
contents <- hGetContents h
let ast = parse0 contents
Parse.showAST ast
|
Ertruby/PPFinalProject
|
src/Main.hs
|
gpl-2.0
| 1,530
| 0
| 15
| 413
| 348
| 167
| 181
| 31
| 2
|
{-# LANGUAGE OverloadedStrings, TupleSections, ScopedTypeVariables #-}
{-
Copyright (C) 2006-2014 John MacFarlane <jgm@berkeley.edu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.Writers.Markdown
Copyright : Copyright (C) 2006-2014 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley.edu>
Stability : alpha
Portability : portable
Conversion of 'Pandoc' documents to markdown-formatted plain text.
Markdown: <http://daringfireball.net/projects/markdown/>
-}
module Text.Pandoc.Writers.Markdown (writeMarkdown, writePlain) where
import Text.Pandoc.Definition
import Text.Pandoc.Walk
import Text.Pandoc.Templates (renderTemplate')
import Text.Pandoc.Shared
import Text.Pandoc.Writers.Shared
import Text.Pandoc.Options
import Text.Pandoc.Parsing hiding (blankline, blanklines, char, space)
import Data.Maybe (fromMaybe)
import Data.List ( group, stripPrefix, find, intersperse, transpose, sortBy )
import Data.Char ( isSpace, isPunctuation )
import Data.Ord ( comparing )
import Text.Pandoc.Pretty
import Control.Monad.State
import qualified Data.Set as Set
import Text.Pandoc.Writers.HTML (writeHtmlString)
import Text.Pandoc.Readers.TeXMath (texMathToInlines)
import Text.HTML.TagSoup (parseTags, isTagText, Tag(..))
import Network.URI (isURI)
import Data.Default
import Data.Yaml (Value(Object,String,Array,Bool,Number))
import qualified Data.HashMap.Strict as H
import qualified Data.Vector as V
import qualified Data.Text as T
type Notes = [[Block]]
type Refs = [([Inline], Target)]
data WriterState = WriterState { stNotes :: Notes
, stRefs :: Refs
, stIds :: [String]
, stPlain :: Bool }
instance Default WriterState
where def = WriterState{ stNotes = [], stRefs = [], stIds = [], stPlain = False }
-- | Convert Pandoc to Markdown.
writeMarkdown :: WriterOptions -> Pandoc -> String
writeMarkdown opts document =
evalState (pandocToMarkdown opts{
writerWrapText = writerWrapText opts &&
not (isEnabled Ext_hard_line_breaks opts) }
document) def
-- | Convert Pandoc to plain text (like markdown, but without links,
-- pictures, or inline formatting).
writePlain :: WriterOptions -> Pandoc -> String
writePlain opts document =
evalState (pandocToMarkdown opts{
writerExtensions = Set.delete Ext_escaped_line_breaks $
Set.delete Ext_pipe_tables $
Set.delete Ext_raw_html $
Set.delete Ext_markdown_in_html_blocks $
Set.delete Ext_raw_tex $
Set.delete Ext_footnotes $
Set.delete Ext_tex_math_dollars $
Set.delete Ext_citations $
writerExtensions opts }
document) def{ stPlain = True }
pandocTitleBlock :: Doc -> [Doc] -> Doc -> Doc
pandocTitleBlock tit auths dat =
hang 2 (text "% ") tit <> cr <>
hang 2 (text "% ") (vcat $ map nowrap auths) <> cr <>
hang 2 (text "% ") dat <> cr
mmdTitleBlock :: Value -> Doc
mmdTitleBlock (Object hashmap) =
vcat $ map go $ sortBy (comparing fst) $ H.toList hashmap
where go (k,v) =
case (text (T.unpack k), v) of
(k', Array vec)
| V.null vec -> empty
| otherwise -> k' <> ":" <> space <>
hcat (intersperse "; "
(map fromstr $ V.toList vec))
(_, String "") -> empty
(k', x) -> k' <> ":" <> space <> nest 2 (fromstr x)
fromstr (String s) = text (removeBlankLines $ T.unpack s)
fromstr (Bool b) = text (show b)
fromstr (Number n) = text (show n)
fromstr _ = empty
-- blank lines not allowed in MMD metadata - we replace with .
removeBlankLines = trimr . unlines . map (\x ->
if all isSpace x then "." else x) . lines
mmdTitleBlock _ = empty
plainTitleBlock :: Doc -> [Doc] -> Doc -> Doc
plainTitleBlock tit auths dat =
tit <> cr <>
(hcat (intersperse (text "; ") auths)) <> cr <>
dat <> cr
yamlMetadataBlock :: Value -> Doc
yamlMetadataBlock v = "---" $$ (jsonToYaml v) $$ "..."
jsonToYaml :: Value -> Doc
jsonToYaml (Object hashmap) =
vcat $ map (\(k,v) ->
case (text (T.unpack k), v, jsonToYaml v) of
(k', Array vec, x)
| V.null vec -> empty
| otherwise -> (k' <> ":") $$ x
(k', Object _, x) -> (k' <> ":") $$ nest 2 x
(_, String "", _) -> empty
(k', _, x) -> k' <> ":" <> space <> hang 2 "" x)
$ sortBy (comparing fst) $ H.toList hashmap
jsonToYaml (Array vec) =
vcat $ map (\v -> hang 2 "- " (jsonToYaml v)) $ V.toList vec
jsonToYaml (String "") = empty
jsonToYaml (String s) =
case T.unpack s of
x | '\n' `elem` x -> hang 2 ("|" <> cr) $ text x
| not (any isPunctuation x) -> text x
| otherwise -> text $ "'" ++ substitute "'" "''" x ++ "'"
jsonToYaml (Bool b) = text $ show b
jsonToYaml (Number n) = text $ show n
jsonToYaml _ = empty
-- | Return markdown representation of document.
pandocToMarkdown :: WriterOptions -> Pandoc -> State WriterState String
pandocToMarkdown opts (Pandoc meta blocks) = do
let colwidth = if writerWrapText opts
then Just $ writerColumns opts
else Nothing
isPlain <- gets stPlain
metadata <- metaToJSON opts
(fmap (render colwidth) . blockListToMarkdown opts)
(fmap (render colwidth) . inlineListToMarkdown opts)
meta
let title' = maybe empty text $ getField "title" metadata
let authors' = maybe [] (map text) $ getField "author" metadata
let date' = maybe empty text $ getField "date" metadata
let titleblock = case writerStandalone opts of
True | isPlain ->
plainTitleBlock title' authors' date'
| isEnabled Ext_yaml_metadata_block opts ->
yamlMetadataBlock metadata
| isEnabled Ext_pandoc_title_block opts ->
pandocTitleBlock title' authors' date'
| isEnabled Ext_mmd_title_block opts ->
mmdTitleBlock metadata
| otherwise -> empty
False -> empty
let headerBlocks = filter isHeaderBlock blocks
let toc = if writerTableOfContents opts
then tableOfContents opts headerBlocks
else empty
-- Strip off final 'references' header if markdown citations enabled
let blocks' = if isEnabled Ext_citations opts
then case reverse blocks of
(Div (_,["references"],_) _):xs -> reverse xs
_ -> blocks
else blocks
body <- blockListToMarkdown opts blocks'
st <- get
notes' <- notesToMarkdown opts (reverse $ stNotes st)
st' <- get -- note that the notes may contain refs
refs' <- refsToMarkdown opts (reverse $ stRefs st')
let render' :: Doc -> String
render' = render colwidth
let main = render' $ body <>
(if isEmpty notes' then empty else blankline <> notes') <>
(if isEmpty refs' then empty else blankline <> refs')
let context = defField "toc" (render' toc)
$ defField "body" main
$ (if isNullMeta meta
then id
else defField "titleblock" (render' titleblock))
$ metadata
if writerStandalone opts
then return $ renderTemplate' (writerTemplate opts) context
else return main
-- | Return markdown representation of reference key table.
refsToMarkdown :: WriterOptions -> Refs -> State WriterState Doc
refsToMarkdown opts refs = mapM (keyToMarkdown opts) refs >>= return . vcat
-- | Return markdown representation of a reference key.
keyToMarkdown :: WriterOptions
-> ([Inline], (String, String))
-> State WriterState Doc
keyToMarkdown opts (label, (src, tit)) = do
label' <- inlineListToMarkdown opts label
let tit' = if null tit
then empty
else space <> "\"" <> text tit <> "\""
return $ nest 2 $ hang 2
("[" <> label' <> "]:" <> space) (text src <> tit')
-- | Return markdown representation of notes.
notesToMarkdown :: WriterOptions -> [[Block]] -> State WriterState Doc
notesToMarkdown opts notes =
mapM (\(num, note) -> noteToMarkdown opts num note) (zip [1..] notes) >>=
return . vsep
-- | Return markdown representation of a note.
noteToMarkdown :: WriterOptions -> Int -> [Block] -> State WriterState Doc
noteToMarkdown opts num blocks = do
contents <- blockListToMarkdown opts blocks
let num' = text $ writerIdentifierPrefix opts ++ show num
let marker = if isEnabled Ext_footnotes opts
then text "[^" <> num' <> text "]:"
else text "[" <> num' <> text "]"
let markerSize = 4 + offset num'
let spacer = case writerTabStop opts - markerSize of
n | n > 0 -> text $ replicate n ' '
_ -> text " "
return $ if isEnabled Ext_footnotes opts
then hang (writerTabStop opts) (marker <> spacer) contents
else marker <> spacer <> contents
-- | Escape special characters for Markdown.
escapeString :: WriterOptions -> String -> String
escapeString opts = escapeStringUsing markdownEscapes
where markdownEscapes = backslashEscapes specialChars
specialChars =
(if isEnabled Ext_superscript opts
then ('^':)
else id) .
(if isEnabled Ext_subscript opts
then ('~':)
else id) .
(if isEnabled Ext_tex_math_dollars opts
then ('$':)
else id) $
"\\`*_<>#"
-- | Construct table of contents from list of header blocks.
tableOfContents :: WriterOptions -> [Block] -> Doc
tableOfContents opts headers =
let opts' = opts { writerIgnoreNotes = True }
contents = BulletList $ map (elementToListItem opts) $ hierarchicalize headers
in evalState (blockToMarkdown opts' contents) def
-- | Converts an Element to a list item for a table of contents,
elementToListItem :: WriterOptions -> Element -> [Block]
elementToListItem opts (Sec lev _ _ headerText subsecs)
= Plain headerText :
[ BulletList (map (elementToListItem opts) subsecs) |
not (null subsecs) && lev < writerTOCDepth opts ]
elementToListItem _ (Blk _) = []
attrsToMarkdown :: Attr -> Doc
attrsToMarkdown attribs = braces $ hsep [attribId, attribClasses, attribKeys]
where attribId = case attribs of
([],_,_) -> empty
(i,_,_) -> "#" <> text i
attribClasses = case attribs of
(_,[],_) -> empty
(_,cs,_) -> hsep $
map (text . ('.':))
cs
attribKeys = case attribs of
(_,_,[]) -> empty
(_,_,ks) -> hsep $
map (\(k,v) -> text k
<> "=\"" <> text v <> "\"") ks
-- | Ordered list start parser for use in Para below.
olMarker :: Parser [Char] ParserState Char
olMarker = do (start, style', delim) <- anyOrderedListMarker
if delim == Period &&
(style' == UpperAlpha || (style' == UpperRoman &&
start `elem` [1, 5, 10, 50, 100, 500, 1000]))
then spaceChar >> spaceChar
else spaceChar
-- | True if string begins with an ordered list marker
beginsWithOrderedListMarker :: String -> Bool
beginsWithOrderedListMarker str =
case runParser olMarker defaultParserState "para start" (take 10 str) of
Left _ -> False
Right _ -> True
-- | Convert Pandoc block element to markdown.
blockToMarkdown :: WriterOptions -- ^ Options
-> Block -- ^ Block element
-> State WriterState Doc
blockToMarkdown _ Null = return empty
blockToMarkdown opts (Div attrs ils) = do
contents <- blockListToMarkdown opts ils
return $ if isEnabled Ext_raw_html opts &&
isEnabled Ext_markdown_in_html_blocks opts
then tagWithAttrs "div" attrs <> blankline <>
contents <> blankline <> "</div>" <> blankline
else contents <> blankline
blockToMarkdown opts (Plain inlines) = do
contents <- inlineListToMarkdown opts inlines
-- escape if para starts with ordered list marker
st <- get
let colwidth = if writerWrapText opts
then Just $ writerColumns opts
else Nothing
let rendered = render colwidth contents
let escapeDelimiter (x:xs) | x `elem` (".()" :: String) = '\\':x:xs
| otherwise = x : escapeDelimiter xs
escapeDelimiter [] = []
let contents' = if isEnabled Ext_all_symbols_escapable opts &&
not (stPlain st) && beginsWithOrderedListMarker rendered
then text $ escapeDelimiter rendered
else contents
return $ contents' <> cr
-- title beginning with fig: indicates figure
blockToMarkdown opts (Para [Image attr alt (src,'f':'i':'g':':':tit)]) =
blockToMarkdown opts (Para [Image attr alt (src,tit)])
blockToMarkdown opts (Para inlines) =
(<> blankline) `fmap` blockToMarkdown opts (Plain inlines)
blockToMarkdown opts (RawBlock f str)
| f == "html" = do
plain <- gets stPlain
return $ if plain
then empty
else if isEnabled Ext_markdown_attribute opts
then text (addMarkdownAttribute str) <> text "\n"
else text str <> text "\n"
| f `elem` ["latex", "tex", "markdown"] = do
plain <- gets stPlain
return $ if plain
then empty
else text str <> text "\n"
blockToMarkdown _ (RawBlock _ _) = return empty
blockToMarkdown opts HorizontalRule = do
return $ blankline <> text (replicate (writerColumns opts) '-') <> blankline
blockToMarkdown opts (Header level attr inlines) = do
plain <- gets stPlain
-- we calculate the id that would be used by auto_identifiers
-- so we know whether to print an explicit identifier
ids <- gets stIds
let autoId = uniqueIdent inlines ids
modify $ \st -> st{ stIds = autoId : ids }
let attr' = case attr of
("",[],[]) -> empty
(id',[],[]) | isEnabled Ext_auto_identifiers opts
&& id' == autoId -> empty
(id',_,_) | isEnabled Ext_mmd_header_identifiers opts ->
space <> brackets (text id')
_ | isEnabled Ext_header_attributes opts ->
space <> attrsToMarkdown attr
| otherwise -> empty
contents <- inlineListToMarkdown opts $
if level == 1 && plain
then capitalize inlines
else inlines
let setext = writerSetextHeaders opts
return $ nowrap
$ case level of
1 | plain -> blanklines 3 <> contents <> blanklines 2
| setext ->
contents <> attr' <> cr <> text (replicate (offset contents) '=') <>
blankline
2 | plain -> blanklines 2 <> contents <> blankline
| setext ->
contents <> attr' <> cr <> text (replicate (offset contents) '-') <>
blankline
-- ghc interprets '#' characters in column 1 as linenum specifiers.
_ | plain || isEnabled Ext_literate_haskell opts ->
contents <> blankline
_ -> text (replicate level '#') <> space <> contents <> attr' <> blankline
blockToMarkdown opts (CodeBlock (_,classes,_) str)
| "haskell" `elem` classes && "literate" `elem` classes &&
isEnabled Ext_literate_haskell opts =
return $ prefixed "> " (text str) <> blankline
blockToMarkdown opts (CodeBlock attribs str) = return $
case attribs == nullAttr of
False | isEnabled Ext_backtick_code_blocks opts ->
backticks <> attrs <> cr <> text str <> cr <> backticks <> blankline
| isEnabled Ext_fenced_code_blocks opts ->
tildes <> attrs <> cr <> text str <> cr <> tildes <> blankline
_ -> nest (writerTabStop opts) (text str) <> blankline
where tildes = text $ case [ln | ln <- lines str, all (=='~') ln] of
[] -> "~~~~"
xs -> case maximum $ map length xs of
n | n < 3 -> "~~~~"
| otherwise -> replicate (n+1) '~'
backticks = text $ case [ln | ln <- lines str, all (=='`') ln] of
[] -> "```"
xs -> case maximum $ map length xs of
n | n < 3 -> "```"
| otherwise -> replicate (n+1) '`'
attrs = if isEnabled Ext_fenced_code_attributes opts
then nowrap $ " " <> attrsToMarkdown attribs
else case attribs of
(_,(cls:_),_) -> " " <> text cls
_ -> empty
blockToMarkdown opts (BlockQuote blocks) = do
plain <- gets stPlain
-- if we're writing literate haskell, put a space before the bird tracks
-- so they won't be interpreted as lhs...
let leader = if isEnabled Ext_literate_haskell opts
then " > "
else if plain then " " else "> "
contents <- blockListToMarkdown opts blocks
return $ (prefixed leader contents) <> blankline
blockToMarkdown opts t@(Table caption aligns widths headers rows) = do
caption' <- inlineListToMarkdown opts caption
let caption'' = if null caption || not (isEnabled Ext_table_captions opts)
then empty
else blankline <> ": " <> caption' <> blankline
rawHeaders <- mapM (blockListToMarkdown opts) headers
rawRows <- mapM (mapM (blockListToMarkdown opts)) rows
let isSimple = all (==0) widths
let isPlainBlock (Plain _) = True
isPlainBlock _ = False
let hasBlocks = not (all isPlainBlock $ concat . concat $ headers:rows)
(nst,tbl) <- case True of
_ | isSimple &&
isEnabled Ext_simple_tables opts -> fmap (nest 2,) $
pandocTable opts (all null headers) aligns widths
rawHeaders rawRows
| isSimple &&
isEnabled Ext_pipe_tables opts -> fmap (id,) $
pipeTable (all null headers) aligns rawHeaders rawRows
| not hasBlocks &&
isEnabled Ext_multiline_tables opts -> fmap (nest 2,) $
pandocTable opts (all null headers) aligns widths
rawHeaders rawRows
| isEnabled Ext_grid_tables opts -> fmap (id,) $
gridTable opts (all null headers) aligns widths
rawHeaders rawRows
| otherwise -> fmap (id,) $
return $ text $ writeHtmlString def
$ Pandoc nullMeta [t]
return $ nst $ tbl $$ blankline $$ caption'' $$ blankline
blockToMarkdown opts (BulletList items) = do
contents <- mapM (bulletListItemToMarkdown opts) items
return $ cat contents <> blankline
blockToMarkdown opts (OrderedList (start,sty,delim) items) = do
let start' = if isEnabled Ext_startnum opts then start else 1
let sty' = if isEnabled Ext_fancy_lists opts then sty else DefaultStyle
let delim' = if isEnabled Ext_fancy_lists opts then delim else DefaultDelim
let attribs = (start', sty', delim')
let markers = orderedListMarkers attribs
let markers' = map (\m -> if length m < 3
then m ++ replicate (3 - length m) ' '
else m) markers
contents <- mapM (\(item, num) -> orderedListItemToMarkdown opts item num) $
zip markers' items
return $ cat contents <> blankline
blockToMarkdown opts (DefinitionList items) = do
contents <- mapM (definitionListItemToMarkdown opts) items
return $ cat contents <> blankline
blockToMarkdown _ (Figure _ _ _ _ _) = return empty
blockToMarkdown _ (ImageGrid _) = return empty
blockToMarkdown _ (Statement _ _) = return empty
blockToMarkdown _ (Proof _ _) = return empty
addMarkdownAttribute :: String -> String
addMarkdownAttribute s =
case span isTagText $ reverse $ parseTags s of
(xs,(TagOpen t attrs:rest)) ->
renderTags' $ reverse rest ++ (TagOpen t attrs' : reverse xs)
where attrs' = ("markdown","1"):[(x,y) | (x,y) <- attrs,
x /= "markdown"]
_ -> s
pipeTable :: Bool -> [Alignment] -> [Doc] -> [[Doc]] -> State WriterState Doc
pipeTable headless aligns rawHeaders rawRows = do
let sp = text " "
let blockFor AlignLeft x y = lblock (x + 2) (sp <> y) <> lblock 0 empty
blockFor AlignCenter x y = cblock (x + 2) (sp <> y) <> lblock 0 empty
blockFor AlignRight x y = rblock (x + 2) (sp <> y) <> lblock 0 empty
blockFor _ x y = lblock (x + 2) (sp <> y) <> lblock 0 empty
let widths = map (max 3 . maximum . map offset) $ transpose (rawHeaders : rawRows)
let torow cs = nowrap $ text "|" <>
hcat (intersperse (text "|") $
zipWith3 blockFor aligns widths (map chomp cs))
<> text "|"
let toborder (a, w) = text $ case a of
AlignLeft -> ':':replicate (w + 1) '-'
AlignCenter -> ':':replicate w '-' ++ ":"
AlignRight -> replicate (w + 1) '-' ++ ":"
AlignDefault -> replicate (w + 2) '-'
let header = if headless then empty else torow rawHeaders
let border = nowrap $ text "|" <> hcat (intersperse (text "|") $
map toborder $ zip aligns widths) <> text "|"
let body = vcat $ map torow rawRows
return $ header $$ border $$ body
pandocTable :: WriterOptions -> Bool -> [Alignment] -> [Double]
-> [Doc] -> [[Doc]] -> State WriterState Doc
pandocTable opts headless aligns widths rawHeaders rawRows = do
let isSimple = all (==0) widths
let alignHeader alignment = case alignment of
AlignLeft -> lblock
AlignCenter -> cblock
AlignRight -> rblock
AlignDefault -> lblock
let numChars = maximum . map offset
let widthsInChars = if isSimple
then map ((+2) . numChars)
$ transpose (rawHeaders : rawRows)
else map
(floor . (fromIntegral (writerColumns opts) *))
widths
let makeRow = hcat . intersperse (lblock 1 (text " ")) .
(zipWith3 alignHeader aligns widthsInChars)
let rows' = map makeRow rawRows
let head' = makeRow rawHeaders
let maxRowHeight = maximum $ map height (head':rows')
let underline = cat $ intersperse (text " ") $
map (\width -> text (replicate width '-')) widthsInChars
let border = if maxRowHeight > 1
then text (replicate (sum widthsInChars +
length widthsInChars - 1) '-')
else if headless
then underline
else empty
let head'' = if headless
then empty
else border <> cr <> head'
let body = if maxRowHeight > 1
then vsep rows'
else vcat rows'
let bottom = if headless
then underline
else border
return $ head'' $$ underline $$ body $$ bottom
gridTable :: WriterOptions -> Bool -> [Alignment] -> [Double]
-> [Doc] -> [[Doc]] -> State WriterState Doc
gridTable opts headless _aligns widths headers' rawRows = do
let numcols = length headers'
let widths' = if all (==0) widths
then replicate numcols (1.0 / fromIntegral numcols)
else widths
let widthsInChars = map (floor . (fromIntegral (writerColumns opts) *)) widths'
let hpipeBlocks blocks = hcat [beg, middle, end]
where h = maximum (map height blocks)
sep' = lblock 3 $ vcat (map text $ replicate h " | ")
beg = lblock 2 $ vcat (map text $ replicate h "| ")
end = lblock 2 $ vcat (map text $ replicate h " |")
middle = chomp $ hcat $ intersperse sep' blocks
let makeRow = hpipeBlocks . zipWith lblock widthsInChars
let head' = makeRow headers'
let rows' = map (makeRow . map chomp) rawRows
let border ch = char '+' <> char ch <>
(hcat $ intersperse (char ch <> char '+' <> char ch) $
map (\l -> text $ replicate l ch) widthsInChars) <>
char ch <> char '+'
let body = vcat $ intersperse (border '-') rows'
let head'' = if headless
then empty
else head' $$ border '='
return $ border '-' $$ head'' $$ body $$ border '-'
-- | Convert bullet list item (list of blocks) to markdown.
bulletListItemToMarkdown :: WriterOptions -> [Block] -> State WriterState Doc
bulletListItemToMarkdown opts items = do
contents <- blockListToMarkdown opts items
let sps = replicate (writerTabStop opts - 2) ' '
let start = text ('-' : ' ' : sps)
-- remove trailing blank line if it is a tight list
let contents' = case reverse items of
(BulletList xs:_) | isTightList xs ->
chomp contents <> cr
(OrderedList _ xs:_) | isTightList xs ->
chomp contents <> cr
_ -> contents
return $ hang (writerTabStop opts) start $ contents' <> cr
-- | Convert ordered list item (a list of blocks) to markdown.
orderedListItemToMarkdown :: WriterOptions -- ^ options
-> String -- ^ list item marker
-> [Block] -- ^ list item (list of blocks)
-> State WriterState Doc
orderedListItemToMarkdown opts marker items = do
contents <- blockListToMarkdown opts items
let sps = case length marker - writerTabStop opts of
n | n > 0 -> text $ replicate n ' '
_ -> text " "
let start = text marker <> sps
return $ hang (writerTabStop opts) start $ contents <> cr
-- | Convert definition list item (label, list of blocks) to markdown.
definitionListItemToMarkdown :: WriterOptions
-> ([Inline],[[Block]])
-> State WriterState Doc
definitionListItemToMarkdown opts (label, defs) = do
labelText <- inlineListToMarkdown opts label
defs' <- mapM (mapM (blockToMarkdown opts)) defs
if isEnabled Ext_definition_lists opts
then do
let tabStop = writerTabStop opts
st <- get
let leader = if stPlain st then " " else ": "
let sps = case writerTabStop opts - 3 of
n | n > 0 -> text $ replicate n ' '
_ -> text " "
if isEnabled Ext_compact_definition_lists opts
then do
let contents = vcat $ map (\d -> hang tabStop (leader <> sps)
$ vcat d <> cr) defs'
return $ nowrap labelText <> cr <> contents <> cr
else do
let contents = vcat $ map (\d -> hang tabStop (leader <> sps)
$ vcat d <> cr) defs'
let isTight = case defs of
((Plain _ : _): _) -> True
_ -> False
return $ blankline <> nowrap labelText <>
(if isTight then cr else blankline) <> contents <> blankline
else do
return $ nowrap labelText <> text " " <> cr <>
vsep (map vsep defs') <> blankline
-- | Convert list of Pandoc block elements to markdown.
blockListToMarkdown :: WriterOptions -- ^ Options
-> [Block] -- ^ List of block elements
-> State WriterState Doc
blockListToMarkdown opts blocks =
mapM (blockToMarkdown opts) (fixBlocks blocks) >>= return . cat
-- insert comment between list and indented code block, or the
-- code block will be treated as a list continuation paragraph
where fixBlocks (b : CodeBlock attr x : rest)
| (not (isEnabled Ext_fenced_code_blocks opts) || attr == nullAttr)
&& isListBlock b = b : commentSep : CodeBlock attr x :
fixBlocks rest
fixBlocks (b1@(BulletList _) : b2@(BulletList _) : bs) =
b1 : commentSep : fixBlocks (b2:bs)
fixBlocks (b1@(OrderedList _ _) : b2@(OrderedList _ _) : bs) =
b1 : commentSep : fixBlocks (b2:bs)
fixBlocks (b1@(DefinitionList _) : b2@(DefinitionList _) : bs) =
b1 : commentSep : fixBlocks (b2:bs)
fixBlocks (x : xs) = x : fixBlocks xs
fixBlocks [] = []
isListBlock (BulletList _) = True
isListBlock (OrderedList _ _) = True
isListBlock (DefinitionList _) = True
isListBlock _ = False
commentSep = RawBlock "html" "<!-- -->\n"
-- | Get reference for target; if none exists, create unique one and return.
-- Prefer label if possible; otherwise, generate a unique key.
getReference :: [Inline] -> Target -> State WriterState [Inline]
getReference label (src, tit) = do
st <- get
case find ((== (src, tit)) . snd) (stRefs st) of
Just (ref, _) -> return ref
Nothing -> do
let label' = case find ((== label) . fst) (stRefs st) of
Just _ -> -- label is used; generate numerical label
case find (\n -> notElem [Str (show n)]
(map fst (stRefs st)))
[1..(10000 :: Integer)] of
Just x -> [Str (show x)]
Nothing -> error "no unique label"
Nothing -> label
modify (\s -> s{ stRefs = (label', (src,tit)) : stRefs st })
return label'
-- | Convert list of Pandoc inline elements to markdown.
inlineListToMarkdown :: WriterOptions -> [Inline] -> State WriterState Doc
inlineListToMarkdown opts lst =
mapM (inlineToMarkdown opts) (avoidBadWraps lst) >>= return . cat
where avoidBadWraps [] = []
avoidBadWraps (Space:Str (c:cs):xs)
| c `elem` ("-*+>" :: String) = Str (' ':c:cs) : avoidBadWraps xs
avoidBadWraps (x:xs) = x : avoidBadWraps xs
escapeSpaces :: Inline -> Inline
escapeSpaces (Str s) = Str $ substitute " " "\\ " s
escapeSpaces Space = Str "\\ "
escapeSpaces x = x
-- | Convert Pandoc inline element to markdown.
inlineToMarkdown :: WriterOptions -> Inline -> State WriterState Doc
inlineToMarkdown opts (Span attrs ils) = do
contents <- inlineListToMarkdown opts ils
return $ if isEnabled Ext_raw_html opts
then tagWithAttrs "span" attrs <> contents <> text "</span>"
else contents
inlineToMarkdown opts (Emph lst) = do
plain <- gets stPlain
contents <- inlineListToMarkdown opts lst
return $ if plain
then "_" <> contents <> "_"
else "*" <> contents <> "*"
inlineToMarkdown opts (Strong lst) = do
plain <- gets stPlain
if plain
then inlineListToMarkdown opts $ capitalize lst
else do
contents <- inlineListToMarkdown opts lst
return $ "**" <> contents <> "**"
inlineToMarkdown opts (Strikeout lst) = do
contents <- inlineListToMarkdown opts lst
return $ if isEnabled Ext_strikeout opts
then "~~" <> contents <> "~~"
else "<s>" <> contents <> "</s>"
inlineToMarkdown opts (Superscript lst) = do
contents <- inlineListToMarkdown opts $ walk escapeSpaces lst
return $ if isEnabled Ext_superscript opts
then "^" <> contents <> "^"
else "<sup>" <> contents <> "</sup>"
inlineToMarkdown opts (Subscript lst) = do
contents <- inlineListToMarkdown opts $ walk escapeSpaces lst
return $ if isEnabled Ext_subscript opts
then "~" <> contents <> "~"
else "<sub>" <> contents <> "</sub>"
inlineToMarkdown opts (SmallCaps lst) = do
plain <- gets stPlain
if plain
then inlineListToMarkdown opts $ capitalize lst
else do
contents <- inlineListToMarkdown opts lst
return $ tagWithAttrs "span"
("",[],[("style","font-variant:small-caps;")])
<> contents <> text "</span>"
inlineToMarkdown opts (Quoted SingleQuote lst) = do
contents <- inlineListToMarkdown opts lst
return $ "‘" <> contents <> "’"
inlineToMarkdown opts (Quoted DoubleQuote lst) = do
contents <- inlineListToMarkdown opts lst
return $ "“" <> contents <> "”"
inlineToMarkdown opts (Code attr str) = do
let tickGroups = filter (\s -> '`' `elem` s) $ group str
let longest = if null tickGroups
then 0
else maximum $ map length tickGroups
let marker = replicate (longest + 1) '`'
let spacer = if (longest == 0) then "" else " "
let attrs = if isEnabled Ext_inline_code_attributes opts && attr /= nullAttr
then attrsToMarkdown attr
else empty
plain <- gets stPlain
if plain
then return $ text str
else return $ text (marker ++ spacer ++ str ++ spacer ++ marker) <> attrs
inlineToMarkdown opts (Str str) = do
st <- get
if stPlain st
then return $ text str
else return $ text $ escapeString opts str
inlineToMarkdown opts (Math InlineMath str)
| isEnabled Ext_scholarly_markdown opts =
return $ "``" <> text (trim str) <> "``"
| isEnabled Ext_tex_math_dollars opts =
return $ "$" <> text str <> "$"
| isEnabled Ext_tex_math_single_backslash opts =
return $ "\\(" <> text str <> "\\)"
| isEnabled Ext_tex_math_double_backslash opts =
return $ "\\\\(" <> text str <> "\\\\)"
| otherwise = do
plain <- gets stPlain
inlineListToMarkdown opts $
(if plain then makeMathPlainer else id) $
texMathToInlines InlineMath str
inlineToMarkdown opts (Math (DisplayMath a) str)
| isEnabled Ext_tex_math_dollars opts =
return $ "$$" <> text str <> "$$"
| isEnabled Ext_tex_math_single_backslash opts =
return $ "\\[" <> text str <> "\\]"
| isEnabled Ext_tex_math_double_backslash opts =
return $ "\\\\[" <> text str <> "\\\\]"
| otherwise = (\x -> cr <> x <> cr) `fmap`
inlineListToMarkdown opts (texMathToInlines (DisplayMath a) str)
inlineToMarkdown opts (RawInline f str) = do
plain <- gets stPlain
if not plain &&
( f == "markdown" ||
(isEnabled Ext_raw_tex opts && (f == "latex" || f == "tex")) ||
(isEnabled Ext_raw_html opts && f == "html") )
then return $ text str
else return empty
inlineToMarkdown opts (LineBreak) = do
plain <- gets stPlain
if plain || isEnabled Ext_hard_line_breaks opts
then return cr
else return $
if isEnabled Ext_escaped_line_breaks opts
then "\\" <> cr
else " " <> cr
inlineToMarkdown _ Space = return space
inlineToMarkdown opts (Cite [] lst) = inlineListToMarkdown opts lst
inlineToMarkdown opts (Cite (c:cs) lst)
| not (isEnabled Ext_citations opts) = inlineListToMarkdown opts lst
| otherwise =
if citationMode c == AuthorInText
then do
suffs <- inlineListToMarkdown opts $ citationSuffix c
rest <- mapM convertOne cs
let inbr = suffs <+> joincits rest
br = if isEmpty inbr then empty else char '[' <> inbr <> char ']'
return $ text ("@" ++ citationId c) <+> br
else do
cits <- mapM convertOne (c:cs)
return $ text "[" <> joincits cits <> text "]"
where
joincits = hcat . intersperse (text "; ") . filter (not . isEmpty)
convertOne Citation { citationId = k
, citationPrefix = pinlines
, citationSuffix = sinlines
, citationMode = m }
= do
pdoc <- inlineListToMarkdown opts pinlines
sdoc <- inlineListToMarkdown opts sinlines
let k' = text (modekey m ++ "@" ++ k)
r = case sinlines of
Str (y:_):_ | y `elem` (",;]@" :: String) -> k' <> sdoc
_ -> k' <+> sdoc
return $ pdoc <+> r
modekey SuppressAuthor = "-"
modekey _ = ""
inlineToMarkdown opts (Link txt (src, tit)) = do
plain <- gets stPlain
linktext <- inlineListToMarkdown opts txt
let linktitle = if null tit
then empty
else text $ " \"" ++ tit ++ "\""
let srcSuffix = fromMaybe src (stripPrefix "mailto:" src)
let useAuto = isURI src &&
case txt of
[Str s] | escapeURI s == srcSuffix -> True
_ -> False
let useRefLinks = writerReferenceLinks opts && not useAuto
ref <- if useRefLinks then getReference txt (src, tit) else return []
reftext <- inlineListToMarkdown opts ref
return $ if useAuto
then if plain
then text srcSuffix
else "<" <> text srcSuffix <> ">"
else if useRefLinks
then let first = "[" <> linktext <> "]"
second = if txt == ref
then "[]"
else "[" <> reftext <> "]"
in first <> second
else if plain
then linktext
else "[" <> linktext <> "](" <>
text src <> linktitle <> ")"
inlineToMarkdown opts (Image _ alternate (source, tit)) = do
plain <- gets stPlain
let txt = if null alternate || alternate == [Str source]
-- to prevent autolinks
then [Str ""]
else alternate
linkPart <- inlineToMarkdown opts (Link txt (source, tit))
return $ if plain
then "[" <> linkPart <> "]"
else "!" <> linkPart
inlineToMarkdown opts (Note contents) = do
modify (\st -> st{ stNotes = contents : stNotes st })
st <- get
let ref = text $ writerIdentifierPrefix opts ++ show (length $ stNotes st)
if isEnabled Ext_footnotes opts
then return $ "[^" <> ref <> "]"
else return $ "[" <> ref <> "]"
inlineToMarkdown _ (NumRef _ _) = return empty
makeMathPlainer :: [Inline] -> [Inline]
makeMathPlainer = walk go
where
go (Emph xs) = Span nullAttr xs
go x = x
|
timtylin/scholdoc
|
src/Text/Pandoc/Writers/Markdown.hs
|
gpl-2.0
| 40,863
| 0
| 26
| 14,145
| 12,078
| 6,004
| 6,074
| 785
| 32
|
module Language.SPO.Translators
( module Language.SPO.Translators.Translator
, module Language.SPO.Translators.SourcePawn
) where
import Language.SPO.Translators.Translator
import Language.SPO.Translators.SourcePawn
|
gxtaillon/spot
|
src/lib/Language/SPO/Translators.hs
|
gpl-3.0
| 230
| 0
| 5
| 28
| 39
| 28
| 11
| 5
| 0
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module VirMat.Core.FlexMicro
( FlexMicroBuilder
, FlexMicro (..)
, mkFlexMicro
, renderFlexMicro
, modifyGrainProps
, flexGrainList
-- * Rendering
, RenderGrainProp (..)
, addGrainAttrs
, showGrainID
-- * 2D Grain triangulation
, getSubOneTriangulation
) where
import Data.Maybe
import Data.Vector (Vector)
import Hammer.MicroGraph
import Hammer.Math.SortSeq
import Hammer.VTK
import Linear.Vect
import SubZero
import qualified Data.HashMap.Strict as HM
import qualified Data.HashSet as HS
import qualified Data.IntSet as IS
import qualified Data.Vector as V
import qualified Data.List as L
import VirMat.Core.VoronoiMicro
-- ================================ FlexMicroBuilder =====================================
class FlexMicroBuilder v where
-- | Stores a flexible microstructure using Subdivision Surfaces. The topology and
-- the values are store separately in order to allow fast update of values. The topology is
-- represented by @MicroGraph@.
data FlexMicro v a :: *
-- | This function converts a Voronoi microstructure (convex polygonal geomerty)
-- to flexible microstructure where arbitrary shape of grains are allowed.
-- Such a feature is provide by using Subdivision Surfaces.
mkFlexMicro :: VoronoiMicro v -> FlexMicro v ()
-- | Render 'FlexMicro' to 'VTK'. The extra info (attributes) are produced by a list of
-- attribute generators 'RenderGrainProp'. The surfaces are rendered with @n@ levels of
-- subdivision.
renderFlexMicro :: [RenderGrainProp g] -> Int -> FlexMicro v g -> Vector (VTK (v Double))
-- | Applies a function to modify the properties of grains
modifyGrainProps :: (GrainID -> GrainProp a -> b) -> FlexMicro v a -> FlexMicro v b
-- | List all @GrainID@s
flexGrainList :: FlexMicro v a -> [GrainID]
-- | Retrieves a specific grain's property
flexGrainProp :: GrainID -> FlexMicro v a -> Maybe (GrainProp a)
instance FlexMicroBuilder Vec2 where
data FlexMicro Vec2 a =
FlexMicro2D
{ flexGraph2D :: MicroGraph a (Vector Int) Int () -- ^ Microstructure graph
, flexPoints2D :: Vector Vec2D -- ^ Controls points (edges and faces)
} deriving (Show)
mkFlexMicro vm = getFlexFaces2D vm $ getFlexGrainsAndEdges2D vm
renderFlexMicro renders n fm@FlexMicro2D{..} = let
gids = V.fromList $ getGrainIDList flexGraph2D
foo gid = renderGrains2D gid renders n fm
in V.concatMap foo gids
modifyGrainProps func fm@FlexMicro2D{..} =
fm { flexGraph2D = flexGraph2D
{ microGrains = HM.mapWithKey foo (microGrains flexGraph2D)}}
where foo gid gp = setPropValue gp (func gid gp)
flexGrainList = getGrainIDList . flexGraph2D
flexGrainProp gid = getGrainProp gid . flexGraph2D
instance FlexMicroBuilder Vec3 where
data FlexMicro Vec3 a =
FlexMicro3D
{ flexGraph3D :: MicroGraph a MeshConn (Vector Int) Int -- ^ Microstructure graph
, flexPoints3D :: Vector Vec3D -- ^ Controls points (vertices, edges and faces)
} deriving (Show)
mkFlexMicro vm = getFlexFaces3D vm $ getFlexEdges3D vm $ getFlexGrainsAndVertices3D vm
renderFlexMicro renders n fm@FlexMicro3D{..} = let
gids = V.fromList $ getGrainIDList flexGraph3D
foo gid = renderGrains3D gid renders n fm
in V.concatMap foo gids
modifyGrainProps func fm@FlexMicro3D{..} =
fm { flexGraph3D = flexGraph3D
{ microGrains = HM.mapWithKey foo (microGrains flexGraph3D)}}
where foo gid gp = setPropValue gp (func gid gp)
flexGrainList = getGrainIDList . flexGraph3D
flexGrainProp gid = getGrainProp gid . flexGraph3D
-- =================================================================================
getFlexGrainsAndEdges2D :: VoronoiMicro Vec2 -> FlexMicro Vec2 ()
getFlexGrainsAndEdges2D MicroGraph{..} = let
vs_clean = filter (hasPropValue . snd) $ HM.toList microEdges
vh = HM.fromList $ zipWith (\(k, p) i -> (k, setPropValue p i)) vs_clean [0..]
fp = V.fromList $ mapMaybe (getPropValue . snd) vs_clean
fg = initMicroGraph { microEdges = vh, microGrains = microGrains }
in FlexMicro2D fg fp
getFlexFaces2D :: VoronoiMicro Vec2 -> FlexMicro Vec2 a -> FlexMicro Vec2 a
getFlexFaces2D vm@MicroGraph{..} (FlexMicro2D fm ps) = let
psSize = V.length ps
fs_clean = fst $ HM.foldlWithKey' foo (V.empty, psSize) microFaces
getter i m = getPropValue =<< getEdgeProp i m
foo acc@(vec, n) k p = fromMaybe acc $ do
conn <- getPropConn p
case HS.toList conn of
[a,b] -> do
ia <- getter a fm
ib <- getter b fm
va <- getter a vm
vb <- getter b vm
let prop = setPropValue p $ V.fromList [ia, n, ib]
avg = 0.5 *& (va &+ vb)
v = (k, avg, prop)
return (vec `V.snoc` v, n + 1)
_ -> Nothing
vv = V.map (\(_,x,_) -> x) fs_clean
vh = HM.fromList . V.toList $ V.map (\(k,_,p) -> (k,p)) fs_clean
fg = fm { microFaces = vh }
fp = ps V.++ vv
in FlexMicro2D fg fp
-- =================================================================================
getFlexGrainsAndVertices3D :: VoronoiMicro Vec3 -> FlexMicro Vec3 ()
getFlexGrainsAndVertices3D MicroGraph{..} = let
vs_clean = filter (hasPropValue . snd) $ HM.toList microVertex
vh = HM.fromList $ zipWith (\(k, p) i -> (k, setPropValue p i)) vs_clean [0..]
fp = V.fromList $ mapMaybe (getPropValue . snd) vs_clean
fg = initMicroGraph { microVertex = vh, microGrains = microGrains }
in FlexMicro3D fg fp
getFlexEdges3D :: VoronoiMicro Vec3 -> FlexMicro Vec3 a -> FlexMicro Vec3 a
getFlexEdges3D vm@MicroGraph{..} (FlexMicro3D fm ps) = let
psSize = V.length ps
es_clean = fst $ HM.foldlWithKey' foo (V.empty, psSize) microEdges
getter i m = getPropValue =<< getVertexProp i m
foo acc@(vec, n) k p = fromMaybe acc $ do
conn <- getPropConn p
case conn of
FullEdge a b -> do
ia <- getter a fm
ib <- getter b fm
va <- getter a vm
vb <- getter b vm
let prop = setPropValue p $ V.fromList [ia, n, ib]
avg = 0.5 *& (va &+ vb)
v = (k, avg, prop)
return (vec `V.snoc` v, n + 1)
_ -> Nothing
vv = V.map (\(_,x,_) -> x) es_clean
vh = HM.fromList . V.toList $ V.map (\(k,_,p) -> (k,p)) es_clean
fg = fm { microEdges = vh }
fp = ps V.++ vv
in FlexMicro3D fg fp
getFlexFaces3D :: VoronoiMicro Vec3 -> FlexMicro Vec3 a -> FlexMicro Vec3 a
getFlexFaces3D MicroGraph{..} (FlexMicro3D fm ps) = let
psSize = V.length ps
fs_clean = fst $ HM.foldlWithKey' foo (V.empty, psSize) microFaces
getEdge eid = getPropValue =<< getEdgeProp eid fm
foo acc@(vec, n) k p = fromMaybe acc $ do
conn <- getPropConn p
let es = HS.foldl' (\acu eid -> maybe acu (V.snoc acu) (getEdge eid)) V.empty conn
mesh <- mkMesh es n
fc <- faceCenter ps es
let v = (k, setPropValue p mesh, fc)
return (vec `V.snoc` v, n + 1)
vh = HM.fromList . V.toList $ V.map (\(k,m,_) -> (k,m)) fs_clean
fp = V.map (\(_,_,p) -> p) fs_clean
fg = fm { microFaces = vh }
in FlexMicro3D fg (ps V.++ fp)
-- =================================================================================
-- | @faceCenter@ calculates the mass center of a given polygon defined by
-- a array of points and a list of edges (reference to array of points).
-- It expects a non-empty face otherwise a error will rise. DON'T EXPORT ME!!!
faceCenter :: (Fractional a, AbelianGroup (v a), LinearMap a v) => Vector (v a) -> Vector (Vector Int) -> Maybe (v a)
faceCenter ps vs
| n > 0 = return $ total &* (1 / fromIntegral n)
| otherwise = Nothing
where
sumBoth (vacu, nacu) x = (vacu &+ sumFecth x, nacu + V.length x)
sumFecth = V.foldl' (\acc i -> acc &+ (ps V.! i)) zero
(total, n) = V.foldl' sumBoth (zero, 0) vs
-- | Finds the subdivision mesh for an closed set of subdivision lines
mkMesh :: Vector (Vector Int) -> Int -> Maybe MeshConn
mkMesh es fc = do
-- check closure of the line's set
ses <- sortEdges es
return $ buildMesh (toTS ses) corners
where
getTris vec = V.imap (\i x -> (x, vec V.! (i+1), fc)) (V.init vec)
toTS = V.toList . V.concatMap getTris
getCorners v
-- the emptiness of the inner Vector is checked by 'sortEdges'
-- and set the ends to be corners
| V.length v > 0 = IS.fromList [V.head v, V.last v]
| otherwise = IS.empty
cornersSet = V.foldl' (\acc v -> acc `IS.union` getCorners v) IS.empty es
corners = IS.toList cornersSet
-- | Sort and check closure of a set of lines (segments)
sortEdges :: (SeqSeg a) => Vector a -> Maybe (Vector a)
sortEdges = getOneLoop . sortSegs
instance SeqComp Int
instance (SeqComp a) => SeqSeg (Vector a) where
type SeqUnit (Vector a) = a
getSeqHead = V.head
getSeqTail = V.last
seqInv = V.reverse
-- ============================= VTK render for FlexMicro ================================
-- | Creates an attribute generator for each grain in a 'FlexMicro' structure. It needs a
-- name for the generated attribute, that be will identified on VTK visualization software,
-- and a function that generates the attribute itself based on 'GrainID' and 'FlexMicro'.
data RenderGrainProp g
= forall a . RenderElemVTK a
=> RenderGrainProp (String, GrainID -> Maybe g -> Maybe a)
-- | Applies an attribute generator to a given VTK (one single grain)
addGrainAttrs :: (RenderElemVTK a, FlexMicroBuilder v)=> GrainID -> FlexMicro v g
-> [RenderGrainProp g] -> VTK a -> VTK a
addGrainAttrs gid fm renders vtk = let
foo (RenderGrainProp (name, func)) = let
add x v = addCellAttr v (mkCellAttr name (\_ _ _ -> x))
in maybe id add (func gid (flexGrainProp gid fm >>= getPropValue))
in L.foldl' (flip foo) vtk renders
-- | Show the 'GrainID' value in the 'VTK' data.
showGrainID :: RenderGrainProp g
showGrainID = RenderGrainProp ("GrainID", \gid _ -> return $ unGrainID gid)
-- =================================== Render 2D Grains ==================================
renderGrains2D :: GrainID -> [RenderGrainProp g] -> Int -> FlexMicro Vec2 g -> Vector (VTK Vec2D)
renderGrains2D gid renders n fm@FlexMicro2D{..} =
maybe V.empty (V.singleton . addGrainAttrs gid fm renders) $ do
grainConn <- getPropConn =<< getGrainProp gid flexGraph2D
renderGrainBulk2D grainConn n fm
renderGrainBulk2D :: HS.HashSet FaceID -> Int -> FlexMicro Vec2 a -> Maybe (VTK Vec2D)
renderGrainBulk2D fs n FlexMicro2D{..} = let
func acc fid = maybe acc (V.snoc acc) (getPropValue =<< getFaceProp fid flexGraph2D)
es = HS.foldl' func V.empty fs
in renderSubOne n flexPoints2D es
-- =================================== Render 3D Grains ==================================
renderGrains3D :: GrainID -> [RenderGrainProp g] -> Int -> FlexMicro Vec3 g -> Vector (VTK Vec3D)
renderGrains3D gid renders n fm@FlexMicro3D{..} = let
grainConn = getPropConn =<< getGrainProp gid flexGraph3D
getVTK fid = addGrainAttrs gid fm renders <$> renderFace3D fid n fm
func acc = maybe acc (V.snoc acc) . getVTK
in maybe V.empty (HS.foldl' func V.empty) grainConn
renderFace3D :: FaceID -> Int -> FlexMicro Vec3 a -> Maybe (VTK Vec3D)
renderFace3D fid n FlexMicro3D{..} = renderSubTwo n flexPoints3D <$>
(getPropValue =<< getFaceProp fid flexGraph3D)
-- ============================== render subdivision surfaces ============================
-- | Construct subdivision triangulation for a 2D grain. Input: level, list of nodes
-- (junctions), list of GB segments. Output: maybe a pair (list of nodes, list of triangles)
getSubOneTriangulation :: Int -> Vector Vec2D -> Vector (Vector Int) -> Maybe (Vector Vec2D, Vector (Int, Int, Int))
getSubOneTriangulation n vs es = do
center <- faceCenter vs es
mesh <- mkMesh es (V.length vs)
let
sb = mkSubTwoFromMesh (vs `V.snoc` center) mesh
sbN = subdivideN n sb
ps = subTwoPoints sbN
ts = getSubTwoFaces $ subTwoMesh sbN
return (ps, ts)
-- | Renders a closed set of subdivision lines(faces in 2D grains) as surface(grain's bulk).
renderSubOne :: Int -> Vector Vec2D -> Vector (Vector Int) -> Maybe (VTK Vec2D)
renderSubOne n vs es =
(\(ps, ts) -> mkUGVTK "FlexMicro" (V.convert ps) ts [] [])
<$> getSubOneTriangulation n vs es
-- | Renders a subdivision surface(faces in 3D grains).
renderSubTwo :: Int -> Vector Vec3D -> MeshConn -> VTK Vec3D
renderSubTwo n vs mesh = let
sb = mkSubTwoFromMesh vs mesh
sbN = subdivideN n sb
ps = V.convert $ subTwoPoints sbN
ts = getSubTwoFaces $ subTwoMesh sbN
in mkUGVTK "FlexMicro" ps ts [] []
|
lostbean/VirMat
|
src/VirMat/Core/FlexMicro.hs
|
gpl-3.0
| 12,849
| 0
| 22
| 2,781
| 3,993
| 2,061
| 1,932
| 225
| 2
|
{-# LANGUAGE ForeignFunctionInterface #-}
module Math.Minuit where
import Control.Monad
import System.IO.Unsafe
import Foreign
import Foreign.C.Types
import Foreign.C.String
import Graphics.PlotWithGnu
type Minimum = ((Bool, Double), ([Double], [Double]))
type FcnFunction = [Double] -> Double
type FcnFunctionIO = [Double] -> IO Double
type CFcnFunctionIO = CInt -> Ptr CDouble -> Ptr () -> IO CDouble
foreign import ccall "minuit-c.h migrad"
c_migradIO :: CInt
-> FunPtr CFcnFunctionIO
-> Ptr CString
-> Ptr CDouble -> Ptr CDouble
-> Ptr CDouble -> Ptr CDouble
-> Ptr CDouble -> Ptr CInt
-> Ptr ()
-> IO CInt
foreign import ccall "wrapper"
mkFunPtr_CFcnFunctionIO :: CFcnFunctionIO
-> IO (FunPtr CFcnFunctionIO)
cFcnFunctionIO :: FcnFunctionIO -> CFcnFunctionIO
cFcnFunctionIO fcnFuncIO c_comp c_pVals _ = do
let comp = fromIntegral c_comp
c_vals <- peekArray comp c_pVals
let vals = map realToFrac c_vals
liftM realToFrac $ fcnFuncIO vals
migradIO :: FcnFunctionIO -> [String] -> [Double] -> [Double] -> IO Minimum
migradIO fcnFuncIO names initVals initErrs =
let comp = length names in
alloca $ \ p_isValid ->
alloca $ \ p_fcn ->
allocaArray comp $ \ p_names ->
allocaArray comp $ \ p_initVals ->
allocaArray comp $ \ p_initErrs ->
allocaArray comp $ \ p_miniVals ->
allocaArray comp $ \ p_miniErrs -> do
c_fcnFuncIO <- mkFunPtr_CFcnFunctionIO $ cFcnFunctionIO fcnFuncIO
c_names <- mapM newCString names
pokeArray p_names c_names
pokeArray p_initVals $ map realToFrac initVals
pokeArray p_initErrs $ map realToFrac initErrs
_ <- c_migradIO (fromIntegral comp) c_fcnFuncIO p_names
p_initVals p_initErrs
p_miniVals p_miniErrs
p_fcn p_isValid nullPtr
c_isValid <- peek p_isValid
c_fcn <- peek p_fcn
let isValid = if c_isValid == 0 then False else True
fcn = realToFrac c_fcn
miniVals <- liftM (map realToFrac) $ peekArray comp p_miniVals
miniErrs <- liftM (map realToFrac) $ peekArray comp p_miniErrs
mapM_ free c_names
freeHaskellFunPtr c_fcnFuncIO
return ((isValid, fcn), (miniVals, miniErrs))
migrad :: FcnFunction -> [String] -> [Double] -> [Double] -> Minimum
migrad fcnFunc names initVals initErrs = unsafePerformIO $
migradIO funcFuncIO names initVals initErrs
where
funcFuncIO vs = return $ fcnFunc vs
minimize :: FcnFunction -> [String] -> [Double] -> [Double] -> Minimum
minimize = migrad
makeFcnFunc :: ([Double] -> [Double] -> Double) -> Int -> DataTable -> FcnFunction
makeFcnFunc fitf dims table = fcn where
poses = map (take dims) table
valerrs = map (drop dims) table
fcn params = sum $ zipWith sfcn valerrs $ map (fitf params) poses
sfcn [v,e] f = sqr $ (f-v)/e
sqr x = x*x
|
waterret/Minuit-haskell
|
src/Math/Minuit.hs
|
gpl-3.0
| 2,916
| 0
| 27
| 716
| 947
| 475
| 472
| 71
| 2
|
:set -XOverloadedStrings
:set prompt ""
import Sound.Tidal.Context
import System.IO (hSetEncoding, stdout, utf8)
hSetEncoding stdout utf8
-- total latency = oLatency + cFrameTimespan
tidal <- startTidal (superdirtTarget {oLatency = 0.1, oAddress = "127.0.0.1", oPort = 57120}) (defaultConfig {cFrameTimespan = 1/20})
:{
let only = (hush >>)
p = streamReplace tidal
hush = streamHush tidal
list = streamList tidal
mute = streamMute tidal
unmute = streamUnmute tidal
unmuteAll = streamUnmuteAll tidal
solo = streamSolo tidal
unsolo = streamUnsolo tidal
once = streamOnce tidal
first = streamFirst tidal
asap = once
nudgeAll = streamNudgeAll tidal
all = streamAll tidal
resetCycles = streamResetCycles tidal
setcps = asap . cps
xfade i = transition tidal True (Sound.Tidal.Transition.xfadeIn 4) i
xfadeIn i t = transition tidal True (Sound.Tidal.Transition.xfadeIn t) i
histpan i t = transition tidal True (Sound.Tidal.Transition.histpan t) i
wait i t = transition tidal True (Sound.Tidal.Transition.wait t) i
waitT i f t = transition tidal True (Sound.Tidal.Transition.waitT f t) i
jump i = transition tidal True (Sound.Tidal.Transition.jump) i
jumpIn i t = transition tidal True (Sound.Tidal.Transition.jumpIn t) i
jumpIn' i t = transition tidal True (Sound.Tidal.Transition.jumpIn' t) i
jumpMod i t = transition tidal True (Sound.Tidal.Transition.jumpMod t) i
mortal i lifespan release = transition tidal True (Sound.Tidal.Transition.mortal lifespan release) i
interpolate i = transition tidal True (Sound.Tidal.Transition.interpolate) i
interpolateIn i t = transition tidal True (Sound.Tidal.Transition.interpolateIn t) i
clutch i = transition tidal True (Sound.Tidal.Transition.clutch) i
clutchIn i t = transition tidal True (Sound.Tidal.Transition.clutchIn t) i
anticipate i = transition tidal True (Sound.Tidal.Transition.anticipate) i
anticipateIn i t = transition tidal True (Sound.Tidal.Transition.anticipateIn t) i
forId i t = transition tidal False (Sound.Tidal.Transition.mortalOverlay t) i
d1 = p 1 . (|< orbit 0)
d2 = p 2 . (|< orbit 1)
d3 = p 3 . (|< orbit 2)
d4 = p 4 . (|< orbit 3)
d5 = p 5 . (|< orbit 4)
d6 = p 6 . (|< orbit 5)
d7 = p 7 . (|< orbit 6)
d8 = p 8 . (|< orbit 7)
d9 = p 9 . (|< orbit 8)
d10 = p 10 . (|< orbit 9)
d11 = p 11 . (|< orbit 10)
d12 = p 12 . (|< orbit 11)
d13 = p 13
d14 = p 14
d15 = p 15
d16 = p 16
:}
:{
let setI = streamSetI tidal
setF = streamSetF tidal
setS = streamSetS tidal
setR = streamSetR tidal
setB = streamSetB tidal
:}
:set prompt "tidal> "
:set prompt-cont ""
|
d0kt0r0/Tidal
|
BootTidal.hs
|
gpl-3.0
| 2,731
| 15
| 9
| 628
| 1,042
| 547
| 495
| -1
| -1
|
module JSONParser where
import Pelias
import SeedyPelias
latestCommitAuthor :: String -> String
latestCommitAuthor json =
case seedyExtract [Index 0, Get "author", Get "login"] json of
Just (SValue author) -> author
_ -> error "JSONParser.latestCommitAuthor failed for input starting with \"" ++ (take 20 json) ++ "\"\n"
latestCommitSha :: String -> String
latestCommitSha json =
case seedyExtract [Index 0, Get "sha"] json of
Just (SValue sha) -> sha
_ -> error "JSONParser.latestCommitSha failed for input starting with \"" ++ (take 20 json) ++ "\"\n"
|
ivanmoore/seedy
|
src/JSONParser.hs
|
gpl-3.0
| 613
| 0
| 11
| 142
| 172
| 86
| 86
| 13
| 2
|
module Fibonacci where
fibonacci :: Integer -> Integer
fibonacci n | n == 0 = 0
| n == 1 = 1
| n > 1 = fibonacci (n - 1) + fibonacci (n - 2)
| n < 0 = fibonacci (n + 2) - fibonacci (n + 1)
| otherwise = undefined
-- https://wiki.haskell.org/The_Fibonacci_sequence#Tail_recursive
fibonacci' :: Integer -> Integer
fibonacci' n = helper n 0 1
helper n a b | n == 0 = a
| n > 0 = helper (n - 1) b (a + b)
| n < 0 = helper (n + 1) b (a - b)
| otherwise = undefined
|
devtype-blogspot-com/Haskell-Examples
|
Fibonacci/Fibonacci.hs
|
gpl-3.0
| 562
| 0
| 9
| 210
| 251
| 123
| 128
| 13
| 1
|
{-# LANGUAGE DeriveDataTypeable #-}
module Ch_GeomAlign_Opts where
import System.Console.CmdArgs
data Ch_GeomAlign_Opts = Ch_GeomAlign_Opts
{ input :: FilePath
, output :: FilePath
, atoms :: String
, mdsteps :: Int
, verbose :: Bool
}
deriving (Show,Data,Typeable)
ch_GeomAlign_Opts = Ch_GeomAlign_Opts
{ input = def &= help "trajectory in XYZ format" &= typ "INPUT"
, output = "stdout" &= help "output file" &= typ "OUTPUT"
, atoms = def &= help "list of atoms to monitor, space separated" &= typ "ATOMS"
, mdsteps = 1 &= help "number of steps to be analysed" &= typ "STEPS"
, verbose = False &= help "print additional output"
}
mode = cmdArgsMode ch_GeomAlign_Opts
|
sheepforce/Haskell-Tools
|
ch_geomalign/Ch_GeomAlign_Opts.hs
|
gpl-3.0
| 697
| 0
| 9
| 137
| 173
| 96
| 77
| 17
| 1
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Application
( getApplicationDev
, appMain
, develMain
, makeFoundation
-- * for DevelMain
, getApplicationRepl
, shutdownApp
-- * for GHCI
, handler
, db
) where
import Control.Monad.Logger (liftLoc, runLoggingT)
import Database.Persist.Postgresql
(createPostgresqlPool, pgConnStr, pgPoolSize, runSqlPool)
import Import
import Language.Haskell.TH.Syntax (qLocation)
import Network.Wai.Handler.Warp
(Settings, defaultSettings, defaultShouldDisplayException,
runSettings, setHost, setOnException, setPort, getPort)
import Network.Wai.Middleware.RequestLogger
(Destination(Logger), IPAddrSource(..), OutputFormat(..),
destination, mkRequestLogger, outputFormat)
import System.Log.FastLogger
(defaultBufSize, newStdoutLoggerSet, toLogStr)
-- Import all relevant handler modules here.
-- Don't forget to add new modules to your cabal file!
import Handler.Account
import Handler.Account.New
import Handler.Common
import Handler.Login
import Handler.Logout
import Handler.Pages
import Handler.User
-- This line actually creates our YesodDispatch instance. It is the second half
-- of the call to mkYesodData which occurs in Foundation.hs. Please see the
-- comments there for more details.
mkYesodDispatch "App" resourcesApp
-- | This function allocates resources (such as a database connection pool),
-- performs initialization and return a foundation datatype value. This is also
-- the place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
makeFoundation :: AppSettings -> IO App
makeFoundation appSettings =
do
-- Some basic initializations: HTTP connection manager, logger, and static
-- subsite.
appHttpManager <- newManager
appLogger <- newStdoutLoggerSet defaultBufSize >>= makeYesodLogger
appStatic <-
(if appMutableStatic appSettings
then staticDevel
else static) (appStaticDir appSettings)
-- We need a log function to create a connection pool. We need a connection
-- pool to create our foundation. And we need our foundation to get a
-- logging function. To get out of this loop, we initially create a
-- temporary foundation without a real connection pool, get a log function
-- from there, and then create the real foundation.
let mkFoundation appConnPool = App {..}
-- The App {..} syntax is an example of record wild cards. For more
-- information, see:
-- https://ocharles.org.uk/blog/posts/2014-12-04-record-wildcards.html
tempFoundation =
mkFoundation $ error "connPool forced in tempFoundation"
logFunc = messageLoggerSource tempFoundation appLogger
-- Create the database connection pool
pool <-
flip runLoggingT logFunc $
createPostgresqlPool (pgConnStr $ appDatabaseConf appSettings)
(pgPoolSize $ appDatabaseConf appSettings)
-- Perform database migration using our application's logging settings.
runLoggingT
(runSqlPool (runMigration migrateAll)
pool)
logFunc
-- Return the foundation
return $
mkFoundation pool
-- | Convert our foundation to a WAI Application by calling @toWaiAppPlain@ and
-- applyng some additional middlewares.
makeApplication :: App -> IO Application
makeApplication foundation = do
logWare <- mkRequestLogger def
{ outputFormat =
if appDetailedRequestLogging $ appSettings foundation
then Detailed True
else Apache
(if appIpFromHeader $ appSettings foundation
then FromFallback
else FromSocket)
, destination = Logger $ loggerSet $ appLogger foundation
}
-- Create the WAI application and apply middlewares
appPlain <- toWaiAppPlain foundation
return $ logWare $ defaultMiddlewaresNoLogging appPlain
-- | Warp settings for the given foundation value.
warpSettings :: App -> Settings
warpSettings foundation =
setPort (appPort $ appSettings foundation)
$ setHost (appHost $ appSettings foundation)
$ setOnException (\_req e ->
when (defaultShouldDisplayException e) $ messageLoggerSource
foundation
(appLogger foundation)
$(qLocation >>= liftLoc)
"yesod"
LevelError
(toLogStr $ "Exception from Warp: " ++ show e))
defaultSettings
-- | For yesod devel, return the Warp settings and WAI Application.
getApplicationDev :: IO (Settings, Application)
getApplicationDev = do
settings <- getAppSettings
foundation <- makeFoundation settings
wsettings <- getDevSettings $ warpSettings foundation
app <- makeApplication foundation
return (wsettings, app)
getAppSettings :: IO AppSettings
getAppSettings = loadAppSettings [configSettingsYml] [] useEnv
-- | main function for use by yesod devel
develMain :: IO ()
develMain = develMainHelper getApplicationDev
-- | The @main@ function for an executable running this site.
appMain :: IO ()
appMain = do
-- Get the settings from all relevant sources
settings <- loadAppSettingsArgs
-- fall back to compile-time values, set to [] to require values at runtime
[configSettingsYmlValue]
-- allow environment variables to override
useEnv
-- Generate the foundation from the settings
foundation <- makeFoundation settings
-- Generate a WAI Application from the foundation
app <- makeApplication foundation
-- Run the application with Warp
runSettings (warpSettings foundation) app
--------------------------------------------------------------
-- Functions for DevelMain.hs (a way to run the app from GHCi)
--------------------------------------------------------------
getApplicationRepl :: IO (Int, App, Application)
getApplicationRepl = do
settings <- getAppSettings
foundation <- makeFoundation settings
wsettings <- getDevSettings $ warpSettings foundation
app1 <- makeApplication foundation
return (getPort wsettings, foundation, app1)
shutdownApp :: App -> IO ()
shutdownApp _ = return ()
---------------------------------------------
-- Functions for use in development with GHCi
---------------------------------------------
-- | Run a handler
handler :: Handler a -> IO a
handler h = getAppSettings >>= makeFoundation >>= flip unsafeHandler h
-- | Run DB queries
db :: ReaderT SqlBackend (HandlerT App IO) a -> IO a
db = handler . runDB
|
learnyou/learnyou
|
Application.hs
|
agpl-3.0
| 6,639
| 0
| 16
| 1,496
| 1,038
| 558
| 480
| -1
| -1
|
module Morse
( Morse
, charToMorse
, morseToChar
, stringToMorse
, letterToMorse
, morseToLetter
) where
import qualified Data.Map as M
type Morse = String
letterToMorse :: (M.Map Char Morse)
letterToMorse = M.fromList [
('a', ".-")
, ('b', "-...")
, ('c', "-.-.")
, ('d', "-..")
, ('e', ".")
, ('f', "..-.")
, ('g', "--.")
, ('h', "....")
, ('i', "..")
, ('j', ".---")
, ('k', "-.-")
, ('l', ".-..")
, ('m', "--")
, ('n', "-.")
, ('o', "---")
, ('p', ".--.")
, ('q', "--.-")
, ('r', ".-.")
, ('s', "...")
, ('t', "-")
, ('u', "..-")
, ('v', "...-")
, ('w', ".--")
, ('x', "-..-")
, ('y', "-.--")
, ('z', "--..")
, ('1', ".----")
, ('2', "..---")
, ('3', "...--")
, ('4', "....-")
, ('5', ".....")
, ('6', "-....")
, ('7', "--...")
, ('8', "---..")
, ('9', "----.")
, ('0', "-----")
]
morseToLetter :: M.Map Morse Char
morseToLetter =
M.foldWithKey (flip M.insert) M.empty letterToMorse
charToMorse :: Char -> Maybe Morse
charToMorse c =
M.lookup c letterToMorse
stringToMorse :: String -> Maybe [Morse]
stringToMorse s =
sequence $ fmap charToMorse s
morseToChar :: Morse -> Maybe Char
morseToChar m =
M.lookup m morseToLetter
|
aniketd/learn.haskell
|
haskellbook/morse/src/Morse.hs
|
unlicense
| 1,239
| 0
| 8
| 303
| 509
| 315
| 194
| 59
| 1
|
module EquationSolver.Common where
import Control.Monad.Identity
import Control.Monad.Error
import Control.Monad.State
import Control.Monad.Writer
-- |Flow collects errors, and allows to write tracing information to some type @x@
-- (Remember, one could write @type Flow a = ErrorT String (...) a@.)
type Flow = ErrorT String (WriterT [String] Identity)
-- |Equation is a data type holding the left and right sides of the equation
data Equation = Equation Expr Expr deriving (Show, Eq)
-- |Expr defines operations we know about: exponentiation, (square) root, multiplication, addition,
-- constants and variables
data Expr = Pow Expr Expr | Sqrt Expr
| Mult Expr Expr | Div Expr Expr
| Plus Expr Expr | Minus Expr Expr
| Variable Char
| Constant Double deriving (Show, Eq)
|
janm399/equationsolver
|
src/EquationSolver/Common.hs
|
apache-2.0
| 849
| 0
| 8
| 196
| 144
| 86
| 58
| 12
| 0
|
{-# LANGUAGE Arrows #-}
module Marvin.Examples.NetworkIntrusionDetection where
import Marvin.API
import Marvin.API.Algorithms.KMeans
import Data.List.Split
import Control.Arrow
anomalyExamples path = do
Right riskOfAnomaly <- mkAnomalyDetector path
let seemsNormal = "0,tcp,http,SF,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,2,"
++ "0.00,0.00,0.00,0.00,1.00,0.00,1.00,1,69,1.00,0.00,1.00,0.04,0.00,0.00,0.00,0.00,normal."
let tooManyConnections = "0,tcp,http,SF,214,5301,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,2,"
++ "0.00,0.00,0.00,0.00,1.00,0.00,1.00,1,69,1.00,0.00,1.00,0.04,0.00,0.00,0.00,0.00,normal."
print $ "normal: " ++ show (riskOfAnomaly seemsNormal)
print $ "strange: " ++ show (riskOfAnomaly tooManyConnections)
mkAnomalyDetector :: FilePath -> IO (Fallible (String -> Fallible Double))
mkAnomalyDetector path = do
csv <- fromCsv ',' NoHeader path
return $ do
let kmeans = KMeans { k = 10, numberOfIterations = 10 }
raw <- csv
model <- fit kmeans (preproc, raw)
let distances = askModel model distancesFromNearestCentroids
return $ distanceByOne distances
distanceByOne :: (RawTable -> Fallible NumericColumn) -> String -> Fallible Double
distanceByOne batchDistance connection = do
rawTable <- fromRowsToRaw [splitOn "," connection]
distance <- batchDistance rawTable
return $ head $ toList distance
preproc :: Pipeline RawTable NumericTable
preproc = proc raw -> do
rawWithoutLabel <- inject -< removeColumn lastColumn raw
let tab = smartParseTable rawWithoutLabel
let noms = nominalColumns tab
let nums = numericColumns tab
let bins = binaryToNumeric $ binaryColumns tab
let nats = naturalToNumeric $ naturalColumns tab
encoded <- transform oneHotEncode -< noms
allNums <- inject -< featureUnion [nums, bins, nats]
normalized <- transform standardize -< allNums
all <- inject -< featureUnion [normalized, binaryToNumeric encoded]
returnA -< all
|
gaborhermann/marvin
|
src/Marvin/Examples/NetworkIntrusionDetection.hs
|
apache-2.0
| 1,948
| 1
| 14
| 313
| 512
| 243
| 269
| 41
| 1
|
{-# LANGUAGE LambdaCase, ScopedTypeVariables, FlexibleContexts #-}
module Crypto.GarbledCircuits.Util
( bind2
, bits2Word
, word2Bits
, evalProg
, progSize
, ungarble
, showWirelabel
, inputSize
, inputPairs
, inputWires
, nextRef
, inputp
, internp
, writep
, lookupC
, lsb
, readGGInput
, readTTInput
, sel
, sortedInput
, orBytes
, xorBytes
, xorWords
, mask
, err
, (!!!)
, trace
, traceM
)
where
import Crypto.GarbledCircuits.Types
import Control.Monad.State
import Data.Bits hiding (xor)
import qualified Data.Bits
import qualified Data.ByteString as BS
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
import qualified Data.Set as S
import Data.Tuple
import Data.Word
import Data.Ord (comparing)
import Data.List
import Numeric (showHex)
import Prelude hiding (traverse)
#ifdef DEBUG
import Debug.Trace
#else
trace :: String -> a -> a
trace = flip const
traceM :: Monad m => String -> m ()
traceM _ = return ()
#endif
--------------------------------------------------------------------------------
-- general helper functions
bind2 :: Monad m => (a -> b -> m c) -> m a -> m b -> m c
bind2 f a b = do x <- a; y <- b; f x y
-- returns a little-endian list of bits
word2Bits :: (FiniteBits b, Num b, Ord b, Bits b) => b -> [Bool]
word2Bits x = map (bitAnd x) (take (finiteBitSize x) pow2s)
where
bitAnd a b = a .&. b > 0
-- takes a little-endian list of bits
bits2Word :: (Bits a, Num a) => [Bool] -> a
bits2Word bs = sum $ zipWith select bs pow2s
where
select b x = if b then x else 0
pow2s :: (Num b, Bits b) => [b]
pow2s = [ shift 1 x | x <- [0..] ]
xorBytes :: ByteString -> ByteString -> ByteString
xorBytes x y | BS.length x /= BS.length y = err "xor" "unequal length inputs"
| otherwise = BS.pack $ BS.zipWith Data.Bits.xor x y
orBytes :: ByteString -> ByteString -> ByteString
orBytes x y | BS.length x /= BS.length y = err "or" "unequal length inputs"
| otherwise = BS.pack $ BS.zipWith (.|.) x y
xorWords :: [Word8] -> [Word8] -> [Word8]
xorWords = zipWith Data.Bits.xor
progSize :: Program c -> Int
progSize = M.size . prog_env
inputSize :: Party -> Program c -> Int
inputSize p prog = S.size (prog_inputs p prog)
--------------------------------------------------------------------------------
-- garbled gate helpers
lsb :: Wirelabel -> Bool
lsb wl = BS.last wl .&. 1 > 0
sel :: Bool -> WirelabelPair -> Wirelabel
sel b = if b then wlp_true else wlp_false
mask :: Bool -> Wirelabel -> Wirelabel
mask b wl = if b then wl else zeroWirelabel
inputPairs :: Party -> Program GarbledGate -> Context -> [WirelabelPair]
inputPairs p prog ctx = map (ctx_pairs ctx !!!) (sortedInput readGGInput p prog)
inputWires :: Party -> Program GarbledGate -> Context -> [Bool] -> [Wirelabel]
inputWires party prog ctx inp = zipWith sel inp (inputPairs party prog ctx)
ungarble :: Context -> Wirelabel -> Bool
ungarble ctx wl = case M.lookup wl (ctx_truth ctx) of
Nothing -> err "ungarble" $ "unknown wirelabel: " ++ showWirelabel wl
Just b -> b
showWirelabel :: Wirelabel -> String
showWirelabel wl = "wl" ++ showCol (lsb wl) ++ " " ++ hexStr
where showCol b = if b then "1" else "0"
hexStr = concatMap (pad . hex) $ BS.unpack wl
pad s = if length s == 1 then '0' : s else s
hex = flip showHex ""
--------------------------------------------------------------------------------
-- polymorphic helper functions for State monads over a Program
nextRef :: (Ord c, MonadState (Program c) m) => m (Ref c)
nextRef = do
env <- gets prog_env
return $ succ (fst (M.findMax env))
internp :: (Ord c, MonadState (Program c) m) => c -> m (Ref c)
internp circ = do
prog <- get
let env = prog_env prog
dedup = map swap (M.toList env)
case lookup circ dedup of
Just ref -> return ref
Nothing -> do
let ref = if M.null env then Ref 0 else succ $ fst (M.findMax env)
env' = M.insert ref circ env
put prog { prog_env = env' }
return ref
inputp :: (Ord c, MonadState (Program c) m) => Party -> c -> m (Ref c)
inputp party inp = do
ref <- internp inp
modify $ \p -> case party of
Garbler -> p { prog_input_gb = S.insert ref (prog_input_gb p) }
Evaluator -> p { prog_input_ev = S.insert ref (prog_input_ev p) }
return ref
writep :: (Ord c, MonadState (Program c) m) => Ref c -> c -> m ()
writep ref circ = modify (\p -> p { prog_env = M.insert ref circ (prog_env p) })
lookupC :: Ref c -> Program c -> c
lookupC ref prog = fromMaybe (error "[lookupC] no c") (M.lookup ref (prog_env prog))
readTTInput :: TruthTable -> InputId
readTTInput (TTInp i p) = i
readTTInput _ = undefined
readGGInput :: GarbledGate -> InputId
readGGInput (GarbledInput i p) = i
readGGInput _ = undefined
-- Program c -> [Ref c] -> [(Ref c, c)] -> Sorted [(Ref c, c)] -> [Ref c]
sortedInput :: (c -> InputId) -> Party -> Program c -> [Ref c]
sortedInput readInputId party prog = fst <$> sortBy byInputId inputs
where
-- [Ref c]
inputRefs = S.toList $ prog_inputs party prog
-- Program c -> Ref c -> (Ref c, c)
findC prog ref = (ref, lookupC ref prog)
-- [(Ref c, c)]
inputs = findC prog <$> inputRefs
-- (Ref c, c) -> Int
inputIdField = getInputId . readInputId . snd
-- ((Ref c, c) -> (Ref c, c) -> Ordering)
byInputId = comparing inputIdField
--------------------------------------------------------------------------------
-- polymorphic evaluation
evalProg :: (Show b, CanHaveChildren c)
=> (Ref c -> c -> [b] -> b) -> Program c -> [b]
evalProg construct prog = outputs
where
resultMap = execState (traverse construct prog) M.empty
outputs = map (resultMap !!!) (prog_output prog)
traverse :: (Show b, MonadState (Map (Ref c) b) m, CanHaveChildren c)
=> (Ref c -> c -> [b] -> b) -> Program c -> m ()
traverse construct prog = mapM_ eval (M.keys (prog_env prog))
where
getVal ref = get >>= \precomputed ->
case M.lookup ref precomputed of
Nothing -> err "traverse.getVal" ("unknown ref: " ++ show ref)
Just res -> return res
eval ref = do
let c = lookupC ref prog
kids <- mapM getVal (children c)
let result = construct ref c kids
modify (M.insert ref result)
return result
--------------------------------------------------------------------------------
-- evil helpers
err :: String -> String -> a
err name warning = error $ "[" ++ name ++ "] " ++ warning
(!!!) :: (Show k, Show v, Ord k) => Map k v -> k -> v
m !!! k = case M.lookup k m of
Nothing -> err "!!!" ("OOPS: " ++ show m)
Just v -> v
|
spaceships/garbled-circuits
|
src/Crypto/GarbledCircuits/Util.hs
|
apache-2.0
| 6,727
| 0
| 20
| 1,591
| 2,384
| 1,233
| 1,151
| 154
| 3
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE NoImplicitPrelude #-}
module HERMIT.Lemma
( -- * Clause
Clause(..)
, mkClause
, mkForall
, addBinder
, collectQs
, instClause
, instsClause
, discardUniVars
, freeVarsClause
, clauseSyntaxEq
, substClause
, substClauses
, dropBinders
, redundantDicts
-- * Lemmas
, LemmaName(..)
, Lemma(..)
, Proven(..)
, andP, orP
, Used(..)
, Lemmas
, NamedLemma
) where
import Prelude.Compat hiding (lookup)
import Control.Monad.Compat
import Data.Dynamic (Typeable)
import Data.String (IsString(..))
import qualified Data.Map as M
import GHC.Generics
import HERMIT.Core
import HERMIT.GHC hiding ((<>))
import Language.KURE.MonadCatch
----------------------------------------------------------------------------
-- | Build a Clause from a list of universally quantified binders and two expressions.
-- If the head of either expression is a lambda expression, it's binder will become a universally quantified binder
-- over both sides. It is assumed the two expressions have the same type.
--
-- Ex. mkClause [] (\x. foo x) bar === forall x. foo x = bar x
-- mkClause [] (baz y z) (\x. foo x x) === forall x. baz y z x = foo x x
-- mkClause [] (\x. foo x) (\y. bar y) === forall x. foo x = bar x
mkClause :: [CoreBndr] -> CoreExpr -> CoreExpr -> Clause
mkClause vs lhs rhs = redundantDicts $ dropBinders $ mkForall (tvs++vs++lbs++rbs) (Equiv lhs' rbody)
where (lbs, lbody) = collectBinders lhs
rhs' = uncurry mkCoreApps $ betaReduceAll rhs $ map varToCoreExpr lbs
(rbs, rbody) = collectBinders rhs'
lhs' = mkCoreApps lbody $ map varToCoreExpr rbs
-- now quantify over the free type variables
tvs = varSetElems
$ filterVarSet isTyVar
$ delVarSetList (unionVarSets $ map freeVarsExpr [lhs',rbody]) (vs++lbs++rbs)
freeVarsClause :: Clause -> VarSet
freeVarsClause (Forall b cl) = delVarSet (freeVarsClause cl) b
freeVarsClause (Conj q1 q2) = unionVarSets $ map freeVarsClause [q1,q2]
freeVarsClause (Disj q1 q2) = unionVarSets $ map freeVarsClause [q1,q2]
freeVarsClause (Impl _ q1 q2) = unionVarSets $ map freeVarsClause [q1,q2]
freeVarsClause (Equiv e1 e2) = unionVarSets $ map freeVarsExpr [e1,e2]
freeVarsClause CTrue = emptyVarSet
dropBinders :: Clause -> Clause
dropBinders (Forall b cl) =
let cl' = dropBinders cl
in if b `elemVarSet` freeVarsClause cl'
then addBinder b cl'
else cl'
dropBinders (Conj q1 q2) = Conj (dropBinders q1) (dropBinders q2)
dropBinders (Disj q1 q2) = Disj (dropBinders q1) (dropBinders q2)
dropBinders (Impl nm q1 q2) = Impl nm (dropBinders q1) (dropBinders q2)
dropBinders other = other
addBinder :: CoreBndr -> Clause -> Clause
addBinder = Forall
mkForall :: [CoreBndr] -> Clause -> Clause
mkForall = flip (foldr Forall)
collectQs :: Clause -> ([CoreBndr], Clause)
collectQs (Forall b cl) = (b:bs, cl')
where (bs, cl') = collectQs cl
collectQs cl = ([],cl)
-- | A name for lemmas. Use a newtype so we can tab-complete in shell.
newtype LemmaName = LemmaName String deriving (Eq, Ord, Typeable)
instance Monoid LemmaName where
mempty = LemmaName mempty
mappend (LemmaName n1) (LemmaName n2) = LemmaName (mappend n1 n2)
instance IsString LemmaName where fromString = LemmaName
instance Show LemmaName where show (LemmaName s) = s
-- | An equality with a proven/used status.
data Lemma = Lemma { lemmaC :: Clause
, lemmaP :: Proven -- whether lemma has been proven
, lemmaU :: Used -- whether lemma has been used
} deriving Typeable
data Proven = Proven
| Assumed -- ^ Assumed by user
| BuiltIn -- ^ Assumed by library/HERMIT
| NotProven
deriving (Eq, Typeable)
instance Show Proven where
show Proven = "Proven"
show Assumed = "Assumed"
show BuiltIn = "Built In"
show NotProven = "Not Proven"
instance Enum Proven where
toEnum 1 = Assumed
toEnum 2 = BuiltIn
toEnum 3 = Proven
toEnum _ = NotProven
fromEnum NotProven = 0
fromEnum Assumed = 1
fromEnum BuiltIn = 2
fromEnum Proven = 3
-- Ordering: NotProven < Assumed < BuiltIn < Proven
instance Ord Proven where
compare :: Proven -> Proven -> Ordering
compare p1 p2 = compare (fromEnum p1) (fromEnum p2)
-- When conjuncting, result is as proven as the least of the two
andP :: Proven -> Proven -> Proven
andP = min
-- When disjuncting, result is as proven as the most of the two
orP :: Proven -> Proven -> Proven
orP = max
data Used = Obligation -- ^ this MUST be proven immediately
| UnsafeUsed -- ^ used, but can be proven later (only introduced in unsafe shell)
| NotUsed
deriving (Eq, Generic, Typeable)
instance Show Used where
show Obligation = "Obligation"
show UnsafeUsed = "Used"
show NotUsed = "Not Used"
data Clause = Forall CoreBndr Clause
| Conj Clause Clause
| Disj Clause Clause
| Impl LemmaName Clause Clause -- ^ name for the antecedent when it is in scope
| Equiv CoreExpr CoreExpr
| CTrue -- the always true clause
deriving Typeable
-- | A collection of named lemmas.
type Lemmas = M.Map LemmaName Lemma
-- | A LemmaName, Lemma pair.
type NamedLemma = (LemmaName, Lemma)
------------------------------------------------------------------------------
discardUniVars :: Clause -> Clause
discardUniVars (Forall _ cl) = discardUniVars cl
discardUniVars cl = cl
------------------------------------------------------------------------------
-- | Assumes Var is free in Clause. If not, no substitution will happen, though uniques might be freshened.
substClause :: Var -> CoreArg -> Clause -> Clause
substClause v e = substClauses [(v,e)]
substClauses :: [(Var,CoreArg)] -> Clause -> Clause
substClauses ps cl = substClauseSubst (extendSubstList sub ps) cl
where (vs,es) = unzip ps
sub = mkEmptySubst
$ mkInScopeSet
$ delVarSetList (unionVarSets $ freeVarsClause cl : map freeVarsExpr es) vs
-- | Note: Subst must be properly set up with an InScopeSet that includes all vars
-- in scope in the *range* of the substitution.
substClauseSubst :: Subst -> Clause -> Clause
substClauseSubst = go
where go subst (Forall b cl) =
let (subst',b') = substBndr subst b
in addBinder b' (go subst' cl)
go _ CTrue = CTrue
go subst (Conj q1 q2) = Conj (go subst q1) (go subst q2)
go subst (Disj q1 q2) = Disj (go subst q1) (go subst q2)
go subst (Impl nm q1 q2) = Impl nm (go subst q1) (go subst q2)
go subst (Equiv e1 e2) =
let e1' = substExpr (text "substClauseSubst e1") subst e1
e2' = substExpr (text "substClauseSubst e2") subst e2
in Equiv e1' e2'
------------------------------------------------------------------------------
redundantDicts :: Clause -> Clause
redundantDicts = go []
where go tys (Forall b cl)
| isDictTy bTy =
case [ varToCoreExpr pb | (pb,ty) <- tys, eqType bTy ty ] of
[] -> addBinder b $ go ((b,bTy):tys) cl -- not seen before
(b':_) -> substClause b b' cl -- seen
| otherwise = addBinder b (go tys cl)
where bTy = varType b
go _ cl = cl
------------------------------------------------------------------------------
-- | Instantiate one of the universally quantified variables in a 'Clause'.
-- Note: assumes implicit ordering of variables, such that substitution happens to the right
-- as it does in case alternatives. Only first variable that matches predicate is
-- instantiated.
instClause :: MonadCatch m => VarSet -- vars in scope
-> (Var -> Bool) -- predicate to select var
-> CoreExpr -- expression to instantiate with
-> Clause -> m Clause
instClause inScope p e = prefixFailMsg "clause instantiation failed: " . liftM fst . go []
where go bs (Forall b cl)
| p b = do -- quantified here, so do substitution and start bubbling up
let (eTvs, eTy) = splitForAllTys $ exprKindOrType e
tyVars = eTvs ++ filter isTyVar bs
failMsg = fail "type of provided expression differs from selected binder."
bindFn v = if v `elem` tyVars then BindMe else Skolem
sub <- maybe failMsg return $ tcUnifyTys bindFn [varType b] [eTy]
-- if b is a tyvar, we know e is a type, so free vars will be tyvars
let e' = mkCoreApps e [ case lookupTyVar sub v of
Nothing -> Type (mkTyVarTy v)
Just ty -> Type ty
| v <- eTvs ]
cl' = substClause b e' cl
newBs = varSetElems
$ filterVarSet (\v -> not (isId v) || isLocalId v)
$ delVarSetList (minusVarSet (freeVarsExpr e') inScope) bs
return (replaceVars sub newBs cl', sub)
| otherwise = do
(cl', sub) <- go (b:bs) cl
return (replaceVars sub [b] cl', sub)
go bs (Conj q1 q2) = go2 bs Conj q1 q2
go bs (Disj q1 q2) = go2 bs Disj q1 q2
go bs (Impl nm q1 q2) = go2 bs (Impl nm) q1 q2
go _ _ = fail "specified variable is not universally quantified."
go2 bs con q1 q2 = do
er <- attemptM $ go bs q1
case er of
Right (q1',s) -> return (con q1' q2, s)
Left _ -> do
er' <- attemptM $ go bs q2
case er' of
Right (q2',s) -> return (con q1 q2', s)
Left msg -> fail msg
-- | The function which 'bubbles up' after the instantiation takes place,
-- replacing any type variables that were instantiated as a result of specialization
-- and rebuilding the foralls.
replaceVars :: TvSubst -> [Var] -> Clause -> Clause
replaceVars sub vs = go (reverse vs)
where go [] cl = cl
go (b:bs) cl
| isTyVar b = case lookupTyVar sub b of
Nothing -> go bs (addBinder b cl)
Just ty -> let new = varSetElems (freeVarsType ty)
in go (new++bs) (substClause b (Type ty) cl)
| otherwise = go bs (addBinder b cl)
-- tvSubstToSubst :: TvSubst -> Subst
-- tvSubstToSubst (TvSubst inS tEnv) = mkSubst inS tEnv emptyVarEnv emptyVarEnv
-- | Instantiate a set of universally quantified variables in a 'Clause'.
-- It is important that all type variables appear before any value-level variables in the first argument.
instsClause :: MonadCatch m => VarSet -> [(Var,CoreExpr)] -> Clause -> m Clause
instsClause inScope = flip (foldM (\ q (v,e) -> instClause inScope (==v) e q)) . reverse
-- foldM is a left-to-right fold, so the reverse is important to do substitutions in reverse order
-- which is what we want (all value variables should be instantiated before type variables).
------------------------------------------------------------------------------
-- Syntactic Equality
-- | Syntactic Equality of clauses.
clauseSyntaxEq :: Clause -> Clause -> Bool
clauseSyntaxEq (Forall b1 c1) (Forall b2 c2) = (b1 == b2) && clauseSyntaxEq c1 c2
clauseSyntaxEq (Conj q1 q2) (Conj p1 p2) = clauseSyntaxEq q1 p1 && clauseSyntaxEq q2 p2
clauseSyntaxEq (Disj q1 q2) (Disj p1 p2) = clauseSyntaxEq q1 p1 && clauseSyntaxEq q2 p2
clauseSyntaxEq (Impl n1 q1 q2) (Impl n2 p1 p2) = n1 == n2 && clauseSyntaxEq q1 p1 && clauseSyntaxEq q2 p2
clauseSyntaxEq (Equiv e1 e2) (Equiv e1' e2') = exprSyntaxEq e1 e1' && exprSyntaxEq e2 e2'
clauseSyntaxEq _ _ = False
------------------------------------------------------------------------------
|
beni55/hermit
|
src/HERMIT/Lemma.hs
|
bsd-2-clause
| 12,331
| 0
| 21
| 3,583
| 3,157
| 1,648
| 1,509
| 212
| 9
|
-- | The TrackerP module is responsible for keeping in touch with the Tracker
-- of a torrent. The tracker is contacted periodically, and we exchange
-- information with it. Specifically, we tell the tracker how much we have
-- downloaded, uploaded and what is left. We also tell it about our current
-- state (i.e., are we a seeder or a leecher?).
--
-- The tracker responds to us with a new set of Peers and general information
-- about the torrent in question. It may also respond with an error in which
-- case we should present it to the user.
--
{-# LANGUAGE CPP #-}
module Process.Tracker
( start
)
where
#if __GLASGOW_HASKELL__ <= 708
import AdaptGhcVersion
#endif
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad.Reader
import Control.Monad.State hiding (state)
import Data.Bits
import Data.Char (chr, ord)
import Data.List (partition)
import Numeric (showHex)
import qualified Data.ByteString as B
import Data.Word
import Network.Socket as S
import Network.HTTP hiding (port, urlEncode, urlEncodeVars)
import Network.URI hiding (unreserved, reserved)
import Network.Stream
import Control.Exception
import Protocol.BCode as BCode hiding (encode, announceList)
import Process
import Channels
import Supervisor
import Torrent
import qualified Process.Status as Status
import qualified Process.PeerMgr as PeerMgr
import qualified Process.Timer as Timer
-- | The tracker state is used to tell the tracker our current state. In order
-- to output it correctly, we override the default show instance with the
-- version below. This may be wrong to do in the long run, but for now it works
-- fine.
--
-- The state is either started or stopped upon the client starting. The
-- tracker will create an entry for us if we tell it that we started, and it
-- will tear down this entry if we tell it that we stopped. It will know if
-- we are a seeder or a leecher based on how much data is left for us to
-- download.
--
-- the 'Completed' entry is used once in the lifetime of a torrent. It
-- explains to the tracker that we completed the torrent in question.
data TrackerEvent = Started | Stopped | Completed | Running
deriving Eq
-- | The tracker will in general respond with a BCoded dictionary. In our world, this is
-- not the data structure we would like to work with. Hence, we parse the structure into
-- the ADT below.
data TrackerResponse = ResponseOk { newPeers :: [PeerMgr.Peer],
completeR :: Maybe Integer,
incompleteR :: Maybe Integer,
timeoutInterval :: Integer,
timeoutMinInterval :: Maybe Integer }
| ResponseDecodeError B.ByteString
| ResponseWarning B.ByteString
| ResponseError B.ByteString
-- | If we fail to contact the tracker, we will wait for 15 minutes. The number is quite arbitrarily chosen
failTimerInterval :: Integer
failTimerInterval = 15 * 60
-- | Configuration of the tracker process
data CF = CF {
statusPCh :: Status.StatusChannel
, trackerMsgCh :: TrackerChannel
, peerMgrCh :: PeerMgr.PeerMgrChannel
, cfInfoHash :: InfoHash
}
instance Logging CF where
logName _ = "Process.Tracker"
-- | Internal state of the tracker CHP process
data ST = ST {
torrentInfo :: TorrentInfo
, announceList :: [[AnnounceURL]] -- will store it separate from TorrentInfo as it could be updated
, peerId :: PeerId
, state :: TrackerEvent
, localPort :: Word16
, nextTick :: Integer
}
start :: InfoHash -> TorrentInfo -> PeerId -> Word16
-> Status.StatusChannel -> TrackerChannel -> PeerMgr.PeerMgrChannel
-> SupervisorChannel -> IO ThreadId
start ih ti pid port statusC msgC pc supC =
spawnP (CF statusC msgC pc ih) (ST ti (announceURLs ti) pid Stopped port 0)
({-# SCC "Tracker" #-} cleanupP loop
(defaultStopHandler supC)
stopEvent)
where
stopEvent = modify (\s -> s { state = Stopped }) >> talkTracker
loop = do
ch <- asks trackerMsgCh
msg <- liftIO . atomically $ readTChan ch
debugP $ "Got tracker event"
case msg of
TrackerTick x ->
do t <- gets nextTick
when (x+1 == t) talkTracker
Stop ->
modify (\s -> s { state = Stopped }) >> talkTracker
Start ->
modify (\s -> s { state = Started }) >> talkTracker
Complete ->
modify (\s -> s { state = Completed }) >> talkTracker
loop
talkTracker = pokeTracker >>= timerUpdate
eventTransition :: Process CF ST ()
eventTransition = do
st <- gets state
modify (\s -> s { state = newS st})
where newS st =
case st of
Running -> Running
Stopped -> Stopped
Completed -> Running
Started -> Running
-- | Poke the tracker. It returns the new timer intervals to use
pokeTracker :: Process CF ST (Integer, Maybe Integer)
pokeTracker = do
v <- liftIO $ newEmptyTMVarIO
ih <- asks cfInfoHash
asks statusPCh >>=
(\ch -> liftIO . atomically $ writeTChan ch (Status.RequestStatus ih v))
upDownLeft <- liftIO . atomically $ takeTMVar v
resp <- queryTrackers upDownLeft
case resp of
Left err -> do infoP $ "Tracker HTTP Error: " ++ err
return (failTimerInterval, Just failTimerInterval)
Right (ResponseWarning wrn) ->
do infoP $ "Tracker Warning Response: " ++ fromBS wrn
return (failTimerInterval, Just failTimerInterval)
Right (ResponseError err) ->
do infoP $ "Tracker Error Response: " ++ fromBS err
return (failTimerInterval, Just failTimerInterval)
Right (ResponseDecodeError err) ->
do infoP $ "Response Decode error: " ++ fromBS err
return (failTimerInterval, Just failTimerInterval)
Right bc -> do
c <- asks peerMgrCh
liftIO . atomically $ writeTChan c (PeerMgr.PeersFromTracker ih $ newPeers bc)
let trackerStats = Status.TrackerStat
{ Status.trackInfoHash = ih
, Status.trackComplete = completeR bc
, Status.trackIncomplete = incompleteR bc }
asks statusPCh >>= \ch -> liftIO . atomically $ writeTChan ch trackerStats
eventTransition
return (timeoutInterval bc, timeoutMinInterval bc)
timerUpdate :: (Integer, Maybe Integer) -> Process CF ST ()
timerUpdate (timeout, _minTimeout) = do
st <- gets state
when (st == Running)
(do t <- tick
ch <- asks trackerMsgCh
_ <- Timer.registerSTM (fromIntegral timeout) ch (TrackerTick t)
debugP $ "Set timer to: " ++ show timeout)
where tick = do t <- gets nextTick
modify (\s -> s { nextTick = t + 1 })
return t
-- Process a result dict into a tracker response object.
processResultDict :: BCode -> TrackerResponse
processResultDict d =
case BCode.trackerError d of
Just err -> ResponseError err
Nothing -> case BCode.trackerWarning d of
Just warn -> ResponseWarning warn
Nothing -> case decodeOk of
Nothing -> ResponseDecodeError . toBS $
"Could not decode response properly"
Just rok -> rok
where decodeOk =
ResponseOk <$> (decodeIps <$> BCode.trackerPeers d)
<*> (pure $ BCode.trackerComplete d)
<*> (pure $ BCode.trackerIncomplete d)
<*> (BCode.trackerInterval d)
<*> (pure $ BCode.trackerMinInterval d)
decodeIps :: (B.ByteString, B.ByteString) -> [PeerMgr.Peer]
decodeIps (ipv4, ipv6) = decodeIps4 ipv4 ++ decodeIps6 ipv6
decodeIps4 :: B.ByteString -> [PeerMgr.Peer]
decodeIps4 bs | B.null bs = []
| B.length bs >= 6 =
let (ip, r1) = B.splitAt 4 bs
(port, r2) = B.splitAt 2 r1
i' = cW32 ip
p' = fromIntegral $ cW16 port
in PeerMgr.Peer (S.SockAddrInet p' i') : decodeIps4 r2
| otherwise = [] -- Some trackers fail spectacularly
decodeIps6 :: B.ByteString -> [PeerMgr.Peer]
decodeIps6 bs | B.null bs = []
| B.length bs >= 18 =
let (ip6, r1) = B.splitAt 16 bs
(port, r2) = B.splitAt 2 r1
i' = cW128 ip6
p' = fromIntegral $ cW16 port
in PeerMgr.Peer (S.SockAddrInet6 p' 0 i' 0) : decodeIps6 r2
| otherwise = [] -- Some trackers fail spectacularly
cW32 :: B.ByteString -> Word32
cW32 bs = fromIntegral . sum $ s
where up = B.unpack bs
s = [ fromIntegral b `shiftL` sa | (b, sa) <- zip up [0,8,16,24]] :: [Word32]
cW16 :: B.ByteString -> Word16
cW16 bs = fromIntegral . sum $ s
where s = [ fromIntegral b `shiftL` sa | (b, sa) <- zip (B.unpack bs) [0,8]] :: [Word16]
cW128 :: B.ByteString -> (Word32, Word32, Word32, Word32)
cW128 bs =
let (q1, r1) = B.splitAt 4 bs
(q2, r2) = B.splitAt 4 r1
(q3, q4) = B.splitAt 4 r2
in (cW32 q1, cW32 q2, cW32 q3, cW32 q4)
bubbleUpURL :: AnnounceURL -> [AnnounceURL] -> Process CF ST ()
bubbleUpURL _ (_:[]) = return ()
bubbleUpURL _ [] = return ()
bubbleUpURL url tier@(x:_) = if url == x
then return ()
else do
alist <- gets announceList
let newTier = url : filter (/=url) tier
newAnnounceList = map (\a -> if a /= tier then a else newTier) alist
_ <- modify (\s -> s { announceList = newAnnounceList })
return ()
tryThisTier' :: Status.StatusState -> [AnnounceURL] -> Process CF ST (Either String (AnnounceURL, TrackerResponse))
tryThisTier' _ [] = return $ Left "Empty announce-list"
tryThisTier' s (x:xs) = do url <- buildRequestURL s x
uri <- case parseURI url of
Nothing -> fail $ "Could not parse the url " ++ url
Just u -> return u
resp <- trackerRequest uri
case resp of
Left m -> if null xs
then return $ Left m
else tryThisTier' s xs
Right r -> return $ Right (x, r)
-- | from BEP0012: try first element in list, if it's can't be reached, then second, and so on
-- first successfull URL will bubble up and become the new head of this tier
-- announceList stored in State should be updated to reflect the changes
tryThisTier :: Status.StatusState -> [AnnounceURL] -> Process CF ST (Either String TrackerResponse)
tryThisTier params tier = do resp <- tryThisTier' params tier
case resp of
Left m -> return $ Left m
Right (url, r) -> do bubbleUpURL url tier
return $ Right r
queryTrackers' :: Status.StatusState -> [[AnnounceURL]] -> Process CF ST (Either String TrackerResponse)
queryTrackers' _ [] = return $ Left "Empty announce-list"
queryTrackers' p (x:[]) = tryThisTier p x --last element, so return whatever it gives us
queryTrackers' p (x:xs) = do resp <- tryThisTier p x
case resp of
Left _ -> queryTrackers' p xs -- in case of error, move to the next tier
Right _ -> return $ resp -- if success just return result
queryTrackers :: Status.StatusState -> Process CF ST (Either String TrackerResponse)
queryTrackers ss = do alist <- gets announceList
queryTrackers' ss alist
-- TODO: Do not recurse infinitely here.
trackerRequest :: URI -> Process CF ST (Either String TrackerResponse)
trackerRequest uri =
do debugP $ "Querying URI: " ++ (show uri)
resp <- liftIO $ catch (simpleHTTP request) (\e -> let err = show (e :: IOException)
in return . Left . ErrorMisc $ err)
case resp of
Left x -> do let err = "Error connecting: " ++ show x
debugP err
return $ Left err
Right r ->
case rspCode r of
(2,_,_) ->
case BCode.decode . toBS . rspBody $ r of
Left pe -> return . Left . show $ pe
Right bc -> do debugP $ "Response: " ++ BCode.prettyPrint bc
return $ Right $ processResultDict bc
(3,_,_) ->
case findHeader HdrLocation r of
Nothing -> return $ Left (show r)
Just newURL -> case parseURI newURL of
Nothing -> return $ Left (show newURL)
Just u -> trackerRequest u
_ -> return $ Left (show r)
where request = Request {rqURI = uri,
rqMethod = GET,
rqHeaders = [],
rqBody = ""}
--- Construct a new request URL. Perhaps this ought to be done with the HTTP
--- client library
buildRequestURL :: Status.StatusState -> AnnounceURL -> Process CF ST String
buildRequestURL ss url = do params <- urlEncodeVars <$> buildRequestParams ss
let announceString = fromBS url
-- announce string might already have some
-- parameters in it
sep = if '?' `elem` announceString
then "&"
else "?"
return $ concat [announceString, sep, params]
-- copied from: the old HTTP library. this commit breaks it for us: b0177fa952a8d0f77e732cb817197864679b1c83
urlEncode :: String -> String
urlEncode [] = []
urlEncode (h:t) = let str = if reserved (ord h) then escape h else [h]
in str ++ urlEncode t
where reserved x
| x >= ord 'a' && x <= ord 'z' = False
| x >= ord 'A' && x <= ord 'Z' = False
| x >= ord '0' && x <= ord '9' = False
| x <= 0x20 || x >= 0x7F = True
| otherwise = x `elem` map ord
[';','/','?',':','@','&'
,'=','+',',','$','{','}'
,'|','\\','^','[',']','`'
,'<','>','#','%','"']
escape x = '%':showHex (ord x) ""
urlEncodeVars :: [(String,String)] -> String
urlEncodeVars ((n,v):t) =
let (same,diff) = partition ((==n) . fst) t
in urlEncode n ++ '=' : foldl (\x y -> x ++ ',' : urlEncode y) (urlEncode $ v) (map snd same)
++ urlEncodeRest diff
where urlEncodeRest [] = []
urlEncodeRest diff = '&' : urlEncodeVars diff
urlEncodeVars [] = []
buildRequestParams :: Status.StatusState -> Process CF ST [(String, String)]
buildRequestParams ss = do
s <- get
p <- gets localPort
return $
[("info_hash", map (chr . fromIntegral) . B.unpack . infoHash . torrentInfo $ s),
("peer_id", peerId s),
("uploaded", show $ Status.uploaded ss),
("downloaded", show $ Status.downloaded ss),
("left", show $ Status.left ss),
("port", show p),
("compact", "1")] ++
(trackerfyEvent $ state s)
trackerfyEvent :: TrackerEvent -> [(String, String)]
trackerfyEvent ev =
case ev of
Running -> []
Completed -> [("event", "completed")]
Started -> [("event", "started")]
Stopped -> [("event", "stopped")]
|
jlouis/combinatorrent
|
src/Process/Tracker.hs
|
bsd-2-clause
| 16,279
| 0
| 22
| 5,699
| 4,275
| 2,213
| 2,062
| 294
| 7
|
{-# options -fno-warn-incomplete-patterns #-}
module Stdlib where
import Z3.Monad as Z3
import AST
import Data.Set (Set)
import qualified Data.Set as Set
opEq [VInt x, VInt y] = VBool (x == y)
opEq [VBool x, VBool y] = VBool (x == y)
opEq [VDom x, VDom y] = VBool (x == y)
opNot [VBool x] = VBool (not x)
opAnd [VBool x, VBool y] = VBool (x && y)
opOr [VBool x, VBool y] = VBool (x || y)
opIns [VInt x, VDom y] = VDom (Set.insert x y)
opDel [VInt x, VDom y] = VDom (Set.delete x y)
opUnion [VDom x, VDom y] = VDom (Set.union x y)
opIntersection [VDom x, VDom y] = VDom (Set.intersection x y)
opDiff [VDom x, VDom y] = VDom (Set.difference x y)
opIn [VInt x, VDom y] = VBool (Set.member x y)
opSubset [VDom x, VDom y] = VBool (Set.isSubsetOf x y)
opAdd [VInt x, VInt y] = VInt (x + y)
opMul [VInt x, VInt y] = VInt (x * y)
opSub [VInt x, VInt y] = VInt (x - y)
opNeg [VInt x] = VInt (-x)
opDiv [VInt x, VInt y] = VInt (x `div` y)
opMod [VInt x, VInt y] = VInt (x `mod` y)
opRem [VInt x, VInt y] = VInt (x `rem` y)
opLt [VInt x, VInt y] = VBool (x < y)
opLe [VInt x, VInt y] = VBool (x <= y)
opGt [VInt x, VInt y] = VBool (x > y)
opGe [VInt x, VInt y] = VBool (x >= y)
mkEq [x, y] = Z3.mkEq x y
mkNot [x] = Z3.mkNot x
mkAnd [x, y] = Z3.mkAnd [x, y]
mkOr [x, y] = Z3.mkOr [x, y]
mkIns [x, y] = Z3.mkSetAdd y x
mkDel [x, y] = Z3.mkSetDel y x
mkUnion [x, y] = Z3.mkSetUnion [x, y]
mkIntersection [x, y] = Z3.mkSetIntersect [x, y]
mkDiff [x, y] = Z3.mkSetDifference x y
mkIn [x, y] = Z3.mkSetMember x y
mkSubset [x, y] = Z3.mkSetSubset x y
mkAdd [x, y] = Z3.mkAdd [x, y]
mkMul [x, y] = Z3.mkMul [x, y]
mkSub [x, y] = Z3.mkSub [x, y]
mkNeg [x] = Z3.mkUnaryMinus x
mkDiv [x, y] = Z3.mkDiv x y
mkMod [x, y] = Z3.mkMod x y
mkRem [x, y] = Z3.mkRem x y
mkLt [x, y] = Z3.mkLt x y
mkLe [x, y] = Z3.mkLe x y
mkGt [x, y] = Z3.mkGt x y
mkGe [x, y] = Z3.mkGe x y
|
kcsmnt0/demesne
|
src/Stdlib.hs
|
bsd-3-clause
| 1,849
| 0
| 8
| 408
| 1,245
| 645
| 600
| 52
| 1
|
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Numeral.UK.Corpus
( corpus ) where
import Prelude
import Data.String
import Duckling.Lang
import Duckling.Numeral.Types
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {lang = UK}, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (NumeralValue 0)
[ "0"
, "нуль"
]
, examples (NumeralValue 1)
[ "1"
, "один"
]
, examples (NumeralValue 2)
[ "2"
, "02"
, "два"
]
, examples (NumeralValue 3)
[ "3"
, "три"
, "03"
]
, examples (NumeralValue 4)
[ "4"
, "чотири"
, "04"
]
, examples (NumeralValue 5)
[ "п‘ять"
, "5"
, "05"
]
, examples (NumeralValue 33)
[ "33"
, "тридцять три"
, "0033"
]
, examples (NumeralValue 14)
[ "14"
, "чотирнадцять"
]
, examples (NumeralValue 16)
[ "16"
, "шістнадцять"
]
, examples (NumeralValue 17)
[ "17"
, "сімнадцять"
]
, examples (NumeralValue 18)
[ "18"
, "вісімнадцять"
]
, examples (NumeralValue 525)
[ "п‘ятсот двадцять п‘ять"
, "525"
]
, examples (NumeralValue 1.1)
[ "1.1"
, "1.10"
, "01.10"
, "1 крапка 1"
, "один крапка один"
]
, examples (NumeralValue 0.77)
[ "0.77"
, ".77"
]
, examples (NumeralValue 100000)
[ "100000"
, "100к"
, "100К"
]
, examples (NumeralValue 3000000)
[ "3М"
, "3000К"
, "3000000"
]
, examples (NumeralValue 1200000)
[ "1200000"
, "1.2М"
, "1200К"
, ".0012Г"
]
, examples (NumeralValue (-1200000))
[ "-1200000"
, "мінус 1200000"
, "-1.2М"
, "-1200К"
, "-.0012Г"
]
]
|
rfranek/duckling
|
Duckling/Numeral/UK/Corpus.hs
|
bsd-3-clause
| 2,824
| 0
| 11
| 1,236
| 500
| 290
| 210
| 82
| 1
|
-----------------------------------------------------------------------------
--
-- Module : Language.Elm.TH.Json
-- Copyright : Copyright: (c) 2011-2013 Joey Eremondi
-- License : BSD3
--
-- Maintainer : joey.eremondi@usask.ca
-- Stability : experimental
-- Portability : portable
--
-- |
--
-----------------------------------------------------------------------------
module Language.Elm.TH.Json where
{-# LANGUAGE TemplateHaskell, QuasiQuotes, MultiWayIf #-}
import Language.Haskell.TH.Syntax
import Data.Aeson.TH
import qualified SourceSyntax.Module as M
import qualified SourceSyntax.Declaration as D
import qualified SourceSyntax.Expression as E
import qualified SourceSyntax.Literal as L
import qualified SourceSyntax.Location as Lo
import qualified SourceSyntax.Pattern as P
import qualified SourceSyntax.Type as T
import Data.List (isPrefixOf)
import Language.Haskell.TH.Desugar.Sweeten
import Language.Haskell.TH.Desugar
import Language.Elm.TH.Util
--import Parse.Expression (makeFunction)
import Control.Applicative
import Control.Monad
import Control.Monad.State (StateT)
import qualified Control.Monad.State as S
-- |Helper function to apply arguments to a function
applyArgs :: Exp -> [Exp] -> Exp
applyArgs fun args = foldl (\ accumFun nextArg -> AppE accumFun nextArg) fun args
fnComp = VarE $ mkName "."
-- | Helper function to generate a the names X1 .. Xn with some prefix X
nNames :: Int -> String -> SQ [Name]
nNames n base = do
let varStrings = map (\n -> base ++ show n) [1..n]
mapM liftNewName varStrings
-- | Variable for the getter function getting the nth variable from a Json
varNamed :: Exp
varNamed = VarE (mkName "JsonUtil.varNamed")
-- | Expression getting a named subvariable from a JSON object
getVarNamed :: String -> Exp
getVarNamed nstr = AppE (AppE varNamed jsonArgExp ) (LitE $ StringL nstr)
-- | Filter function to test if a dec is a data
-- Also filters out decs which types that can't be serialized, such as functions
isData :: Dec -> Bool
isData dec = (isData' dec) && (canSerial dec)
where
isData' DataD{} = True
isData' NewtypeD{} = True
isData' TySynD{} = True
isData' _ = False
canSerial (DataD _ _ _ ctors _) = all canSerialCtor ctors
canSerial (NewtypeD _ _ _ ctor _) = canSerialCtor ctor
canSerial (TySynD _ _ ty) = canSerialType ty
--can't serialize if type variables --TODO is this true?
canSerial _ = False
canSerialCtor (NormalC _ types) = all (canSerialType) (map snd types)
canSerialCtor (RecC _ types) = all (canSerialType) (map (\(_,_,c)->c) types)
canSerialType (ArrowT) = False
canSerialType t = all canSerialType (subTypes t)
--General helper functions
jsonArgName :: Name
jsonArgName = mkName "jsonArg"
jsonArgPat :: Pat
jsonArgPat = VarP jsonArgName
jsonArgExp :: Exp
jsonArgExp = VarE jsonArgName
fromJsonName :: Name -> Name
fromJsonName name = mkName $ "fromJson_" ++ nameToString name
toJsonName :: Name -> Name
toJsonName name = mkName $ "toJson_" ++ nameToString name
makeFromJson :: [Dec] -> SQ [Dec]
makeFromJson allDecs = do
let decs = filter isData allDecs
mapM fromJsonForDec decs
-- | Given a type, and an expression for an argument of type Json
-- return the expression which applies the proper fromJson function to that expression
fromJsonForType :: Type -> SQ Exp
--Type name not covered by Prelude
fromJsonForType (ConT name) = case (nameToString name) of
"Int" -> return $ VarE $ mkName "JsonUtil.intFromJson"
"Bool" -> return $ VarE $ mkName "JsonUtil.boolFromJson"
"Float" -> return $ VarE $ mkName "JsonUtil.floatFromJson"
"Double" -> return $ VarE $ mkName "JsonUtil.floatFromJson"
"String" -> return $ VarE $ mkName "JsonUtil.stringFromJson"
_ -> return $ VarE $ fromJsonName name
fromJsonForType (AppT ListT t) = do
subExp <- fromJsonForType t
return $ AppE (VarE $ mkName "JsonUtil.listFromJson") subExp
fromJsonForType (AppT (ConT name) t) = do
subExp <- fromJsonForType t
case (nameToString name) of
"Maybe" -> return $ AppE (VarE $ mkName "JsonUtil.maybeFromJson") subExp
fromJsonForType (AppT (AppT (ConT name) t1) t2) = do
sub1 <- fromJsonForType t1
sub2 <- fromJsonForType t2
case (nameToString name) of
"Data.Map.Map" -> return $ applyArgs (VarE $ mkName "JsonUtil.dictFromJson") [sub1, sub2]
s -> error $ "Unsupported json type " ++ s
fromJsonForType t
| isTupleType t = do
let tList = tupleTypeToList t
let n = length tList
--Generate the lambda to convert the list into a tuple
subFunList <- mapM fromJsonForType tList
argNames <- mapM (liftNewName . ("x" ++) . show) [1 .. n]
let argValues = map VarE argNames
let argPat = ListP $ map VarP argNames
let lambdaBody = TupE $ zipWith AppE subFunList argValues
let lambda = LamE [argPat] lambdaBody
let makeList = VarE $ mkName "makeList"
return $ InfixE (Just lambda) fnComp (Just makeList)
| otherwise = error $ "Can't make Json for type " ++ (show t)
-- |Given a type declaration, generate the function declaration
-- Which takes a Json object to a value of that type
fromJsonForDec :: Dec -> SQ Dec
--Special case: we only have one ctor, so we don't use a tag
fromJsonForDec dec@(DataD _ name _ [ctor] _deriving) = do
Match _pat fnBody _decs <- fromMatchForCtor 1 ctor
let argPat = jsonArgPat
let fnName = fromJsonName name
let fnClause = Clause [argPat] fnBody []
return $ FunD fnName [fnClause]
fromJsonForDec dec@(DataD _ name _ ctors _deriving) = do
let argTagExpression = AppE (VarE $ mkName "JsonUtil.getTag") jsonArgExp
let numCtors = length ctors
ctorMatches <- mapM (fromMatchForCtor numCtors) ctors
let fnExp = CaseE argTagExpression ctorMatches
let argPat = jsonArgPat
let fnName = fromJsonName name
let fnBody = NormalB fnExp
let fnClause = Clause [argPat] fnBody []
return $ FunD fnName [fnClause]
fromJsonForDec (NewtypeD cxt name tyBindings ctor nameList) =
fromJsonForDec $ DataD cxt name tyBindings [ctor] nameList
fromJsonForDec dec@(TySynD name _tyvars ty) = do
let fnName = fromJsonName name
fnBody <- NormalB <$> fromJsonForType ty
let fnClause = Clause [] fnBody []
return $ FunD fnName [fnClause]
fromMatchForCtor :: Int -> Con -> SQ Match
fromMatchForCtor numCtors (NormalC name strictTypes) = do
let types = map snd strictTypes
let leftHandSide = LitP $ StringL $ nameToString name
let ctorExp = VarE name
--Exp in TH, list in Haskell
contentListExpr <- NormalB <$> unpackContents numCtors jsonArgExp
fromJsonFunctions <- mapM fromJsonForType types
let intNames = map (("subVar" ++) . show) [1 .. length types]
subDataNames <- mapM liftNewName intNames
--We unpack each json var into its own named variable, so we can unpack them into different types
let subDataListPattern = ListP $ map VarP subDataNames
--let subDataExprs = map VarE subDataNames
let unJsonedExprList = zipWith AppE fromJsonFunctions (map VarE subDataNames)
let letExp = LetE [ValD subDataListPattern contentListExpr []] (applyArgs ctorExp unJsonedExprList)
let rightHandSide = NormalB $ letExp
return $ Match leftHandSide rightHandSide []
fromMatchForCtor _numCtors (RecC name vstList) = do
let nameTypes = map (\(a,_,b)->(nameToString a,b)) vstList
let matchPat = LitP $ StringL $ nameToString name
(subNames, subDecs) <- unzip <$> mapM getSubJsonRecord nameTypes
let body = NormalB $ if null subNames
then applyArgs subNames ctorExp
else LetE subDecs (applyArgs subNames ctorExp)
return $ Match matchPat body []
where
ctorExp = ConE name
applyArgs t accum = foldl (\ accum h -> AppE accum (VarE h)) accum t
-- | Generate a declaration, and a name bound in that declaration,
-- Which unpacks a value of the given type from the nth field of a JSON object
getSubJsonRecord :: (String, Type) -> SQ (Name, Dec)
-- We need special cases for lists and tuples, to unpack them
--TODO recursive case
getSubJsonRecord (field, t) = do
funToApply <- fromJsonForType t
subName <- liftNewName "subVar"
let subLeftHand = VarP subName
let subRightHand = NormalB $ AppE funToApply (getVarNamed field)
return (subName, ValD subLeftHand subRightHand [])
unpackContents :: Int -> Exp -> SQ Exp
unpackContents numCtors jsonValue = return $ applyArgs (VarE $ mkName "JsonUtil.unpackContents") [LitE $ IntegerL $ toInteger numCtors, jsonValue]
makeToJson allDecs = do
let decs = filter isData allDecs
mapM toJsonForDec decs
toJsonForType :: Type -> SQ Exp
toJsonForType (ConT name) = case (nameToString name) of
"Int" -> return $ VarE $ mkName "JsonUtil.intToJson"
"Bool" -> return $ VarE $ mkName "JsonUtil.boolToJson"
"Float" -> return $ VarE $ mkName "JsonUtil.floatToJson"
"Double" -> return $ VarE $ mkName "JsonUtil.floatToJson"
"String" -> return $ VarE $ mkName "JsonUtil.stringToJson"
_ -> return $ VarE $ toJsonName name
toJsonForType (AppT (AppT (ConT name) t1) t2) = do
sub1 <- toJsonForType t1
sub2 <- toJsonForType t2
case (nameToString name) of
"Data.Map.Map" -> return $ applyArgs (VarE $ mkName "JsonUtil.dictToJson") [sub1, sub2]
s -> error $ "Unsupported json type " ++ s
toJsonForType (AppT ListT t) = do
subExp <- toJsonForType t
return $ AppE (VarE $ mkName "JsonUtil.listToJson") subExp
toJsonForType (AppT (ConT name) t) = do
subExp <- toJsonForType t
case (nameToString name) of
"Maybe" -> return $ AppE (VarE $ mkName "JsonUtil.maybeToJson") subExp
toJsonForType t
| isTupleType t = do
let tList = tupleTypeToList t
let n = length tList
--Generate the lambda to convert the list into a tuple
subFunList <- mapM toJsonForType tList
argNames <- mapM (liftNewName . ("x" ++) . show) [1 .. n]
let argValues = map VarE argNames
let argPat = TupP $ map VarP argNames
--Get each tuple element as Json, then wrap them in a Json Array
let listExp = AppE (VarE $ mkName "Json.Array") (ListE $ zipWith AppE subFunList argValues)
return $ LamE [argPat] listExp
toJsonForDec :: Dec -> SQ Dec
toJsonForDec dec@(DataD _ name _ ctors _deriving) = do
let argPat = jsonArgPat
let argExp = jsonArgExp
let numCtors = length ctors
ctorMatches <- mapM (toMatchForCtor numCtors) ctors
let fnExp = CaseE jsonArgExp ctorMatches
let fnName = toJsonName name
let fnBody = NormalB fnExp
let fnClause = Clause [argPat] fnBody []
return $ FunD fnName [fnClause]
toJsonForDec (NewtypeD cxt name tyBindings ctor nameList) =
toJsonForDec $ DataD cxt name tyBindings [ctor] nameList
toJsonForDec dec@(TySynD name _tyvars ty) = do
let fnName = toJsonName name
fnBody <- NormalB <$> toJsonForType ty
let fnClause = Clause [] fnBody []
return $ FunD fnName [fnClause]
toJsonForDec dec = error $ "Unknown dec type" ++ (show dec)
toMatchForCtor :: Int -> Con -> SQ Match
toMatchForCtor numCtors (NormalC name strictTypes) = do
let types = map snd strictTypes
let numStrings = map (("subVar_" ++) . show) [1 .. length types]
subDataNames <- mapM liftNewName numStrings
let subDataPats = map VarP subDataNames
let leftHandSide = ConP name subDataPats
let subDataExprs = map VarE subDataNames
toJsonFunctions <- mapM toJsonForType types
let contentsList = ListE $ zipWith AppE toJsonFunctions subDataExprs
jsonValueExp <- packContents numCtors name contentsList
let rightHandSide = NormalB jsonValueExp
return $ Match leftHandSide rightHandSide []
--TODO is there ever a record with 0 args?
toMatchForCtor _numCtors (RecC name vstList) = do
let (adtNames, _, types) = unzip3 vstList
let n = length types
jsonNames <- nNames n "jsonVar"
let adtPats = map VarP adtNames
let matchPat = ConP name adtPats
jsonDecs <- mapM makeSubJsonRecord (zip3 types adtNames jsonNames)
dictName <- liftNewName "objectDict"
dictDec <- makeRecordDict name dictName jsonNames
let ret = AppE (VarE $ mkName "Json.Object") (VarE dictName)
let body = NormalB $ LetE (jsonDecs ++ [dictDec]) ret
return $ Match matchPat body []
-- | Generate the declaration of a dictionary mapping field names to values
-- to be used with the JSON Object constructor
makeRecordDict :: Name -> Name -> [Name] -> SQ Dec
makeRecordDict ctorName dictName jsonNames = do
let leftSide = VarP dictName
let jsonExps = map VarE jsonNames
let fieldNames = map (LitE . StringL . show) [1 .. (length jsonNames)]
let tuples = map (\(field, json) -> TupE [field, json]) (zip fieldNames jsonExps)
let ctorExp = LitE $ StringL $ nameToString ctorName
let ctorTuple = TupE [LitE $ StringL "tag", AppE (VarE (mkName "Json.String")) ctorExp ]
let tupleList = ListE $ [ctorTuple] ++ tuples
let rightSide = NormalB $ AppE (VarE $ mkName "Data.Map.fromList") tupleList
return $ ValD leftSide rightSide []
-- | Generate the declaration of a value converted to Json
-- given the name of an ADT value to convert
makeSubJsonRecord :: (Type, Name, Name) -> SQ Dec
-- We need special cases for lists and tuples, to unpack them
--TODO recursive case
makeSubJsonRecord (t, adtName, jsonName) = do
funToApply <- toJsonForType t
let subLeftHand = VarP jsonName
let subRightHand = NormalB $ AppE funToApply (VarE adtName)
return $ ValD subLeftHand subRightHand []
packContents :: Int -> Name -> Exp -> SQ Exp
packContents numCtors name contentList = do
return $ applyArgs (VarE $ mkName "JsonUtil.packContents") [LitE $ IntegerL $ toInteger numCtors, LitE $ StringL $ nameToString name, contentList]
|
JoeyEremondi/haskelm-old
|
src/Language/Elm/TH/Json.hs
|
bsd-3-clause
| 13,680
| 0
| 16
| 2,751
| 4,159
| 2,042
| 2,117
| -1
| -1
|
module Anatomy.AutoFlow where
import Data.Char (isSpace)
import Text.HTML.TagSoup
autoFlow :: String -> String
autoFlow = renderTags . autoFlow' False . canonicalizeTags . parseTags
where
autoFlow' open []
| open = [TagClose "p"]
| otherwise = []
autoFlow' open (o@(TagOpen n _):ts)
-- inline element, already in a <p>; carry on
| isPhrasing n && open = o : autoFlow' open ts
-- inline element, not in a <p>; start a <p>
| isPhrasing n = TagOpen "p" [] : o : autoFlow' True ts
-- opening a block element; </p>
| open = TagClose "p" : autoFlow' False (o:ts)
-- a block that can contain <p>
| isFlowable n = o : autoFlow' False tagContents ++ [TagClose n] ++ autoFlow' False rest
-- not <p>-able; leave it alone
| otherwise = o : tagContents ++ [TagClose n] ++ autoFlow' False rest
where
tagContents = getTagContent n (o:ts)
rest = drop (length tagContents + 1) ts
autoFlow' open (t@(TagText c):ts)
-- skip whitespace
| all isSpace c = t : autoFlow' open ts
-- a new paragraph, indicated by a linebreak
| open && head c == '\n' = TagClose "p" : autoFlow' False (t:ts)
-- a new paragraph, indicated by a linebreak
| head c == '\n' = TagOpen "p" [] : autoFlow' True (TagText (dropWhile (== '\n') c) : ts)
-- already open; carry on
| open = thisPara : autoFlow' True rest
-- text, pop it in a <p>
| otherwise = TagOpen "p" [] : thisPara : autoFlow' True rest
where
thisPara = TagText (takeWhile (/= '\n') c)
rest
| thisPara == t = ts
| otherwise = TagText (dropWhile (/= '\n') c) : ts
autoFlow' True (t@(TagClose n):ts)
| isBlock n =
TagClose "p" : t : autoFlow' False ts
autoFlow' open (t:ts) = t : autoFlow' open ts
isPhrasing :: String -> Bool
isPhrasing = flip elem . words $
"a abbr area audio b bdo br button canvas cite code command datelist del dfn em embed i iframe img input ins kbd keygen label link map mark math meta meter noscript object output progress q ruby samp script select small span strong sub sup svg textarea time var video wbr"
-- flow content, excluding phrasing
isBlock :: String -> Bool
isBlock = flip elem . words $
"article aside blockquote details div dl fieldset figure footer form h1 h2 h3 h4 h5 h6 header hgroup hr menu nav ol p pre section style table tr td ul li"
isFlow :: String -> Bool
isFlow x = isPhrasing x || isBlock x
isFlowable :: String -> Bool
isFlowable = flip elem . words $
"article aside blockquote dd div dl footer header section table tr td ul ol li"
getTagContent :: String -> [Tag String] -> [Tag String]
getTagContent n ts' = getTagContent' 0 [] ts'
where
getTagContent' :: Int -> [Tag String] -> [Tag String] -> [Tag String]
-- error: reached the end with an unclosed tag
getTagContent' _ _ [] = error $ "unmatched tag " ++ n ++ " in: " ++ show ts'
-- final closing tag
getTagContent' 1 acc (TagClose tn:_) | tn == n =
reverse acc
-- initial opening tag
getTagContent' 0 acc (TagOpen tn _:ts) | tn == n =
getTagContent' 1 acc ts
-- nested open tag
getTagContent' d acc (TagOpen tn as:ts) | tn == n =
getTagContent' (d + 1) (TagOpen tn as:acc) ts
-- nested close tag
getTagContent' d acc (TagClose tn:ts) | tn == n =
getTagContent' (d - 1) (TagClose tn:acc) ts
-- content
getTagContent' d acc (t:ts) =
getTagContent' d (t:acc) ts
|
vito/atomo-anatomy
|
src/Anatomy/AutoFlow.hs
|
bsd-3-clause
| 3,593
| 0
| 15
| 1,014
| 1,095
| 541
| 554
| 55
| 6
|
module Exec (execAST, execMain, execBlock, execStatement) where
import Control.Monad.Trans.Class
import Control.Monad.Trans.Either
import AST
import Error
import Eval
execAST :: AST -> IO (Either Error ())
execAST (AST m) = execMain m
execMain :: Main -> IO (Either Error ())
execMain (Main b) = execBlock b
execBlock :: Block -> IO (Either Error ())
execBlock (Block xs) = execStatementList xs
execStatementList :: [Statement] -> IO (Either Error ())
execStatementList ([]) = return $ Right ()
execStatementList (x:[]) = execStatement x
execStatementList (x:xs) = do
ei <- execStatement x
case ei of
l@(Left _) -> return l
r@(Right _) -> execStatementList xs
execStatement :: Statement -> IO (Either Error ())
execStatement ps@(PrintStatement _) = execPrintStatement ps
execStatement (IfStatement ex bl els) = execIfStatement ex bl els
execStatement NoOp = return $ Right ()
execPrintStatement :: Statement -> IO (Either Error ())
execPrintStatement (PrintStatement e) = runEitherT $ do
case expressionToString e of
Left err -> left err
Right ev -> lift $ putStrLn ev
right ()
-- execIf :: If -> IO (Either Error ())
-- execIf (If expr block els) = execBranch expr block els
--
-- execElse :: Else -> IO (Either Error ())
-- execElse (ElseIf expr block els) = execBranch expr block els
execIfStatement :: Expression -> Block -> Statement -> IO (Either Error ())
execIfStatement expr block els = case eval expr of
Right (BooleanValue True) -> execBlock block
Right (BooleanValue False) -> execStatement els
-- ElseIf nextExpr nextBlock nextEls -> execBranch nextExpr nextBlock nextEls
-- EndIf -> return $ Right ()
_ -> return $ Left $ TypeMismatchError errMsgNoNumberInBool
|
EarthCitizen/baskell
|
src/Exec.hs
|
bsd-3-clause
| 1,762
| 0
| 12
| 350
| 572
| 287
| 285
| 35
| 3
|
module Paths_potius (
version,
getBinDir, getLibDir, getDataDir, getLibexecDir,
getDataFileName, getSysconfDir
) where
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
import Prelude
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
catchIO = Exception.catch
version :: Version
version = Version [0,1,0,0] []
bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath
bindir = "/home/hefesto/dev/potius/.stack-work/install/x86_64-linux/lts-6.12/7.10.3/bin"
libdir = "/home/hefesto/dev/potius/.stack-work/install/x86_64-linux/lts-6.12/7.10.3/lib/x86_64-linux-ghc-7.10.3/potius-0.1.0.0-FUaPVJFVkAa7DzQhBW5H04"
datadir = "/home/hefesto/dev/potius/.stack-work/install/x86_64-linux/lts-6.12/7.10.3/share/x86_64-linux-ghc-7.10.3/potius-0.1.0.0"
libexecdir = "/home/hefesto/dev/potius/.stack-work/install/x86_64-linux/lts-6.12/7.10.3/libexec"
sysconfdir = "/home/hefesto/dev/potius/.stack-work/install/x86_64-linux/lts-6.12/7.10.3/etc"
getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath
getBinDir = catchIO (getEnv "potius_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "potius_libdir") (\_ -> return libdir)
getDataDir = catchIO (getEnv "potius_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "potius_libexecdir") (\_ -> return libexecdir)
getSysconfDir = catchIO (getEnv "potius_sysconfdir") (\_ -> return sysconfdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
|
hhefesto/potius
|
.stack-work/dist/x86_64-linux/Cabal-1.22.5.0/build/autogen/Paths_potius.hs
|
bsd-3-clause
| 1,597
| 0
| 10
| 177
| 362
| 206
| 156
| 28
| 1
|
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
module Test.ZM.ADT.SensorReading.Ke45682c11f7b (SensorReading(..)) where
import qualified Prelude(Eq,Ord,Show)
import qualified GHC.Generics
import qualified Flat
import qualified Data.Model
data SensorReading a b = SensorReading {reading :: a,
location :: b}
deriving (Prelude.Eq, Prelude.Ord, Prelude.Show, GHC.Generics.Generic, Flat.Flat)
instance ( Data.Model.Model a,Data.Model.Model b ) => Data.Model.Model ( SensorReading a b )
|
tittoassini/typed
|
test/Test/ZM/ADT/SensorReading/Ke45682c11f7b.hs
|
bsd-3-clause
| 546
| 0
| 8
| 103
| 147
| 90
| 57
| 11
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.