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 Main (
main
) where
import Data.LinearProgram
import Control.Monad.LPMonad
import Data.LinearProgram.GLPK
import Control.Monad.State
import qualified Data.Map as Map
loadPattern = Map.fromList [ ("night",5),("morning",25),("evenings",100) ]
-- on-demand instances cost/hour
onDemandHourlyCost = 0.64
-- reserved instances cost
reservationFixedCosts = [("light", 552.0),("medium",1280.0),("heavy",1560.0)]
reservationVariableCosts = [("light",0.312),("medium",0.192),("heavy",0.128)]
reservationTypes = map (\(x,y) -> x) reservationFixedCosts
dailyCost :: Map.Map [Char] Double -> LinFunc [Char] Double
dailyCost loadPattern = let
periods = Map.keys loadPattern
--cost of reserving an instance
reservationFixedCostsObj = [ ( cost/365.0, "reservation_" ++ kind)
| (kind, cost) <- reservationFixedCosts ]
-- cost of *running* the reserved instance.
reservationVariableCostsObj = [ (cost*8, "reserved_" ++ kind ++ "_" ++ period)
| (kind, cost) <- reservationVariableCosts,
period <- periods ]
-- cost of running on-demand instances
onDemandVariableCostsObj = [ (onDemandHourlyCost*8, "onDemand_" ++ p) |p <- periods ]
in
linCombination (reservationFixedCostsObj ++ reservationVariableCostsObj ++ onDemandVariableCostsObj)
-- Constraints..
--
-- on meeting the load at any instant the combination of all
-- services should satisfy load demand.
capacityConstraints loadPattern = [ (linCombination (
[ (1.0, "onDemand_" ++ period) ]
++[(1.0, "reserved_" ++ k ++ "_" ++ period) | k <- reservationTypes]
),
load)
| (period,load) <- (Map.assocs loadPattern)]
-- reservationConstraints
reservationConstraints loadPattern =
[ (linCombination(
[ (1.0, "reservation_" ++ k) ]
++[(-1.0, "reserved_" ++ k ++ "_" ++ p) ]
),
0.0) |p <- (Map.keys loadPattern),
k <- reservationTypes ]
-- Positive integer variables constraint
allVariables loadPatten = ["onDemand_" ++ p | p <- periods] ++
["reserved_" ++ k ++ "_" ++ p | p <- periods, k <- reservationTypes] ++
["reservation_" ++ k | k <- reservationTypes]
where periods = Map.keys loadPattern
lp :: Map.Map [Char] Double -> LP String Double
lp loadPattern = execLPM $ do
-- Tell glpk we are minimizing no maximizing
setDirection Min
-- pass the objective function/variable to minimize
setObjective (dailyCost loadPattern)
--First and second set of constraints
mapM (\(func, val) -> func `geqTo` val) (reservationConstraints loadPattern)
mapM (\(func, val) -> func `geqTo` val) (capacityConstraints loadPattern)
-- Positive values constraint
mapM (\var -> varGeq var 0.0) (allVariables loadPattern)
-- Integer values constraint. aws instances can't be
-- fractional
mapM (\var -> setVarKind var IntVar) (allVariables loadPattern)
--Finally, printing results
printLPSolution loadPattern = do
x <- glpSolveVars mipDefaults (lp loadPattern)
putStrLn (show (allVariables loadPattern))
case x of (Success, Just (obj,vars)) -> do
putStrLn "Success!"
putStrLn ("Cost: " ++ (show obj))
putStrLn ("Variables: " ++ (show vars))
(failure, result) -> putStrLn ("Failure: " ++ (show failure))
main :: IO ()
main = do
printLPSolution (Map.fromList [ ("night", 12.2), ("morning",25.1), ("evening",53.5) ])
| softwaremechanic/Miscellaneous | Haskell/linear_prog_aws.hs | gpl-2.0 | 4,236 | 0 | 16 | 1,523 | 1,014 | 562 | 452 | 56 | 2 |
{-# OPTIONS_GHC -O3 -optc-O3 #-}
--idea 0
fib=zipWith (+) (0:(1:fib)) (0:fib)
main=print.sum.takeWhile (<=4000000).filter even$ fib
| kumar0ed/euler | 2.hs | gpl-2.0 | 133 | 0 | 9 | 16 | 62 | 35 | 27 | 3 | 1 |
import Test.Framework (defaultMain, testGroup)
import Test.Framework.Providers.HUnit
import Test.AllTests
import Test.HUnit
main = defaultMain tests
tests = [ testGroup "primitiveParsers"
[ testCase "parseNumber" parseNumber
, testCase "parseNumberNegative" parseNumberNegative
, testCase "parseString" parseString
, testCase "parseString_withNewLine" parseString_withNewLine
, testCase "parseString_withEscapedQuote" parseString_withEscapedQuote
]
, testGroup "parseEvent"
[ testCase "parseAuth" parseAuth
, testCase "parseBalloonText" parseBalloonText
, testCase "parseButtonRelease" parseButtonRelease
, testCase "parseDisconnect" parseDisconnect
, testCase "parseFileOpened" parseFileOpened
, testCase "parseGeometry" parseGeometry
, testCase "parseInsert" parseInsert
, testCase "parseKeyCommand" parseKeyCommand
, testCase "parseKeyAtPos" parseKeyAtPos
, testCase "parseKilled" parseKilled
, testCase "parseNewDotAndMark" parseNewDotAndMark
, testCase "parseRemove" parseRemove
, testCase "parseSave" parseSave
, testCase "parseStartupDone" parseStartupDone
, testCase "parseUnmodified" parseUnmodified
, testCase "parseVersion" parseVersion
]
, testGroup "parseReply"
[ testCase "parseGetCursorReply" parseGetCursorReply
, testCase "parseGetLengthReply" parseGetLengthReply
, testCase "parseGetAnnoReply" parseGetAnnoReply
, testCase "parseGetModifiedReply" parseGetModifiedReply
, testCase "parseGetTextReply" parseGetTextReply
, testCase "parseInsertReplySuccess" parseInsertReplySuccess
, testCase "parseInsertReplyError" parseInsertReplyError
, testCase "parseRemoveReplySuccess" parseRemoveReplySuccess
, testCase "parseRemoveReplyError" parseRemoveReplyError
]
, testGroup "printCommand"
[ testCase "printDisconnect" printDisconnect
, testCase "printDetach" printDetach
, testCase "printAddAnno" printAddAnno
, testCase "printClose" printClose
, testCase "printCreate" printCreate
, testCase "printDefineAnnoType" printDefineAnnoType
, testCase "printEditFile" printEditFile
, testCase "printEndAtomic" printEndAtomic
, testCase "printGuard" printGuard
, testCase "printInitDone" printInitDone
, testCase "printInsertDone" printInsertDone
, testCase "printNetbeansBuffer" printNetbeansBuffer
, testCase "printPutBufferNumber" printPutBufferNumber
, testCase "printRaise" printRaise
, testCase "printRemoveAnno" printRemoveAnno
, testCase "printSave" printSave
, testCase "printSaveDone" printSaveDone
, testCase "printSetBufferNumber" printSetBufferNumber
, testCase "printSetDot" printSetDot
, testCase "printSetExitDelay" printSetExitDelay
, testCase "printSetFullName" printSetFullName
, testCase "printSetModified" printSetModified
, testCase "printSetReadOnly" printSetReadOnly
, testCase "printSetTitle" printSetTitle
, testCase "printSetVisible" printSetVisible
, testCase "printShowBalloon" printShowBalloon
, testCase "printSpecialKeys" printSpecialKeys
, testCase "printStartAtomic" printStartAtomic
, testCase "printStartDocumentListen" printStartDocumentListen
, testCase "printStopDocumentListen" printStopDocumentListen
, testCase "printUnguard" printUnguard
]
, testGroup "printFunction"
[ testCase "printGetCursor" printGetCursor
, testCase "printGetLength" printGetLength
, testCase "printGetAnno" printGetAnno
, testCase "printGetModified" printGetModified
, testCase "printGetText" printGetText
, testCase "printInsert" printInsert
, testCase "printRemove" printRemove
, testCase "printSaveAndExit" printSaveAndExit
]
]
| VictorDenisov/vim-netbeans | src/Test/ByFramework.hs | gpl-2.0 | 4,384 | 0 | 8 | 1,245 | 636 | 322 | 314 | 79 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-
Copyright (C) 2006-2014 John MacFarlane <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; 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.Readers.RST
Copyright : Copyright (C) 2006-2014 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <[email protected]>
Stability : alpha
Portability : portable
Conversion from reStructuredText to 'Pandoc' document.
-}
module Text.Pandoc.Readers.RST (
readRST,
readRSTWithWarnings
) where
import Text.Pandoc.Definition
import Text.Pandoc.Builder (setMeta, fromList)
import Text.Pandoc.Shared
import Text.Pandoc.Parsing
import Text.Pandoc.Options
import Control.Monad ( when, liftM, guard, mzero )
import Data.List ( findIndex, intersperse, intercalate,
transpose, sort, deleteFirstsBy, isSuffixOf , nub, union)
import Data.Maybe (fromMaybe)
import qualified Data.Map as M
import Text.Printf ( printf )
import Control.Applicative ((<$>), (<$), (<*), (*>), (<*>), pure)
import Text.Pandoc.Builder (Inlines, Blocks, trimInlines, (<>))
import qualified Text.Pandoc.Builder as B
import Data.Monoid (mconcat, mempty)
import Data.Sequence (viewr, ViewR(..))
import Data.Char (toLower, isHexDigit, isSpace)
-- | Parse reStructuredText string and return Pandoc document.
readRST :: ReaderOptions -- ^ Reader options
-> String -- ^ String to parse (assuming @'\n'@ line endings)
-> Pandoc
readRST opts s = (readWith parseRST) def{ stateOptions = opts } (s ++ "\n\n")
readRSTWithWarnings :: ReaderOptions -> String -> (Pandoc, [String])
readRSTWithWarnings opts s = (readWithWarnings parseRST) def{ stateOptions = opts } (s ++ "\n\n")
type RSTParser = Parser [Char] ParserState
--
-- Constants and data structure definitions
---
bulletListMarkers :: [Char]
bulletListMarkers = "*+-"
underlineChars :: [Char]
underlineChars = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
-- treat these as potentially non-text when parsing inline:
specialChars :: [Char]
specialChars = "\\`|*_<>$:/[]{}()-.\"'\8216\8217\8220\8221"
--
-- parsing documents
--
isHeader :: Int -> Block -> Bool
isHeader n (Header x _ _) = x == n
isHeader _ _ = False
-- | Promote all headers in a list of blocks. (Part of
-- title transformation for RST.)
promoteHeaders :: Int -> [Block] -> [Block]
promoteHeaders num ((Header level attr text):rest) =
(Header (level - num) attr text):(promoteHeaders num rest)
promoteHeaders num (other:rest) = other:(promoteHeaders num rest)
promoteHeaders _ [] = []
-- | If list of blocks starts with a header (or a header and subheader)
-- of level that are not found elsewhere, return it as a title and
-- promote all the other headers. Also process a definition list right
-- after the title block as metadata.
titleTransform :: ([Block], Meta) -- ^ list of blocks, metadata
-> ([Block], Meta) -- ^ modified list of blocks, metadata
titleTransform (bs, meta) =
let (bs', meta') =
case bs of
((Header 1 _ head1):(Header 2 _ head2):rest)
| not (any (isHeader 1) rest || any (isHeader 2) rest) -> -- tit/sub
(promoteHeaders 2 rest, setMeta "title" (fromList head1) $
setMeta "subtitle" (fromList head2) meta)
((Header 1 _ head1):rest)
| not (any (isHeader 1) rest) -> -- title only
(promoteHeaders 1 rest,
setMeta "title" (fromList head1) meta)
_ -> (bs, meta)
in case bs' of
(DefinitionList ds : rest) ->
(rest, metaFromDefList ds meta')
_ -> (bs', meta')
metaFromDefList :: [([Inline], [[Block]])] -> Meta -> Meta
metaFromDefList ds meta = adjustAuthors $ foldr f meta ds
where f (k,v) = setMeta (map toLower $ stringify k) (mconcat $ map fromList v)
adjustAuthors (Meta metamap) = Meta $ M.adjust splitAuthors "author"
$ M.adjust toPlain "date"
$ M.adjust toPlain "title"
$ M.mapKeys (\k -> if k == "authors" then "author" else k)
$ metamap
toPlain (MetaBlocks [Para xs]) = MetaInlines xs
toPlain x = x
splitAuthors (MetaBlocks [Para xs])
= MetaList $ map MetaInlines
$ splitAuthors' xs
splitAuthors x = x
splitAuthors' = map normalizeSpaces .
splitOnSemi . concatMap factorSemi
splitOnSemi = splitBy (==Str ";")
factorSemi (Str []) = []
factorSemi (Str s) = case break (==';') s of
(xs,[]) -> [Str xs]
(xs,';':ys) -> Str xs : Str ";" :
factorSemi (Str ys)
(xs,ys) -> Str xs :
factorSemi (Str ys)
factorSemi x = [x]
parseRST :: RSTParser Pandoc
parseRST = do
optional blanklines -- skip blank lines at beginning of file
startPos <- getPosition
-- go through once just to get list of reference keys and notes
-- docMinusKeys is the raw document with blanks where the keys were...
docMinusKeys <- concat <$>
manyTill (referenceKey <|> noteBlock <|> lineClump) eof
setInput docMinusKeys
setPosition startPos
st' <- getState
let reversedNotes = stateNotes st'
updateState $ \s -> s { stateNotes = reverse reversedNotes }
-- now parse it for real...
blocks <- B.toList <$> parseBlocks
standalone <- getOption readerStandalone
state <- getState
let meta = stateMeta state
let (blocks', meta') = if standalone
then titleTransform (blocks, meta)
else (blocks, meta)
return $ Pandoc meta' blocks'
--
-- parsing blocks
--
parseBlocks :: RSTParser Blocks
parseBlocks = mconcat <$> manyTill block eof
block :: RSTParser Blocks
block = choice [ codeBlock
, blockQuote
, fieldList
, directive
, comment
, header
, hrule
, lineBlock -- must go before definitionList
, table
, list
, lhsCodeBlock
, para
, mempty <$ blanklines
] <?> "block"
--
-- field list
--
rawFieldListItem :: Int -> RSTParser (String, String)
rawFieldListItem minIndent = try $ do
indent <- length <$> many (char ' ')
guard $ indent >= minIndent
char ':'
name <- many1Till (noneOf "\n") (char ':')
(() <$ lookAhead newline) <|> skipMany1 spaceChar
first <- anyLine
rest <- option "" $ try $ do lookAhead (count indent (char ' ') >> spaceChar)
indentedBlock
let raw = (if null first then "" else (first ++ "\n")) ++ rest ++ "\n"
return (name, raw)
fieldListItem :: Int -> RSTParser (Inlines, [Blocks])
fieldListItem minIndent = try $ do
(name, raw) <- rawFieldListItem minIndent
let term = B.str name
contents <- parseFromString parseBlocks raw
optional blanklines
return (term, [contents])
fieldList :: RSTParser Blocks
fieldList = try $ do
indent <- length <$> lookAhead (many spaceChar)
items <- many1 $ fieldListItem indent
case items of
[] -> return mempty
items' -> return $ B.definitionList items'
--
-- line block
--
lineBlock :: RSTParser Blocks
lineBlock = try $ do
lines' <- lineBlockLines
lines'' <- mapM (parseFromString
(trimInlines . mconcat <$> many inline)) lines'
return $ B.para (mconcat $ intersperse B.linebreak lines'')
--
-- paragraph block
--
-- note: paragraph can end in a :: starting a code block
para :: RSTParser Blocks
para = try $ do
result <- trimInlines . mconcat <$> many1 inline
option (B.plain result) $ try $ do
newline
blanklines
case viewr (B.unMany result) of
ys :> (Str xs) | "::" `isSuffixOf` xs -> do
raw <- option mempty codeBlockBody
return $ B.para (B.Many ys <> B.str (take (length xs - 1) xs))
<> raw
_ -> return (B.para result)
plain :: RSTParser Blocks
plain = B.plain . trimInlines . mconcat <$> many1 inline
--
-- header blocks
--
header :: RSTParser Blocks
header = doubleHeader <|> singleHeader <?> "header"
-- a header with lines on top and bottom
doubleHeader :: RSTParser Blocks
doubleHeader = try $ do
c <- oneOf underlineChars
rest <- many (char c) -- the top line
let lenTop = length (c:rest)
skipSpaces
newline
txt <- trimInlines . mconcat <$> many1 (notFollowedBy blankline >> inline)
pos <- getPosition
let len = (sourceColumn pos) - 1
if (len > lenTop) then fail "title longer than border" else return ()
blankline -- spaces and newline
count lenTop (char c) -- the bottom line
blanklines
-- check to see if we've had this kind of header before.
-- if so, get appropriate level. if not, add to list.
state <- getState
let headerTable = stateHeaderTable state
let (headerTable',level) = case findIndex (== DoubleHeader c) headerTable of
Just ind -> (headerTable, ind + 1)
Nothing -> (headerTable ++ [DoubleHeader c], (length headerTable) + 1)
setState (state { stateHeaderTable = headerTable' })
attr <- registerHeader nullAttr txt
return $ B.headerWith attr level txt
-- a header with line on the bottom only
singleHeader :: RSTParser Blocks
singleHeader = try $ do
notFollowedBy' whitespace
txt <- trimInlines . mconcat <$> many1 (do {notFollowedBy blankline; inline})
pos <- getPosition
let len = (sourceColumn pos) - 1
blankline
c <- oneOf underlineChars
count (len - 1) (char c)
many (char c)
blanklines
state <- getState
let headerTable = stateHeaderTable state
let (headerTable',level) = case findIndex (== SingleHeader c) headerTable of
Just ind -> (headerTable, ind + 1)
Nothing -> (headerTable ++ [SingleHeader c], (length headerTable) + 1)
setState (state { stateHeaderTable = headerTable' })
attr <- registerHeader nullAttr txt
return $ B.headerWith attr level txt
--
-- hrule block
--
hrule :: Parser [Char] st Blocks
hrule = try $ do
chr <- oneOf underlineChars
count 3 (char chr)
skipMany (char chr)
blankline
blanklines
return B.horizontalRule
--
-- code blocks
--
-- read a line indented by a given string
indentedLine :: String -> Parser [Char] st [Char]
indentedLine indents = try $ do
string indents
anyLine
-- one or more indented lines, possibly separated by blank lines.
-- any amount of indentation will work.
indentedBlock :: Parser [Char] st [Char]
indentedBlock = try $ do
indents <- lookAhead $ many1 spaceChar
lns <- many1 $ try $ do b <- option "" blanklines
l <- indentedLine indents
return (b ++ l)
optional blanklines
return $ unlines lns
quotedBlock :: Parser [Char] st [Char]
quotedBlock = try $ do
quote <- lookAhead $ oneOf "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
lns <- many1 $ lookAhead (char quote) >> anyLine
optional blanklines
return $ unlines lns
codeBlockStart :: Parser [Char] st Char
codeBlockStart = string "::" >> blankline >> blankline
codeBlock :: Parser [Char] st Blocks
codeBlock = try $ codeBlockStart >> codeBlockBody
codeBlockBody :: Parser [Char] st Blocks
codeBlockBody = try $ B.codeBlock . stripTrailingNewlines <$>
(indentedBlock <|> quotedBlock)
lhsCodeBlock :: RSTParser Blocks
lhsCodeBlock = try $ do
getPosition >>= guard . (==1) . sourceColumn
guardEnabled Ext_literate_haskell
optional codeBlockStart
lns <- latexCodeBlock <|> birdCodeBlock
blanklines
return $ B.codeBlockWith ("", ["sourceCode", "literate", "haskell"], [])
$ intercalate "\n" lns
latexCodeBlock :: Parser [Char] st [[Char]]
latexCodeBlock = try $ do
try (latexBlockLine "\\begin{code}")
many1Till anyLine (try $ latexBlockLine "\\end{code}")
where
latexBlockLine s = skipMany spaceChar >> string s >> blankline
birdCodeBlock :: Parser [Char] st [[Char]]
birdCodeBlock = filterSpace <$> many1 birdTrackLine
where filterSpace lns =
-- if (as is normal) there is always a space after >, drop it
if all (\ln -> null ln || take 1 ln == " ") lns
then map (drop 1) lns
else lns
birdTrackLine :: Parser [Char] st [Char]
birdTrackLine = char '>' >> anyLine
--
-- block quotes
--
blockQuote :: RSTParser Blocks
blockQuote = do
raw <- indentedBlock
-- parse the extracted block, which may contain various block elements:
contents <- parseFromString parseBlocks $ raw ++ "\n\n"
return $ B.blockQuote contents
--
-- list blocks
--
list :: RSTParser Blocks
list = choice [ bulletList, orderedList, definitionList ] <?> "list"
definitionListItem :: RSTParser (Inlines, [Blocks])
definitionListItem = try $ do
-- avoid capturing a directive or comment
notFollowedBy (try $ char '.' >> char '.')
term <- trimInlines . mconcat <$> many1Till inline endline
raw <- indentedBlock
-- parse the extracted block, which may contain various block elements:
contents <- parseFromString parseBlocks $ raw ++ "\n"
return (term, [contents])
definitionList :: RSTParser Blocks
definitionList = B.definitionList <$> many1 definitionListItem
-- parses bullet list start and returns its length (inc. following whitespace)
bulletListStart :: Parser [Char] st Int
bulletListStart = try $ do
notFollowedBy' hrule -- because hrules start out just like lists
marker <- oneOf bulletListMarkers
white <- many1 spaceChar
return $ length (marker:white)
-- parses ordered list start and returns its length (inc following whitespace)
orderedListStart :: ListNumberStyle
-> ListNumberDelim
-> RSTParser Int
orderedListStart style delim = try $ do
(_, markerLen) <- withHorizDisplacement (orderedListMarker style delim)
white <- many1 spaceChar
return $ markerLen + length white
-- parse a line of a list item
listLine :: Int -> RSTParser [Char]
listLine markerLength = try $ do
notFollowedBy blankline
indentWith markerLength
line <- anyLine
return $ line ++ "\n"
-- indent by specified number of spaces (or equiv. tabs)
indentWith :: Int -> RSTParser [Char]
indentWith num = do
tabStop <- getOption readerTabStop
if (num < tabStop)
then count num (char ' ')
else choice [ try (count num (char ' ')),
(try (char '\t' >> count (num - tabStop) (char ' '))) ]
-- parse raw text for one list item, excluding start marker and continuations
rawListItem :: RSTParser Int
-> RSTParser (Int, [Char])
rawListItem start = try $ do
markerLength <- start
firstLine <- anyLine
restLines <- many (listLine markerLength)
return (markerLength, (firstLine ++ "\n" ++ (concat restLines)))
-- continuation of a list item - indented and separated by blankline or
-- (in compact lists) endline.
-- Note: nested lists are parsed as continuations.
listContinuation :: Int -> RSTParser [Char]
listContinuation markerLength = try $ do
blanks <- many1 blankline
result <- many1 (listLine markerLength)
return $ blanks ++ concat result
listItem :: RSTParser Int
-> RSTParser Blocks
listItem start = try $ do
(markerLength, first) <- rawListItem start
rest <- many (listContinuation markerLength)
blanks <- choice [ try (many blankline <* lookAhead start),
many1 blankline ] -- whole list must end with blank.
-- parsing with ListItemState forces markers at beginning of lines to
-- count as list item markers, even if not separated by blank space.
-- see definition of "endline"
state <- getState
let oldContext = stateParserContext state
setState $ state {stateParserContext = ListItemState}
-- parse the extracted block, which may itself contain block elements
parsed <- parseFromString parseBlocks $ concat (first:rest) ++ blanks
updateState (\st -> st {stateParserContext = oldContext})
return $ case B.toList parsed of
[Para xs] -> B.singleton $ Plain xs
[Para xs, BulletList ys] -> B.fromList [Plain xs, BulletList ys]
[Para xs, OrderedList s ys] -> B.fromList [Plain xs, OrderedList s ys]
[Para xs, DefinitionList ys] -> B.fromList [Plain xs, DefinitionList ys]
_ -> parsed
orderedList :: RSTParser Blocks
orderedList = try $ do
(start, style, delim) <- lookAhead (anyOrderedListMarker <* spaceChar)
items <- many1 (listItem (orderedListStart style delim))
let items' = compactify' items
return $ B.orderedListWith (start, style, delim) items'
bulletList :: RSTParser Blocks
bulletList = B.bulletList . compactify' <$> many1 (listItem bulletListStart)
--
-- directive (e.g. comment, container, compound-paragraph)
--
comment :: RSTParser Blocks
comment = try $ do
string ".."
skipMany1 spaceChar <|> (() <$ lookAhead newline)
notFollowedBy' directiveLabel
manyTill anyChar blanklines
optional indentedBlock
return mempty
directiveLabel :: RSTParser String
directiveLabel = map toLower
<$> many1Till (letter <|> char '-') (try $ string "::")
directive :: RSTParser Blocks
directive = try $ do
string ".."
directive'
-- TODO: line-block, parsed-literal, table, csv-table, list-table
-- date
-- include
-- title
directive' :: RSTParser Blocks
directive' = do
skipMany1 spaceChar
label <- directiveLabel
skipMany spaceChar
top <- many $ satisfy (/='\n')
<|> try (char '\n' <*
notFollowedBy' (rawFieldListItem 3) <*
count 3 (char ' ') <*
notFollowedBy blankline)
newline
fields <- many $ rawFieldListItem 3
body <- option "" $ try $ blanklines >> indentedBlock
optional blanklines
let body' = body ++ "\n\n"
case label of
"raw" -> return $ B.rawBlock (trim top) (stripTrailingNewlines body)
"role" -> addNewRole top $ map (\(k,v) -> (k, trim v)) fields
"container" -> parseFromString parseBlocks body'
"replace" -> B.para <$> -- consumed by substKey
parseFromString (trimInlines . mconcat <$> many inline)
(trim top)
"unicode" -> B.para <$> -- consumed by substKey
parseFromString (trimInlines . mconcat <$> many inline)
(trim $ unicodeTransform top)
"compound" -> parseFromString parseBlocks body'
"pull-quote" -> B.blockQuote <$> parseFromString parseBlocks body'
"epigraph" -> B.blockQuote <$> parseFromString parseBlocks body'
"highlights" -> B.blockQuote <$> parseFromString parseBlocks body'
"rubric" -> B.para . B.strong <$> parseFromString
(trimInlines . mconcat <$> many inline) top
_ | label `elem` ["attention","caution","danger","error","hint",
"important","note","tip","warning"] ->
do let tit = B.para $ B.strong $ B.str label
bod <- parseFromString parseBlocks $ top ++ "\n\n" ++ body'
return $ B.blockQuote $ tit <> bod
"admonition" ->
do tit <- B.para . B.strong <$> parseFromString
(trimInlines . mconcat <$> many inline) top
bod <- parseFromString parseBlocks body'
return $ B.blockQuote $ tit <> bod
"sidebar" ->
do let subtit = maybe "" trim $ lookup "subtitle" fields
tit <- B.para . B.strong <$> parseFromString
(trimInlines . mconcat <$> many inline)
(trim top ++ if null subtit
then ""
else (": " ++ subtit))
bod <- parseFromString parseBlocks body'
return $ B.blockQuote $ tit <> bod
"topic" ->
do tit <- B.para . B.strong <$> parseFromString
(trimInlines . mconcat <$> many inline) top
bod <- parseFromString parseBlocks body'
return $ tit <> bod
"default-role" -> mempty <$ updateState (\s ->
s { stateRstDefaultRole =
case trim top of
"" -> stateRstDefaultRole def
role -> role })
"code" -> codeblock (lookup "number-lines" fields) (trim top) body
"code-block" -> codeblock (lookup "number-lines" fields) (trim top) body
"aafig" -> do
let attribs = ("", ["aafig"], map (\(k,v) -> (k, trimr v)) fields)
return $ B.codeBlockWith attribs $ stripTrailingNewlines body
"math" -> return $ B.para $ mconcat $ map B.displayMath
$ toChunks $ top ++ "\n\n" ++ body
"figure" -> do
(caption, legend) <- parseFromString extractCaption body'
let src = escapeURI $ trim top
return $ B.para (B.image src "fig:" caption) <> legend
"image" -> do
let src = escapeURI $ trim top
let alt = B.str $ maybe "image" trim $ lookup "alt" fields
return $ B.para
$ case lookup "target" fields of
Just t -> B.link (escapeURI $ trim t) ""
$ B.image src "" alt
Nothing -> B.image src "" alt
"class" -> do
let attrs = ("", (splitBy isSpace $ trim top), map (\(k,v) -> (k, trimr v)) fields)
-- directive content or the first immediately following element
children <- case body of
"" -> block
_ -> parseFromString parseBlocks body'
return $ B.divWith attrs children
other -> do
pos <- getPosition
addWarning (Just pos) $ "ignoring unknown directive: " ++ other
return mempty
-- TODO:
-- - Silently ignores illegal fields
-- - Only supports :format: fields with a single format for :raw: roles,
-- change Text.Pandoc.Definition.Format to fix
addNewRole :: String -> [(String, String)] -> RSTParser Blocks
addNewRole roleString fields = do
(role, parentRole) <- parseFromString inheritedRole roleString
customRoles <- stateRstCustomRoles <$> getState
let (baseRole, baseFmt, baseAttr) =
maybe (parentRole, Nothing, nullAttr) id $
M.lookup parentRole customRoles
fmt = if parentRole == "raw" then lookup "format" fields else baseFmt
annotate :: [String] -> [String]
annotate = maybe id (:) $
if parentRole == "code"
then lookup "language" fields
else Nothing
attr = let (ident, classes, keyValues) = baseAttr
-- nub in case role name & language class are the same
in (ident, nub . (role :) . annotate $ classes, keyValues)
-- warn about syntax we ignore
flip mapM_ fields $ \(key, _) -> case key of
"language" -> when (parentRole /= "code") $ addWarning Nothing $
"ignoring :language: field because the parent of role :" ++
role ++ ": is :" ++ parentRole ++ ": not :code:"
"format" -> when (parentRole /= "raw") $ addWarning Nothing $
"ignoring :format: field because the parent of role :" ++
role ++ ": is :" ++ parentRole ++ ": not :raw:"
_ -> addWarning Nothing $ "ignoring unknown field :" ++ key ++
": in definition of role :" ++ role ++ ": in"
when (parentRole == "raw" && countKeys "format" > 1) $
addWarning Nothing $
"ignoring :format: fields after the first in the definition of role :"
++ role ++": in"
when (parentRole == "code" && countKeys "language" > 1) $
addWarning Nothing $
"ignoring :language: fields after the first in the definition of role :"
++ role ++": in"
updateState $ \s -> s {
stateRstCustomRoles =
M.insert role (baseRole, fmt, attr) customRoles
}
return $ B.singleton Null
where
countKeys k = length . filter (== k) . map fst $ fields
inheritedRole =
(,) <$> roleName <*> ((char '(' *> roleName <* char ')') <|> pure "span")
-- Can contain character codes as decimal numbers or
-- hexadecimal numbers, prefixed by 0x, x, \x, U+, u, or \u
-- or as XML-style hexadecimal character entities, e.g. ᨫ
-- or text, which is used as-is. Comments start with ..
unicodeTransform :: String -> String
unicodeTransform t =
case t of
('.':'.':xs) -> unicodeTransform $ dropWhile (/='\n') xs -- comment
('0':'x':xs) -> go "0x" xs
('x':xs) -> go "x" xs
('\\':'x':xs) -> go "\\x" xs
('U':'+':xs) -> go "U+" xs
('u':xs) -> go "u" xs
('\\':'u':xs) -> go "\\u" xs
('&':'#':'x':xs) -> maybe ("&#x" ++ unicodeTransform xs)
-- drop semicolon
(\(c,s) -> c : unicodeTransform (drop 1 s))
$ extractUnicodeChar xs
(x:xs) -> x : unicodeTransform xs
[] -> []
where go pref zs = maybe (pref ++ unicodeTransform zs)
(\(c,s) -> c : unicodeTransform s)
$ extractUnicodeChar zs
extractUnicodeChar :: String -> Maybe (Char, String)
extractUnicodeChar s = maybe Nothing (\c -> Just (c,rest)) mbc
where (ds,rest) = span isHexDigit s
mbc = safeRead ('\'':'\\':'x':ds ++ "'")
extractCaption :: RSTParser (Inlines, Blocks)
extractCaption = do
capt <- trimInlines . mconcat <$> many inline
legend <- optional blanklines >> (mconcat <$> many block)
return (capt,legend)
-- divide string by blanklines
toChunks :: String -> [String]
toChunks = dropWhile null
. map (trim . unlines)
. splitBy (all (`elem` " \t")) . lines
codeblock :: Maybe String -> String -> String -> RSTParser Blocks
codeblock numberLines lang body =
return $ B.codeBlockWith attribs $ stripTrailingNewlines body
where attribs = ("", classes, kvs)
classes = "sourceCode" : lang
: maybe [] (\_ -> ["numberLines"]) numberLines
kvs = case numberLines of
Just "" -> []
Nothing -> []
Just n -> [("startFrom",trim n)]
---
--- note block
---
noteBlock :: RSTParser [Char]
noteBlock = try $ do
startPos <- getPosition
string ".."
spaceChar >> skipMany spaceChar
ref <- noteMarker
first <- (spaceChar >> skipMany spaceChar >> anyLine)
<|> (newline >> return "")
blanks <- option "" blanklines
rest <- option "" indentedBlock
endPos <- getPosition
let raw = first ++ "\n" ++ blanks ++ rest ++ "\n"
let newnote = (ref, raw)
st <- getState
let oldnotes = stateNotes st
updateState $ \s -> s { stateNotes = newnote : oldnotes }
-- return blanks so line count isn't affected
return $ replicate (sourceLine endPos - sourceLine startPos) '\n'
noteMarker :: RSTParser [Char]
noteMarker = do
char '['
res <- many1 digit
<|> (try $ char '#' >> liftM ('#':) simpleReferenceName')
<|> count 1 (oneOf "#*")
char ']'
return res
--
-- reference key
--
quotedReferenceName :: RSTParser Inlines
quotedReferenceName = try $ do
char '`' >> notFollowedBy (char '`') -- `` means inline code!
label' <- trimInlines . mconcat <$> many1Till inline (char '`')
return label'
unquotedReferenceName :: RSTParser Inlines
unquotedReferenceName = try $ do
label' <- trimInlines . mconcat <$> many1Till inline (lookAhead $ char ':')
return label'
-- Simple reference names are single words consisting of alphanumerics
-- plus isolated (no two adjacent) internal hyphens, underscores,
-- periods, colons and plus signs; no whitespace or other characters
-- are allowed.
simpleReferenceName' :: Parser [Char] st String
simpleReferenceName' = do
x <- alphaNum
xs <- many $ alphaNum
<|> (try $ oneOf "-_:+." >> lookAhead alphaNum)
return (x:xs)
simpleReferenceName :: Parser [Char] st Inlines
simpleReferenceName = do
raw <- simpleReferenceName'
return $ B.str raw
referenceName :: RSTParser Inlines
referenceName = quotedReferenceName <|>
(try $ simpleReferenceName <* lookAhead (char ':')) <|>
unquotedReferenceName
referenceKey :: RSTParser [Char]
referenceKey = do
startPos <- getPosition
choice [substKey, anonymousKey, regularKey]
optional blanklines
endPos <- getPosition
-- return enough blanks to replace key
return $ replicate (sourceLine endPos - sourceLine startPos) '\n'
targetURI :: Parser [Char] st [Char]
targetURI = do
skipSpaces
optional newline
contents <- many1 (try (many spaceChar >> newline >>
many1 spaceChar >> noneOf " \t\n") <|> noneOf "\n")
blanklines
return $ escapeURI $ trim $ contents
substKey :: RSTParser ()
substKey = try $ do
string ".."
skipMany1 spaceChar
(alt,ref) <- withRaw $ trimInlines . mconcat
<$> enclosed (char '|') (char '|') inline
res <- B.toList <$> directive'
il <- case res of
-- use alt unless :alt: attribute on image:
[Para [Image [Str "image"] (src,tit)]] ->
return $ B.image src tit alt
[Para [Link [Image [Str "image"] (src,tit)] (src',tit')]] ->
return $ B.link src' tit' (B.image src tit alt)
[Para ils] -> return $ B.fromList ils
_ -> mzero
let key = toKey $ stripFirstAndLast ref
updateState $ \s -> s{ stateSubstitutions = M.insert key il $ stateSubstitutions s }
anonymousKey :: RSTParser ()
anonymousKey = try $ do
oneOfStrings [".. __:", "__"]
src <- targetURI
pos <- getPosition
let key = toKey $ "_" ++ printf "%09d" (sourceLine pos)
updateState $ \s -> s { stateKeys = M.insert key (src,"") $ stateKeys s }
stripTicks :: String -> String
stripTicks = reverse . stripTick . reverse . stripTick
where stripTick ('`':xs) = xs
stripTick xs = xs
regularKey :: RSTParser ()
regularKey = try $ do
string ".. _"
(_,ref) <- withRaw referenceName
char ':'
src <- targetURI
let key = toKey $ stripTicks ref
updateState $ \s -> s { stateKeys = M.insert key (src,"") $ stateKeys s }
--
-- tables
--
-- General tables TODO:
-- - figure out if leading spaces are acceptable and if so, add
-- support for them
--
-- Simple tables TODO:
-- - column spans
-- - multiline support
-- - ensure that rightmost column span does not need to reach end
-- - require at least 2 columns
--
-- Grid tables TODO:
-- - column spans
dashedLine :: Char -> Parser [Char] st (Int, Int)
dashedLine ch = do
dashes <- many1 (char ch)
sp <- many (char ' ')
return (length dashes, length $ dashes ++ sp)
simpleDashedLines :: Char -> Parser [Char] st [(Int,Int)]
simpleDashedLines ch = try $ many1 (dashedLine ch)
-- Parse a table row separator
simpleTableSep :: Char -> RSTParser Char
simpleTableSep ch = try $ simpleDashedLines ch >> newline
-- Parse a table footer
simpleTableFooter :: RSTParser [Char]
simpleTableFooter = try $ simpleTableSep '=' >> blanklines
-- Parse a raw line and split it into chunks by indices.
simpleTableRawLine :: [Int] -> RSTParser [String]
simpleTableRawLine indices = do
line <- many1Till anyChar newline
return (simpleTableSplitLine indices line)
-- Parse a table row and return a list of blocks (columns).
simpleTableRow :: [Int] -> RSTParser [[Block]]
simpleTableRow indices = do
notFollowedBy' simpleTableFooter
firstLine <- simpleTableRawLine indices
colLines <- return [] -- TODO
let cols = map unlines . transpose $ firstLine : colLines
mapM (parseFromString (B.toList . mconcat <$> many plain)) cols
simpleTableSplitLine :: [Int] -> String -> [String]
simpleTableSplitLine indices line =
map trim
$ tail $ splitByIndices (init indices) line
simpleTableHeader :: Bool -- ^ Headerless table
-> RSTParser ([[Block]], [Alignment], [Int])
simpleTableHeader headless = try $ do
optional blanklines
rawContent <- if headless
then return ""
else simpleTableSep '=' >> anyLine
dashes <- simpleDashedLines '=' <|> simpleDashedLines '-'
newline
let lines' = map snd dashes
let indices = scanl (+) 0 lines'
let aligns = replicate (length lines') AlignDefault
let rawHeads = if headless
then replicate (length dashes) ""
else simpleTableSplitLine indices rawContent
heads <- mapM (parseFromString (B.toList . mconcat <$> many plain)) $
map trim rawHeads
return (heads, aligns, indices)
-- Parse a simple table.
simpleTable :: Bool -- ^ Headerless table
-> RSTParser Blocks
simpleTable headless = do
Table c a _w h l <- tableWith (simpleTableHeader headless) simpleTableRow sep simpleTableFooter
-- Simple tables get 0s for relative column widths (i.e., use default)
return $ B.singleton $ Table c a (replicate (length a) 0) h l
where
sep = return () -- optional (simpleTableSep '-')
gridTable :: Bool -- ^ Headerless table
-> RSTParser Blocks
gridTable headerless = B.singleton
<$> gridTableWith (B.toList <$> parseBlocks) headerless
table :: RSTParser Blocks
table = gridTable False <|> simpleTable False <|>
gridTable True <|> simpleTable True <?> "table"
--
-- inline
--
inline :: RSTParser Inlines
inline = choice [ whitespace
, link
, str
, endline
, strong
, emph
, code
, subst
, interpretedRole
, note
, smart
, hyphens
, escapedChar
, symbol ] <?> "inline"
hyphens :: RSTParser Inlines
hyphens = do
result <- many1 (char '-')
optional endline
-- don't want to treat endline after hyphen or dash as a space
return $ B.str result
escapedChar :: Parser [Char] st Inlines
escapedChar = do c <- escaped anyChar
return $ if c == ' ' -- '\ ' is null in RST
then mempty
else B.str [c]
symbol :: RSTParser Inlines
symbol = do
result <- oneOf specialChars
return $ B.str [result]
-- parses inline code, between codeStart and codeEnd
code :: RSTParser Inlines
code = try $ do
string "``"
result <- manyTill anyChar (try (string "``"))
return $ B.code
$ trim $ unwords $ lines result
-- succeeds only if we're not right after a str (ie. in middle of word)
atStart :: RSTParser a -> RSTParser a
atStart p = do
pos <- getPosition
st <- getState
-- single quote start can't be right after str
guard $ stateLastStrPos st /= Just pos
p
emph :: RSTParser Inlines
emph = B.emph . trimInlines . mconcat <$>
enclosed (atStart $ char '*') (char '*') inline
strong :: RSTParser Inlines
strong = B.strong . trimInlines . mconcat <$>
enclosed (atStart $ string "**") (try $ string "**") inline
-- Note, this doesn't precisely implement the complex rule in
-- http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#inline-markup-recognition-rules
-- but it should be good enough for most purposes
--
-- TODO:
-- - Classes are silently discarded in addNewRole
-- - Lacks sensible implementation for title-reference (which is the default)
-- - Allows direct use of the :raw: role, rST only allows inherited use.
interpretedRole :: RSTParser Inlines
interpretedRole = try $ do
(role, contents) <- roleBefore <|> roleAfter
renderRole contents Nothing role nullAttr
renderRole :: String -> Maybe String -> String -> Attr -> RSTParser Inlines
renderRole contents fmt role attr = case role of
"sup" -> return $ B.superscript $ B.str contents
"superscript" -> return $ B.superscript $ B.str contents
"sub" -> return $ B.subscript $ B.str contents
"subscript" -> return $ B.subscript $ B.str contents
"emphasis" -> return $ B.emph $ B.str contents
"strong" -> return $ B.strong $ B.str contents
"rfc-reference" -> return $ rfcLink contents
"RFC" -> return $ rfcLink contents
"pep-reference" -> return $ pepLink contents
"PEP" -> return $ pepLink contents
"literal" -> return $ B.codeWith attr contents
"math" -> return $ B.math contents
"title-reference" -> titleRef contents
"title" -> titleRef contents
"t" -> titleRef contents
"code" -> return $ B.codeWith (addClass "sourceCode" attr) contents
"span" -> return $ B.spanWith attr $ B.str contents
"raw" -> return $ B.rawInline (fromMaybe "" fmt) contents
custom -> do
customRoles <- stateRstCustomRoles <$> getState
case M.lookup custom customRoles of
Just (newRole, newFmt, newAttr) ->
renderRole contents newFmt newRole newAttr
Nothing -> do
pos <- getPosition
addWarning (Just pos) $ "ignoring unknown role :" ++ custom ++ ": in"
return $ B.str contents -- Undefined role
where
titleRef ref = return $ B.str ref -- FIXME: Not a sensible behaviour
rfcLink rfcNo = B.link rfcUrl ("RFC " ++ rfcNo) $ B.str ("RFC " ++ rfcNo)
where rfcUrl = "http://www.faqs.org/rfcs/rfc" ++ rfcNo ++ ".html"
pepLink pepNo = B.link pepUrl ("PEP " ++ pepNo) $ B.str ("PEP " ++ pepNo)
where padNo = replicate (4 - length pepNo) '0' ++ pepNo
pepUrl = "http://www.python.org/dev/peps/pep-" ++ padNo ++ "/"
addClass :: String -> Attr -> Attr
addClass c (ident, classes, keyValues) = (ident, union classes [c], keyValues)
roleName :: RSTParser String
roleName = many1 (letter <|> char '-')
roleMarker :: RSTParser String
roleMarker = char ':' *> roleName <* char ':'
roleBefore :: RSTParser (String,String)
roleBefore = try $ do
role <- roleMarker
contents <- unmarkedInterpretedText
return (role,contents)
roleAfter :: RSTParser (String,String)
roleAfter = try $ do
contents <- unmarkedInterpretedText
role <- roleMarker <|> (stateRstDefaultRole <$> getState)
return (role,contents)
unmarkedInterpretedText :: RSTParser [Char]
unmarkedInterpretedText = enclosed (atStart $ char '`') (char '`') anyChar
whitespace :: RSTParser Inlines
whitespace = B.space <$ skipMany1 spaceChar <?> "whitespace"
str :: RSTParser Inlines
str = do
let strChar = noneOf ("\t\n " ++ specialChars)
result <- many1 strChar
updateLastStrPos
return $ B.str result
-- an endline character that can be treated as a space, not a structural break
endline :: RSTParser Inlines
endline = try $ do
newline
notFollowedBy blankline
-- parse potential list-starts at beginning of line differently in a list:
st <- getState
if (stateParserContext st) == ListItemState
then notFollowedBy (anyOrderedListMarker >> spaceChar) >>
notFollowedBy' bulletListStart
else return ()
return B.space
--
-- links
--
link :: RSTParser Inlines
link = choice [explicitLink, referenceLink, autoLink] <?> "link"
explicitLink :: RSTParser Inlines
explicitLink = try $ do
char '`'
notFollowedBy (char '`') -- `` marks start of inline code
label' <- trimInlines . mconcat <$>
manyTill (notFollowedBy (char '`') >> inline) (char '<')
src <- manyTill (noneOf ">\n") (char '>')
skipSpaces
string "`_"
optional $ char '_' -- anonymous form
return $ B.link (escapeURI $ trim src) "" label'
referenceLink :: RSTParser Inlines
referenceLink = try $ do
(label',ref) <- withRaw (quotedReferenceName <|> simpleReferenceName) <*
char '_'
state <- getState
let keyTable = stateKeys state
let isAnonKey (Key ('_':_)) = True
isAnonKey _ = False
key <- option (toKey $ stripTicks ref) $
do char '_'
let anonKeys = sort $ filter isAnonKey $ M.keys keyTable
if null anonKeys
then mzero
else return (head anonKeys)
(src,tit) <- case M.lookup key keyTable of
Nothing -> fail "no corresponding key"
Just target -> return target
-- if anonymous link, remove key so it won't be used again
when (isAnonKey key) $ updateState $ \s -> s{ stateKeys = M.delete key keyTable }
return $ B.link src tit label'
autoURI :: RSTParser Inlines
autoURI = do
(orig, src) <- uri
return $ B.link src "" $ B.str orig
autoEmail :: RSTParser Inlines
autoEmail = do
(orig, src) <- emailAddress
return $ B.link src "" $ B.str orig
autoLink :: RSTParser Inlines
autoLink = autoURI <|> autoEmail
subst :: RSTParser Inlines
subst = try $ do
(_,ref) <- withRaw $ enclosed (char '|') (char '|') inline
state <- getState
let substTable = stateSubstitutions state
case M.lookup (toKey $ stripFirstAndLast ref) substTable of
Nothing -> fail "no corresponding key"
Just target -> return target
note :: RSTParser Inlines
note = try $ do
ref <- noteMarker
char '_'
state <- getState
let notes = stateNotes state
case lookup ref notes of
Nothing -> fail "note not found"
Just raw -> do
-- We temporarily empty the note list while parsing the note,
-- so that we don't get infinite loops with notes inside notes...
-- Note references inside other notes are allowed in reST, but
-- not yet in this implementation.
updateState $ \st -> st{ stateNotes = [] }
contents <- parseFromString parseBlocks raw
let newnotes = if (ref == "*" || ref == "#") -- auto-numbered
-- delete the note so the next auto-numbered note
-- doesn't get the same contents:
then deleteFirstsBy (==) notes [(ref,raw)]
else notes
updateState $ \st -> st{ stateNotes = newnotes }
return $ B.note contents
smart :: RSTParser Inlines
smart = do
getOption readerSmart >>= guard
doubleQuoted <|> singleQuoted <|>
choice [apostrophe, dash, ellipses]
singleQuoted :: RSTParser Inlines
singleQuoted = try $ do
singleQuoteStart
withQuoteContext InSingleQuote $
B.singleQuoted . trimInlines . mconcat <$>
many1Till inline singleQuoteEnd
doubleQuoted :: RSTParser Inlines
doubleQuoted = try $ do
doubleQuoteStart
withQuoteContext InDoubleQuote $
B.doubleQuoted . trimInlines . mconcat <$>
many1Till inline doubleQuoteEnd
| rgaiacs/pandoc | src/Text/Pandoc/Readers/RST.hs | gpl-2.0 | 43,516 | 657 | 34 | 11,936 | 11,504 | 6,045 | 5,459 | 889 | 27 |
module Main where
import Misc
import Tree
import ParseCss (parseCss)
import Control.Exception as CE -- CE.try
import Data.Either.Utils
import Data.Attoparsec.Text.Lazy (eitherResult)
import qualified Data.Text.Lazy.IO as T
import qualified Data.Text.Lazy as TL
import Text.Taggy (run)
import Text.Taggy.Types
{-
handleCss :: Either IOError String -> IO ()
handleCss result =
case result of
Left _ ->
putStrLn $ "[ERRO] " ++ show err
Right ok ->
case parseCss ok of
Left err' ->
putStrLn $ "[PARSE CSS FALHOU]" ++ (show err')
Right ok' ->
print ok'
-}
{-
handleHtml :: Either IOError String -> IO ()
handleHtml result =
case result of
Left err ->
putStrLn $ "[ERRO] " ++ show err
Right content ->
let
result =
content
|> TL.pack
|> Text.Taggy.run True
in
case eitherResult result of
Left err ->
putStrLn err
Right tags -> do
mapM_ print tags
putStrLn "\n"
tags
|> listToTree
|> (flip (!!) 0)
|> show
|> putStrLn
-}
strToDom :: String -> DOM
strToDom str =
str
|> TL.pack
|> Text.Taggy.run True
|> eitherResult
|> fromRight
|> listToTree
|> (flip (!!) 0)
main :: IO ()
main = do
putStrLn "--------------------------------------------------\n"
htmlResult <- readFile "src/InputHTML.html"
cssResult <- readFile "src/InputCSS.css"
let dom = strToDom htmlResult
case parseCss cssResult of
Left err ->
print err
Right (cssVariables, cssRules) -> do
let dom' = applyCssRules cssRules dom
print cssVariables
print cssRules
--print dom
print dom'
| mackenzie-tcc-arthur-gabriel/CSS-Applier | src/Main.hs | gpl-3.0 | 2,147 | 0 | 15 | 937 | 263 | 141 | 122 | 34 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Numerical.PETSc.Internal.PutGet.PC
-- Copyright : (c) Marco Zocca 2015
-- License : LGPL3
-- Maintainer : zocca . marco . gmail . com
-- Stability : experimental
--
-- | PC Mid-level interface
--
-----------------------------------------------------------------------------
module Numerical.PETSc.Internal.PutGet.PC where
import Numerical.PETSc.Internal.InlineC
import Numerical.PETSc.Internal.Types
import Numerical.PETSc.Internal.Exception
import Numerical.PETSc.Internal.Utils
pcSetType :: PC -> PCType_ -> IO ()
pcSetType pc pct = chk0 $ pcSetType' pc pct
| ocramz/petsc-hs | src/Numerical/PETSc/Internal/PutGet/PC.hs | gpl-3.0 | 677 | 0 | 8 | 90 | 85 | 56 | 29 | 7 | 1 |
module Print3Broken where
printSecond :: IO ()
printSecond = do
putStrLn greeting
main :: IO ()
main = do
putStrLn greeting
printSecond
where greeting = "Yarrr"
-- greeting :: String
-- greeting = "Yarrrr"
| dkensinger/haskell | haskellbook/print3broken.hs | gpl-3.0 | 219 | 0 | 7 | 47 | 58 | 30 | 28 | 9 | 1 |
{-- An simple todolist manager:
- Planned features : replace , prioritise
--}
module Main( main ) where
import System.Environment
import System.Directory
import System.Console.GetOpt
import System.IO
import Data.Maybe( fromMaybe )
import Data.List
import System.Exit
fileName=""
main = do
args <- getArgs
let ( actions, nonOpts, msgs ) = getOpt RequireOrder options args
opts <- foldl (>>=) (return defaultOptions) actions
let Options { optInput = input,
optOutput = output } = opts
input >>= output
data Options = Options {
optInput :: IO String,
optOutput :: String -> IO ()
}
defaultOptions :: Options
defaultOptions = Options {
optInput = getContents,
optOutput = putStr
}
--cli options
options :: [OptDescr (Options -> IO Options)]
options = [
Option ['h'] ["help"] (NoArg showHelp) "show help",
Option ['v'] ["view"] (NoArg view ) "view todoList",
Option ['a'] ["add"] (ReqArg add "todo" ) "add item to todolist",
Option ['r'] ["remove"] (ReqArg remove "lineNumber" ) "remove item from list",
Option ['s'] ["search"] (ReqArg search "keyword") "search you todo items",
Option ['p'] ["setPath"] (ReqArg path "path") "set the path for todofile",
Option ['V'] ["version"] (NoArg showVersion) "show version number"
]
--show the version of the porgram
showVersion _ = do
putStrLn "TodoListEditor version 0.2"
exitWith ExitSuccess
--show usage
showHelp _ = do
putStrLn "Usage: todo [OPTIONS] \n\tOPTIONS: \n\t\t-a [--add]:\tadd an todolist item\n\t\t-h [--help]\tshow help\n\t\t-p [--setPath]\tset the todolist file path\n\t\t-r [--remove]\tremove an line, give lineNumber as argument\n\t\t-s [--search]\tsearch the todolist with an keyword\n\t\t-v [--view]\tview the todolist\n\t\t-V [--version]\tshow the version\n"
exitWith ExitSuccess
--View the todo list
view _ = do
contents <- readFile fileName
let todoTasks = lines contents
numberedTasks = zipWith (\n line -> show n ++ " - " ++ line) [0..] todoTasks
putStr $ unlines numberedTasks
exitWith ExitSuccess
--Set path for todolist File
path args opt = do
let fileName = args
exitWith ExitSuccess
--Add an todo item
add args opt = do
appendFile fileName (args ++ "\n")
exitWith ExitSuccess
--Remove an todo item
remove args opt = do
handle <- openFile fileName ReadMode
(tempName, tempHandle) <- openTempFile "." "temp"
contents <- hGetContents handle
let number = read args :: Int
todoTasks = lines contents
newTodoItems = delete (todoTasks !! number) todoTasks
hPutStr tempHandle ( unlines newTodoItems )
hClose handle
hClose tempHandle
removeFile fileName
renameFile tempName fileName
exitWith ExitSuccess
--Search an todo item
search args opt = do
contents <- readFile fileName
let todoTasks = filter (args `isInfixOf`) (lines contents)
putStr ( unlines todoTasks )
exitWith ExitSuccess
| jelly/TodoList | todo.hs | gpl-3.0 | 2,947 | 29 | 15 | 604 | 787 | 411 | 376 | 68 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module Lambia.Interactive (interactive) where
import Prelude hiding (getLine, putStr, putStrLn, filter)
import Data.Char (isSpace)
import Data.ByteString.Char8 hiding (
append, map, splitAt, init,
dropWhile, head, null, isPrefixOf)
import Data.List.Split (splitOn)
import qualified Data.Map as M
import qualified Data.ByteString.Char8 as B
import Control.Applicative hiding (empty)
import Control.Monad
import Control.Monad.State.Strict
import Control.Monad.Trans.Except
import System.Console.Haskeline
import Lambia.Parse
import Lambia.Index
import Lambia.Apply ()
import Lambia.Types
type Act s a = InputT (StateT (Status s) IO) a
cf :: Store s => CompletionFunc (StateT (Status s) IO)
cf = completeWordWithPrev Nothing " ()`\'-,[]" $ \pv wd -> do
Status _ (Save (l,_)) <- get
let
(pva,pvb) = splitAt 4 $ dropWhile (==' ') pv
op = pva == "nepo" && (null pvb || head pvb == ' ')
wds = map pack $ splitOn "." wd
toComp :: M.Map ByteString (Entity s) -> [Completion]
toComp m = flip map (M.toList m) $ \(k,(Save (s,_),v)) -> let
k' = unpack k
in case v of
Nothing -> if op
then Completion k' k' True
else Completion (k'++".") k' False
Just e -> Completion k' k' $ M.null s
addComp :: ByteString -> Completion -> Completion
addComp s (Completion a b c) = Completion (t a) (t b) c where
t x = s' ++ "." ++ x
s' = unpack s
word :: [ByteString] -> Save s -> [Completion]
word [] (Save (s,_)) = toComp s
word [x] (Save (s,_)) = toComp $ M.filterWithKey (\k _ -> x`B.isPrefixOf`k) s
word (x:xs) (Save (s,_)) = case M.lookup x s of
Nothing -> []
Just (y,_) -> map (addComp x) $ word xs y
return $ word wds $ Save $ (,const Nothing) $ if op
then M.filter (\(Save (x,_),_) -> not $ M.null x) l
else l
setting :: Store s => Settings (StateT (Status s) IO)
setting = setComplete cf defaultSettings
interactive :: Store s => (Save s,Save s) -> IO ()
interactive (s1,s2) = let
i = runInputT setting $ withInterrupt $ ev empty
in void $ runStateT i $ Status s1 s2
ev :: Store s => ByteString -> Act s ()
ev str = do
let hdl :: MonadIO m => SomeException -> m (Maybe String)
hdl _ = return Nothing
xi <- handle hdl $ do
getInputLine $ if B.null str then "> " else "| "
let xj = fmap (flip snoc '\n' . pack) xi
case xj of
Nothing -> ev ""
Just x -> if B.null $ filter (not . isSpace) x
then ev str
else if x == ":q\n"
then outputStrLn "[Quit]"
else if B.null str && B.take 3 x == ":s "
then search $ B.dropWhile isSpace $ B.drop 3 x
else proc $ str`B.append`x
search :: Store s => ByteString -> Act s ()
search ss = do
Status _ l <- lift $ get
let
str = init $ unpack ss
s = map pack $ splitOn "." str
fu :: [ByteString] -> Save s -> Maybe s
fu [] _ = Nothing
fu [x] (Save (s,u)) = join $ (fmap fst . snd) <$> (M.lookup x s <|> u x)
fu (x:xs) (Save (s,u)) = case M.lookup x s <|> u x of
Just (s',_) -> fu xs s'
Nothing -> Nothing
case fu s l of
Nothing -> outputStrLn $ "Not in scope : " ++ str
Just l -> outputStrLn $ str ++ " = " ++ show l
ev ""
proc :: Store s => ByteString -> Act s ()
proc ss = case parseLines ss of
Left err -> case "unexpected \'\\NUL\'"`isInfixOf`err of
True -> do
ev ss
False -> do
outputStrLn $ unpack err
ev ""
Right e -> do
s <- lift $ get
let
(r,s') = flip runState s $ runExceptT $ case e of
Left d -> Left <$> ixDecl d
Right x -> Right <$> ixExpr x
s'' <- case r of
Left f -> do
outputStrLn $ unpack f
return s'
Right (Left d') -> return s'
Right (Right e') -> do
let
v = fst $ apply e'
hdl :: MonadIO m => a -> SomeException -> InputT m a
hdl a _ = outputStrLn "[Interrupt]" >> return a
handle (hdl s') $ do
outputStrLn $ show v
return $ case s' of
Status a u -> Status a $ append "it" Nothing v u
lift $ put s''
ev ""
| phi16/Lambia | src/Lambia/Interactive.hs | gpl-3.0 | 4,163 | 37 | 25 | 1,197 | 1,882 | 950 | 932 | 117 | 7 |
{-# LANGUAGE OverloadedStrings #-}
module Teatros.Types where
data Entidad = EntidadPeriodico
| EntidadProgramaMano
| EntidadAfiche
| EntidadFotografia
| EntidadAudiovisual
| EntidadBibliografia
| EntidadPremio
| EntidadObraGrafica
| EntidadActividadCultural
| EntidadProgramaAcademico
| arpunk/jfdb | src/Teatros/Types.hs | gpl-3.0 | 404 | 0 | 5 | 147 | 41 | 27 | 14 | 12 | 0 |
{-# LANGUAGE ExistentialQuantification, FlexibleInstances #-}
-- module Mescaline.EngineSF where
import Control.Applicative
import Control.Arrow ((>>>), first, second)
import Control.Concurrent (ThreadId, forkIO, forkOS, threadDelay)
import qualified Control.Concurrent.Chan as Chan
import qualified Control.Concurrent.Chan.Chunked as CChan
import Control.Monad (forever, liftM)
import Control.Monad.Fix (fix)
import qualified Control.Monad.Trans.State as State
import qualified Data.Foldable as Fold
import qualified Data.Map as Map
import Data.Monoid (mappend, mempty)
import Mescaline (Time)
import qualified Mescaline.Data.PriorityQueue as PQ
import Mescaline.Data.Signal
import Mescaline.FeatureSpace.Model (FeatureSpace, RegionId, Region)
import qualified Mescaline.FeatureSpace.Model as FeatureSpace
import Mescaline.Pattern (Pattern)
import Mescaline.Pattern.Event (Event)
import Sound.OpenSoundControl.Time (pauseThreadUntil, utcr)
import qualified System.Console.SimpleLineEditor as RL
-- data Input =
-- UpdateRegion RegionId Region
-- | PatternControl RegionId Control Value
-- | SetPattern RegionId Pattern
--
-- data Output =
-- RegionChanged RegionId Region
-- | PatternChanged PatternOutput
-- | UnitStarted Unit
-- | UnitStopped Unit
-- instance Show FeatureSpace where
-- show _ = "FeatureSpace"
-- data Scheduler m = Scheduler (PQ.PQueue Time (m ()))
--
-- instance Show (Scheduler m) where
-- show _ = "Scheduler"
--
-- scheduler :: Scheduler m
-- scheduler = Scheduler PQ.empty
--
-- schedule :: Monad m => Time -> m () -> Scheduler m -> Scheduler m
-- schedule time action (Scheduler pq) = Scheduler (PQ.insert time action pq)
--
-- tick :: Monad m => Time -> Scheduler m -> m (Scheduler m)
-- tick time (Scheduler pq) = do
-- let (as, pq') = PQ.popUntil pq time
-- sequence as
-- return (Scheduler pq')
type UnitId = Int
data Unit = Unit deriving Show
-- type FeatureSpace = [Unit]
-- type RegionId = Int
-- data Region = Region (Double, Double) Double deriving (Read, Show)
-- data PatternRate
-- data Pattern a = Pattern (EventS TickRate a) deriving (Show)
data UnitFilter =
Exclude UnitId
deriving (Show)
data Filter = Filter {
files :: [FilePath]
, unitFilter :: [UnitFilter]
} deriving (Show)
type Vector a = [a]
class IsMapping a where
map2D :: a -> Vector Double -> Vector Double
instance IsMapping (Vector Double -> Vector Double) where
map2D f = f
data Mapping = forall a . IsMapping a => Mapping {
features :: [String]
, featureMapping :: a
}
instance Show Mapping where
show _ = "Mapping"
data View = View {
filter :: Filter
, mapping :: Mapping
} deriving (Show)
type RegionMap = Map.Map RegionId Region
type ProcessId = Int
type Process = Pattern Event
type ProcessMap = Map.Map ProcessId Process
instance Show FeatureSpace where
show _ = "FeatureSpace"
type SceneId = Int
data Scene = Scene {
view :: View
, featureSpace :: FeatureSpace
, processes :: PQ.PriorityQueue Time (RegionId, Process)
} deriving (Show)
defaultScene :: Scene
defaultScene = Scene (View (Filter [] []) (Mapping [] (id :: Vector Double -> Vector Double))) FeatureSpace.empty Map.empty
type SceneMap = Map.Map SceneId Scene
data State = State {
time :: !Time
, scenes :: SceneMap
, currentScene :: Maybe Scene
} deriving (Show)
makeState :: Time -> State
makeState t0 = State t0 Map.empty Nothing
data TransportChange = Start | Pause | Reset deriving (Eq, Read, Show)
data Input =
GetState
| AddScene SceneId
-- Regions
| AddRegion SceneId RegionId (Double,Double) Double
| SetPattern SceneId RegionId ()
| UpdateRegion SceneId RegionId (Double,Double) Double
-- Patterns
-- Transport
| Transport TransportChange
deriving (Read, Show)
data Output =
GetState' State
| AddScene' SceneId Scene
-- Regions
| AddRegion' SceneId RegionId
| UpdateRegion' Scene RegionId (Double,Double) Double
-- Synths
| Synth' SynthCommand
-- Transport
| Transport' TransportChange
deriving (Show)
data SynthCommand =
StartUnit Time Event
| StopUnit Time
deriving (Show)
data TickRate
type Update a = State.State ([Output], State) a
runUpdate :: Update a -> State -> ([Output], State)
runUpdate u s = State.execState u (mempty, s)
get :: Update State
get = liftM snd State.get
gets :: (State -> a) -> Update a
gets f = liftM f get
modify :: (State -> State) -> Update ()
modify f = State.modify (\(o, s) -> (o, f s))
output :: Output -> Update ()
output o = State.modify (\(os, s) -> (os `mappend` [o], s))
update :: Input -> Update ()
update GetState = output =<< gets GetState'
update (AddScene si) = do
let sc = defaultScene
modify (\s -> s { scenes = Map.insert si sc (scenes s) })
output (AddScene' si sc)
update (AddRegion si ri c r) = do
modify $ \s ->
case Map.lookup si (scenes s) of
Nothing -> s
Just sc ->
s {
scenes =
Map.insert si (sc {
featureSpace = FeatureSpace.updateRegion (FeatureSpace.mkRegion ri c r) (featureSpace sc)
})
(scenes s) }
output $ AddRegion' si ri
update (Transport t) =
output $ Transport' t
-- combine :: [a -> ([b], a)] -> [b] -> a -> ([b], a)
-- combine fs bs a = foldl (\(bs, a) f -> let (bs', a') = f a in (bs ++ bs', a')) (bs, a) fs
-- eventS :: Signal [a] -> EventS [a]
-- eventS = fmap f
-- where
-- f [] -> Nothing
-- f as -> Just as
--
-- regionS :: Signal ([Input], State) -> Signal ([Output], Maybe (RegionMap -> RegionMap))
-- regionS s =
-- let (inputs, state) = unzipS
-- events = eventS inputs
-- f (is, s) =
-- in fmap f (events `snapshot` state)
tick :: Time -> State -> State
tick dt s = s { time = time s + dt }
engine :: Double -> Signal TickRate ([Input], State) -> Signal TickRate ([Output], State)
engine dt = fmap (\(inputs, state) -> runUpdate (mapM_ update inputs) state)
>>> fmap (second (tick dt))
mkEngine :: Double -> IO ([Input] -> IO (), IO [Output])
mkEngine dt = do
ichan <- CChan.newChan
(inputS, addInput) <- makeStream
ochan <- Chan.newChan
forkOS $ do
t0 <- utcr
let state0 = makeState t0
(outputS, stateS) = unzipS (engine dt (zipS inputS (initS state0 stateS)))
getInput = CChan.readChanAvailable ichan >>= addInput
putOutput = Chan.writeChan ochan
run (inp:inps) (outp:outps) (s:ss) = do
-- print (inp, outp, s)
putOutput outp
-- putStrLn "sent output"
-- FIXME: `pauseThreadUntil' doesn't seem to work in ghci 7.0.1!
dtms <- liftM (floor . (*1e6) . (time s -)) utcr
-- print dtms
threadDelay dtms
getInput
-- putStrLn "recurse"
run inps outps ss
getInput
run (unS inputS) (unS outputS) (unS stateS)
return (CChan.writeList2Chan ichan, Chan.readChan ochan)
-- engine2 :: Time -> [Input] -> State -> ([Output], State)
-- engine2 dt is state = ([], tick dt state)
--
-- mkEngine2 :: Double -> IO ([Input] -> IO (), IO [Output])
-- mkEngine2 dt = do
-- ichan <- CChan.newChan
-- ochan <- Chan.newChan
-- forkOS $ do
-- let getInputs = CChan.readChanAvailable ichan
-- putOutputs = Chan.writeChan ochan
-- run state = do
-- is <- getInputs
-- let (os, state') = engine2 dt is state
-- putOutputs os
-- dt <- liftM (floor . (*1e6) . (time state' -)) utcr
-- threadDelay dt
-- run state'
-- run . makeState =<< utcr
-- return (CChan.writeList2Chan ichan, Chan.readChan ochan)
mkDebugEngine :: Double -> IO ([Input] -> IO ())
mkDebugEngine dt = do
(i, o) <- mkEngine dt
forkIO $ forever $ do
os <- o
case os of
[] -> return ()
_ -> print os
return i
main = do
RL.initialise
i <- mkDebugEngine 1e-3
fix $ \loop -> do
l <- RL.getLineEdited "> "
case l of
Nothing -> return ()
Just "" -> loop
Just "exit" -> return ()
Just s -> do
case readMaybe s of
Nothing -> putStrLn "Parse Error"
Just a -> i [a]
loop
RL.restore
return ()
where
readMaybe s = case reads s of
((a, _):_) -> return a
_ -> Nothing
| kaoskorobase/mescaline | lib/mescaline/Mescaline/EngineSF.hs | gpl-3.0 | 8,840 | 0 | 21 | 2,557 | 2,181 | 1,205 | 976 | -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.StreetViewPublish.Photo.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Gets the metadata of the specified Photo. This method returns the
-- following error codes: * google.rpc.Code.PERMISSION_DENIED if the
-- requesting user did not create the requested Photo. *
-- google.rpc.Code.NOT_FOUND if the requested Photo does not exist. *
-- google.rpc.Code.UNAVAILABLE if the requested Photo is still being
-- indexed.
--
-- /See:/ <https://developers.google.com/streetview/publish/ Street View Publish API Reference> for @streetviewpublish.photo.get@.
module Network.Google.Resource.StreetViewPublish.Photo.Get
(
-- * REST Resource
PhotoGetResource
-- * Creating a Request
, photoGet
, PhotoGet
-- * Request Lenses
, pgXgafv
, pgLanguageCode
, pgUploadProtocol
, pgAccessToken
, pgUploadType
, pgView
, pgPhotoId
, pgCallback
) where
import Network.Google.Prelude
import Network.Google.StreetViewPublish.Types
-- | A resource alias for @streetviewpublish.photo.get@ method which the
-- 'PhotoGet' request conforms to.
type PhotoGetResource =
"v1" :>
"photo" :>
Capture "photoId" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "languageCode" Text :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "view" PhotoGetView :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Photo
-- | Gets the metadata of the specified Photo. This method returns the
-- following error codes: * google.rpc.Code.PERMISSION_DENIED if the
-- requesting user did not create the requested Photo. *
-- google.rpc.Code.NOT_FOUND if the requested Photo does not exist. *
-- google.rpc.Code.UNAVAILABLE if the requested Photo is still being
-- indexed.
--
-- /See:/ 'photoGet' smart constructor.
data PhotoGet =
PhotoGet'
{ _pgXgafv :: !(Maybe Xgafv)
, _pgLanguageCode :: !(Maybe Text)
, _pgUploadProtocol :: !(Maybe Text)
, _pgAccessToken :: !(Maybe Text)
, _pgUploadType :: !(Maybe Text)
, _pgView :: !(Maybe PhotoGetView)
, _pgPhotoId :: !Text
, _pgCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PhotoGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pgXgafv'
--
-- * 'pgLanguageCode'
--
-- * 'pgUploadProtocol'
--
-- * 'pgAccessToken'
--
-- * 'pgUploadType'
--
-- * 'pgView'
--
-- * 'pgPhotoId'
--
-- * 'pgCallback'
photoGet
:: Text -- ^ 'pgPhotoId'
-> PhotoGet
photoGet pPgPhotoId_ =
PhotoGet'
{ _pgXgafv = Nothing
, _pgLanguageCode = Nothing
, _pgUploadProtocol = Nothing
, _pgAccessToken = Nothing
, _pgUploadType = Nothing
, _pgView = Nothing
, _pgPhotoId = pPgPhotoId_
, _pgCallback = Nothing
}
-- | V1 error format.
pgXgafv :: Lens' PhotoGet (Maybe Xgafv)
pgXgafv = lens _pgXgafv (\ s a -> s{_pgXgafv = a})
-- | The BCP-47 language code, such as \"en-US\" or \"sr-Latn\". For more
-- information, see
-- http:\/\/www.unicode.org\/reports\/tr35\/#Unicode_locale_identifier. If
-- language_code is unspecified, the user\'s language preference for Google
-- services is used.
pgLanguageCode :: Lens' PhotoGet (Maybe Text)
pgLanguageCode
= lens _pgLanguageCode
(\ s a -> s{_pgLanguageCode = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pgUploadProtocol :: Lens' PhotoGet (Maybe Text)
pgUploadProtocol
= lens _pgUploadProtocol
(\ s a -> s{_pgUploadProtocol = a})
-- | OAuth access token.
pgAccessToken :: Lens' PhotoGet (Maybe Text)
pgAccessToken
= lens _pgAccessToken
(\ s a -> s{_pgAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pgUploadType :: Lens' PhotoGet (Maybe Text)
pgUploadType
= lens _pgUploadType (\ s a -> s{_pgUploadType = a})
-- | Required. Specifies if a download URL for the photo bytes should be
-- returned in the Photo response.
pgView :: Lens' PhotoGet (Maybe PhotoGetView)
pgView = lens _pgView (\ s a -> s{_pgView = a})
-- | Required. ID of the Photo.
pgPhotoId :: Lens' PhotoGet Text
pgPhotoId
= lens _pgPhotoId (\ s a -> s{_pgPhotoId = a})
-- | JSONP
pgCallback :: Lens' PhotoGet (Maybe Text)
pgCallback
= lens _pgCallback (\ s a -> s{_pgCallback = a})
instance GoogleRequest PhotoGet where
type Rs PhotoGet = Photo
type Scopes PhotoGet =
'["https://www.googleapis.com/auth/streetviewpublish"]
requestClient PhotoGet'{..}
= go _pgPhotoId _pgXgafv _pgLanguageCode
_pgUploadProtocol
_pgAccessToken
_pgUploadType
_pgView
_pgCallback
(Just AltJSON)
streetViewPublishService
where go
= buildClient (Proxy :: Proxy PhotoGetResource)
mempty
| brendanhay/gogol | gogol-streetviewpublish/gen/Network/Google/Resource/StreetViewPublish/Photo/Get.hs | mpl-2.0 | 5,786 | 0 | 18 | 1,346 | 873 | 512 | 361 | 120 | 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.SQL.Users.Insert
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates a new user in a Cloud SQL instance.
--
-- /See:/ <https://developers.google.com/cloud-sql/ Cloud SQL Admin API Reference> for @sql.users.insert@.
module Network.Google.Resource.SQL.Users.Insert
(
-- * REST Resource
UsersInsertResource
-- * Creating a Request
, usersInsert
, UsersInsert
-- * Request Lenses
, uiXgafv
, uiUploadProtocol
, uiProject
, uiAccessToken
, uiUploadType
, uiPayload
, uiCallback
, uiInstance
) where
import Network.Google.Prelude
import Network.Google.SQLAdmin.Types
-- | A resource alias for @sql.users.insert@ method which the
-- 'UsersInsert' request conforms to.
type UsersInsertResource =
"v1" :>
"projects" :>
Capture "project" Text :>
"instances" :>
Capture "instance" Text :>
"users" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] User :> Post '[JSON] Operation
-- | Creates a new user in a Cloud SQL instance.
--
-- /See:/ 'usersInsert' smart constructor.
data UsersInsert =
UsersInsert'
{ _uiXgafv :: !(Maybe Xgafv)
, _uiUploadProtocol :: !(Maybe Text)
, _uiProject :: !Text
, _uiAccessToken :: !(Maybe Text)
, _uiUploadType :: !(Maybe Text)
, _uiPayload :: !User
, _uiCallback :: !(Maybe Text)
, _uiInstance :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UsersInsert' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'uiXgafv'
--
-- * 'uiUploadProtocol'
--
-- * 'uiProject'
--
-- * 'uiAccessToken'
--
-- * 'uiUploadType'
--
-- * 'uiPayload'
--
-- * 'uiCallback'
--
-- * 'uiInstance'
usersInsert
:: Text -- ^ 'uiProject'
-> User -- ^ 'uiPayload'
-> Text -- ^ 'uiInstance'
-> UsersInsert
usersInsert pUiProject_ pUiPayload_ pUiInstance_ =
UsersInsert'
{ _uiXgafv = Nothing
, _uiUploadProtocol = Nothing
, _uiProject = pUiProject_
, _uiAccessToken = Nothing
, _uiUploadType = Nothing
, _uiPayload = pUiPayload_
, _uiCallback = Nothing
, _uiInstance = pUiInstance_
}
-- | V1 error format.
uiXgafv :: Lens' UsersInsert (Maybe Xgafv)
uiXgafv = lens _uiXgafv (\ s a -> s{_uiXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
uiUploadProtocol :: Lens' UsersInsert (Maybe Text)
uiUploadProtocol
= lens _uiUploadProtocol
(\ s a -> s{_uiUploadProtocol = a})
-- | Project ID of the project that contains the instance.
uiProject :: Lens' UsersInsert Text
uiProject
= lens _uiProject (\ s a -> s{_uiProject = a})
-- | OAuth access token.
uiAccessToken :: Lens' UsersInsert (Maybe Text)
uiAccessToken
= lens _uiAccessToken
(\ s a -> s{_uiAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
uiUploadType :: Lens' UsersInsert (Maybe Text)
uiUploadType
= lens _uiUploadType (\ s a -> s{_uiUploadType = a})
-- | Multipart request metadata.
uiPayload :: Lens' UsersInsert User
uiPayload
= lens _uiPayload (\ s a -> s{_uiPayload = a})
-- | JSONP
uiCallback :: Lens' UsersInsert (Maybe Text)
uiCallback
= lens _uiCallback (\ s a -> s{_uiCallback = a})
-- | Database instance ID. This does not include the project ID.
uiInstance :: Lens' UsersInsert Text
uiInstance
= lens _uiInstance (\ s a -> s{_uiInstance = a})
instance GoogleRequest UsersInsert where
type Rs UsersInsert = Operation
type Scopes UsersInsert =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/sqlservice.admin"]
requestClient UsersInsert'{..}
= go _uiProject _uiInstance _uiXgafv
_uiUploadProtocol
_uiAccessToken
_uiUploadType
_uiCallback
(Just AltJSON)
_uiPayload
sQLAdminService
where go
= buildClient (Proxy :: Proxy UsersInsertResource)
mempty
| brendanhay/gogol | gogol-sqladmin/gen/Network/Google/Resource/SQL/Users/Insert.hs | mpl-2.0 | 5,115 | 0 | 20 | 1,320 | 864 | 502 | 362 | 125 | 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.CloudResourceManager.Operations.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Gets the latest state of a long-running operation. Clients can use this
-- method to poll the operation result at intervals as recommended by the
-- API service.
--
-- /See:/ <https://cloud.google.com/resource-manager Cloud Resource Manager API Reference> for @cloudresourcemanager.operations.get@.
module Network.Google.Resource.CloudResourceManager.Operations.Get
(
-- * REST Resource
OperationsGetResource
-- * Creating a Request
, operationsGet
, OperationsGet
-- * Request Lenses
, ogXgafv
, ogUploadProtocol
, ogAccessToken
, ogUploadType
, ogName
, ogCallback
) where
import Network.Google.Prelude
import Network.Google.ResourceManager.Types
-- | A resource alias for @cloudresourcemanager.operations.get@ method which the
-- 'OperationsGet' request conforms to.
type OperationsGetResource =
"v3" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Operation
-- | Gets the latest state of a long-running operation. Clients can use this
-- method to poll the operation result at intervals as recommended by the
-- API service.
--
-- /See:/ 'operationsGet' smart constructor.
data OperationsGet =
OperationsGet'
{ _ogXgafv :: !(Maybe Xgafv)
, _ogUploadProtocol :: !(Maybe Text)
, _ogAccessToken :: !(Maybe Text)
, _ogUploadType :: !(Maybe Text)
, _ogName :: !Text
, _ogCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OperationsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ogXgafv'
--
-- * 'ogUploadProtocol'
--
-- * 'ogAccessToken'
--
-- * 'ogUploadType'
--
-- * 'ogName'
--
-- * 'ogCallback'
operationsGet
:: Text -- ^ 'ogName'
-> OperationsGet
operationsGet pOgName_ =
OperationsGet'
{ _ogXgafv = Nothing
, _ogUploadProtocol = Nothing
, _ogAccessToken = Nothing
, _ogUploadType = Nothing
, _ogName = pOgName_
, _ogCallback = Nothing
}
-- | V1 error format.
ogXgafv :: Lens' OperationsGet (Maybe Xgafv)
ogXgafv = lens _ogXgafv (\ s a -> s{_ogXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
ogUploadProtocol :: Lens' OperationsGet (Maybe Text)
ogUploadProtocol
= lens _ogUploadProtocol
(\ s a -> s{_ogUploadProtocol = a})
-- | OAuth access token.
ogAccessToken :: Lens' OperationsGet (Maybe Text)
ogAccessToken
= lens _ogAccessToken
(\ s a -> s{_ogAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
ogUploadType :: Lens' OperationsGet (Maybe Text)
ogUploadType
= lens _ogUploadType (\ s a -> s{_ogUploadType = a})
-- | The name of the operation resource.
ogName :: Lens' OperationsGet Text
ogName = lens _ogName (\ s a -> s{_ogName = a})
-- | JSONP
ogCallback :: Lens' OperationsGet (Maybe Text)
ogCallback
= lens _ogCallback (\ s a -> s{_ogCallback = a})
instance GoogleRequest OperationsGet where
type Rs OperationsGet = Operation
type Scopes OperationsGet =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only"]
requestClient OperationsGet'{..}
= go _ogName _ogXgafv _ogUploadProtocol
_ogAccessToken
_ogUploadType
_ogCallback
(Just AltJSON)
resourceManagerService
where go
= buildClient (Proxy :: Proxy OperationsGetResource)
mempty
| brendanhay/gogol | gogol-resourcemanager/gen/Network/Google/Resource/CloudResourceManager/Operations/Get.hs | mpl-2.0 | 4,609 | 0 | 15 | 1,057 | 701 | 411 | 290 | 99 | 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.PlacementStrategies.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes an existing placement strategy.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ Campaign Manager 360 API Reference> for @dfareporting.placementStrategies.delete@.
module Network.Google.Resource.DFAReporting.PlacementStrategies.Delete
(
-- * REST Resource
PlacementStrategiesDeleteResource
-- * Creating a Request
, placementStrategiesDelete
, PlacementStrategiesDelete
-- * Request Lenses
, psdXgafv
, psdUploadProtocol
, psdAccessToken
, psdUploadType
, psdProFileId
, psdId
, psdCallback
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.placementStrategies.delete@ method which the
-- 'PlacementStrategiesDelete' request conforms to.
type PlacementStrategiesDeleteResource =
"dfareporting" :>
"v3.5" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"placementStrategies" :>
Capture "id" (Textual Int64) :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] ()
-- | Deletes an existing placement strategy.
--
-- /See:/ 'placementStrategiesDelete' smart constructor.
data PlacementStrategiesDelete =
PlacementStrategiesDelete'
{ _psdXgafv :: !(Maybe Xgafv)
, _psdUploadProtocol :: !(Maybe Text)
, _psdAccessToken :: !(Maybe Text)
, _psdUploadType :: !(Maybe Text)
, _psdProFileId :: !(Textual Int64)
, _psdId :: !(Textual Int64)
, _psdCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PlacementStrategiesDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'psdXgafv'
--
-- * 'psdUploadProtocol'
--
-- * 'psdAccessToken'
--
-- * 'psdUploadType'
--
-- * 'psdProFileId'
--
-- * 'psdId'
--
-- * 'psdCallback'
placementStrategiesDelete
:: Int64 -- ^ 'psdProFileId'
-> Int64 -- ^ 'psdId'
-> PlacementStrategiesDelete
placementStrategiesDelete pPsdProFileId_ pPsdId_ =
PlacementStrategiesDelete'
{ _psdXgafv = Nothing
, _psdUploadProtocol = Nothing
, _psdAccessToken = Nothing
, _psdUploadType = Nothing
, _psdProFileId = _Coerce # pPsdProFileId_
, _psdId = _Coerce # pPsdId_
, _psdCallback = Nothing
}
-- | V1 error format.
psdXgafv :: Lens' PlacementStrategiesDelete (Maybe Xgafv)
psdXgafv = lens _psdXgafv (\ s a -> s{_psdXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
psdUploadProtocol :: Lens' PlacementStrategiesDelete (Maybe Text)
psdUploadProtocol
= lens _psdUploadProtocol
(\ s a -> s{_psdUploadProtocol = a})
-- | OAuth access token.
psdAccessToken :: Lens' PlacementStrategiesDelete (Maybe Text)
psdAccessToken
= lens _psdAccessToken
(\ s a -> s{_psdAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
psdUploadType :: Lens' PlacementStrategiesDelete (Maybe Text)
psdUploadType
= lens _psdUploadType
(\ s a -> s{_psdUploadType = a})
-- | User profile ID associated with this request.
psdProFileId :: Lens' PlacementStrategiesDelete Int64
psdProFileId
= lens _psdProFileId (\ s a -> s{_psdProFileId = a})
. _Coerce
-- | Placement strategy ID.
psdId :: Lens' PlacementStrategiesDelete Int64
psdId
= lens _psdId (\ s a -> s{_psdId = a}) . _Coerce
-- | JSONP
psdCallback :: Lens' PlacementStrategiesDelete (Maybe Text)
psdCallback
= lens _psdCallback (\ s a -> s{_psdCallback = a})
instance GoogleRequest PlacementStrategiesDelete
where
type Rs PlacementStrategiesDelete = ()
type Scopes PlacementStrategiesDelete =
'["https://www.googleapis.com/auth/dfatrafficking"]
requestClient PlacementStrategiesDelete'{..}
= go _psdProFileId _psdId _psdXgafv
_psdUploadProtocol
_psdAccessToken
_psdUploadType
_psdCallback
(Just AltJSON)
dFAReportingService
where go
= buildClient
(Proxy :: Proxy PlacementStrategiesDeleteResource)
mempty
| brendanhay/gogol | gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/PlacementStrategies/Delete.hs | mpl-2.0 | 5,282 | 0 | 19 | 1,234 | 825 | 476 | 349 | 116 | 1 |
module Util where
import Prelude ()
import BasicPrelude
import Control.Concurrent
import Control.Concurrent.STM (STM, atomically)
import Data.Word (Word16)
import Data.Bits (shiftL, (.|.))
import Data.Char (isDigit)
import Control.Applicative (many)
import Control.Error (hush)
import Data.Time (getCurrentTime)
import Data.XML.Types as XML (Name(Name), Element(..), Node(NodeElement, NodeContent), Content(ContentText), isNamed, elementText, elementChildren, attributeText)
import Crypto.Random (getSystemDRG, withRandomBytes)
import Data.ByteString.Base58 (bitcoinAlphabet, encodeBase58)
import Data.Digest.Pure.SHA (sha1, bytestringDigest)
import Data.Void (absurd)
import UnexceptionalIO (Unexceptional)
import qualified UnexceptionalIO as UIO
import qualified Control.Exception as Ex
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Network.Protocol.XMPP as XMPP
import qualified Data.Attoparsec.Text as Atto
import qualified Data.ByteString.Lazy as LZ
import qualified Text.Regex.PCRE.Light as PCRE
instance Unexceptional XMPP.XMPP where
lift = liftIO . UIO.lift
log :: (Show a, Unexceptional m) => String -> a -> m ()
log tag x = fromIO_ $ do
time <- getCurrentTime
putStr (tshow time ++ s" " ++ fromString tag ++ s" :: ") >> print x >> putStrLn mempty
s :: (IsString a) => String -> a
s = fromString
(.:) :: (c -> d) -> (a -> b -> c) -> a -> b -> d
(.:) = (.) . (.)
fromIO_ :: (Unexceptional m) => IO a -> m a
fromIO_ = fmap (either absurd id) . UIO.fromIO' (error . show)
atomicUIO :: (Unexceptional m) => STM a -> m a
atomicUIO = fromIO_ . atomically
escapeJid :: Text -> Text
escapeJid txt = mconcat result
where
Right result = Atto.parseOnly (many (
slashEscape <|>
replace ' ' "\\20" <|>
replace '"' "\\22" <|>
replace '&' "\\26" <|>
replace '\'' "\\27" <|>
replace '/' "\\2f" <|>
replace ':' "\\3a" <|>
replace '<' "\\3c" <|>
replace '>' "\\3e" <|>
replace '@' "\\40" <|>
fmap T.singleton Atto.anyChar
) <* Atto.endOfInput) txt
replace c str = Atto.char c *> pure (fromString str)
-- XEP-0106 says to only escape \ when absolutely necessary
slashEscape =
fmap (s"\\5c"++) $
Atto.char '\\' *> Atto.choice escapes
escapes = map (Atto.string . fromString) [
"20", "22", "26", "27", "2f", "3a", "3c", "3e", "40", "5c"
]
unescapeJid :: Text -> Text
unescapeJid txt = fromString result
where
Right result = Atto.parseOnly (many (
(Atto.char '\\' *> Atto.choice unescapes) <|>
Atto.anyChar
) <* Atto.endOfInput) txt
unescapes = map (\(str, c) -> Atto.string (fromString str) *> pure c) [
("20", ' '), ("22", '"'), ("26", '&'), ("27", '\''), ("2f", '/'), ("3a", ':'), ("3c", '<'), ("3e", '>'), ("40", '@'), ("5c", '\\')
]
-- Matches any URL-ish text, but not [email protected] forms
autolinkRegex :: PCRE.Regex
autolinkRegex = PCRE.compile (encodeUtf8 $ s"(?<!@)(?<=\\b)(?:((http|https)://)?([a-z0-9-]+\\.)?[a-z0-9-]+(\\.[a-z]{2,6}){1,3}(/[a-z0-9.,_/~#&=;%+?-]*)?)") [PCRE.caseless, PCRE.dotall]
sanitizeSipLocalpart :: Text -> Maybe Text
sanitizeSipLocalpart localpart
| Just ('+', tel) <- T.uncons candidate,
T.all isDigit tel = Just candidate
| T.length candidate < 3 =
Just $ s"13;phone-context=anonymous.phone-context.soprani.ca"
| candidate == s"Restricted" =
Just $ s"14;phone-context=anonymous.phone-context.soprani.ca"
| candidate == s"anonymous" =
Just $ s"15;phone-context=anonymous.phone-context.soprani.ca"
| candidate == s"Anonymous" =
Just $ s"16;phone-context=anonymous.phone-context.soprani.ca"
| candidate == s"unavailable" =
Just $ s"17;phone-context=anonymous.phone-context.soprani.ca"
| candidate == s"Unavailable" =
Just $ s"18;phone-context=anonymous.phone-context.soprani.ca"
| otherwise = Nothing
where
candidate = fst $ T.breakOn (s"@") $ unescapeJid localpart
showAvailableness :: String -> Word8
showAvailableness "chat" = 5
showAvailableness "" = 4
showAvailableness "away" = 3
showAvailableness "dnd" = 2
showAvailableness "xa" = 1
showAvailableness _ = 0
priorityAvailableness :: Integer -> Word8
priorityAvailableness priority
| priority > 127 = 0xff
| priority < -128 = 0x00
| otherwise = fromIntegral (priority + 128)
availableness :: Text -> Integer -> Word16
availableness sshow priority =
(fromIntegral (showAvailableness (textToString sshow)) `shiftL` 8) .|.
(fromIntegral (priorityAvailableness priority))
parsePhoneContext :: Text -> Maybe (Text, Text)
parsePhoneContext txt = hush $ Atto.parseOnly (
(,) <$> Atto.takeWhile isDigit <* Atto.string (s";phone-context=") <*> Atto.takeTill (Atto.inClass " ;")
<* Atto.endOfInput
) txt
bareTxt :: XMPP.JID -> Text
bareTxt (XMPP.JID (Just node) domain _) = mconcat [XMPP.strNode node, s"@", XMPP.strDomain domain]
bareTxt (XMPP.JID Nothing domain _) = XMPP.strDomain domain
getFormField :: XML.Element -> Text -> Maybe Text
getFormField form var =
listToMaybe $ mapMaybe (\node ->
case node of
NodeElement el
| elementName el == s"{jabber:x:data}field" &&
(attributeText (s"{jabber:x:data}var") el == Just var ||
attributeText (s"var") el == Just var) ->
Just $ mconcat $
elementText =<< isNamed (s"{jabber:x:data}value") =<< elementChildren el
_ -> Nothing
) (elementNodes form)
genToken :: Int -> IO Text
genToken n = do
g <- getSystemDRG
return $ fst $ withRandomBytes g n (T.decodeUtf8 . encodeBase58 bitcoinAlphabet)
child :: (XMPP.Stanza s) => Name -> s -> Maybe Element
child name = listToMaybe .
(isNamed name <=< XMPP.stanzaPayloads)
attrOrBlank :: XML.Name -> XML.Element -> Text
attrOrBlank name el = fromMaybe mempty $ XML.attributeText name el
discoCapsIdentities :: XML.Element -> [Text]
discoCapsIdentities query =
sort $
map (\identity -> mconcat $ intersperse (s"/") [
attrOrBlank (s"category") identity,
attrOrBlank (s"type") identity,
attrOrBlank (s"xml:lang") identity,
attrOrBlank (s"name") identity
]) $
XML.isNamed (s"{http://jabber.org/protocol/disco#info}identity") =<<
XML.elementChildren query
discoVars :: XML.Element -> [Text]
discoVars query =
sort $
mapMaybe (XML.attributeText (s"var")) $
XML.isNamed (s"{http://jabber.org/protocol/disco#info}feature") =<<
XML.elementChildren query
data DiscoForm = DiscoForm Text [(Text, [Text])] deriving (Show, Ord, Eq)
oneDiscoForm :: XML.Element -> DiscoForm
oneDiscoForm form =
DiscoForm form_type (filter ((/= s"FORM_TYPE") . fst) fields)
where
form_type = mconcat $ fromMaybe [] $ lookup (s"FORM_TYPE") fields
fields = sort $ map (\field ->
(
attrOrBlank (s"var") field,
sort (map (mconcat . XML.elementText) $ XML.isNamed (s"{jabber:x:data}value") =<< XML.elementChildren form)
)
) $
XML.isNamed (s"{jabber:x:data}field") =<<
XML.elementChildren form
discoForms :: XML.Element -> [DiscoForm]
discoForms query =
sort $
map oneDiscoForm $
XML.isNamed (s"{jabber:x:data}x") =<<
XML.elementChildren query
discoCapsForms :: XML.Element -> [Text]
discoCapsForms query =
concatMap (\(DiscoForm form_type fields) ->
form_type : concatMap (uncurry (:)) fields
) (discoForms query)
discoToCaps :: XML.Element -> Text
discoToCaps query =
(mconcat $ intersperse (s"<") (discoCapsIdentities query ++ discoVars query ++ discoCapsForms query)) ++ s"<"
discoToCapsHash :: XML.Element -> ByteString
discoToCapsHash query =
LZ.toStrict $ bytestringDigest $ sha1 $ LZ.fromStrict $ T.encodeUtf8 $ discoToCaps query
getBody :: String -> XMPP.Message -> Maybe Text
getBody ns = listToMaybe . fmap (mconcat . XML.elementText) . (XML.isNamed (XML.Name (fromString "body") (Just $ fromString ns) Nothing) <=< XMPP.messagePayloads)
mkSMS :: XMPP.JID -> XMPP.JID -> Text -> XMPP.Message
mkSMS from to txt = (XMPP.emptyMessage XMPP.MessageChat) {
XMPP.messageTo = Just to,
XMPP.messageFrom = Just from,
XMPP.messagePayloads = [mkElement (s"{jabber:component:accept}body") txt]
}
castException :: (Ex.Exception e1, Ex.Exception e2) => e1 -> Maybe e2
castException = Ex.fromException . Ex.toException
-- Re-throws all by ThreadKilled async to parent thread
-- Makes sync child exceptions async in parent, which is a bit sloppy
forkXMPP :: XMPP.XMPP () -> XMPP.XMPP ThreadId
forkXMPP kid = do
parent <- liftIO myThreadId
forkFinallyXMPP kid (either (handler parent) (const $ return ()))
where
handler parent e
| Just Ex.ThreadKilled <- castException e = return ()
| otherwise = throwTo parent e
forkFinallyXMPP :: XMPP.XMPP () -> (Either SomeException () -> IO ()) -> XMPP.XMPP ThreadId
forkFinallyXMPP kid handler = do
session <- XMPP.getSession
liftIO $ forkFinally (void $ XMPP.runXMPP session kid) handler
mkElement :: XML.Name -> Text -> XML.Element
mkElement name txt = XML.Element name [] [XML.NodeContent $ XML.ContentText txt]
nickname :: Text -> XML.Element
nickname nick = XML.Element (s"{http://jabber.org/protocol/nick}nick") [] [
XML.NodeContent $ XML.ContentText nick
]
addNickname :: Text -> XMPP.Message -> XMPP.Message
addNickname nick m@(XMPP.Message { XMPP.messagePayloads = p }) = m {
XMPP.messagePayloads = (nickname nick) : p
}
mapReceivedMessageM :: (Applicative f) =>
(XMPP.Message -> f XMPP.Message)
-> XMPP.ReceivedStanza
-> f XMPP.ReceivedStanza
mapReceivedMessageM f (XMPP.ReceivedMessage m) = XMPP.ReceivedMessage <$> f m
mapReceivedMessageM _ s = pure s
iqReply :: Maybe XML.Element -> XMPP.IQ -> XMPP.IQ
iqReply payload iq = iq {
XMPP.iqType = XMPP.IQResult,
XMPP.iqFrom = XMPP.iqTo iq,
XMPP.iqTo = XMPP.iqFrom iq,
XMPP.iqPayload = payload
}
queryCommandList' :: XMPP.JID -> XMPP.JID -> XMPP.IQ
queryCommandList' to from = (XMPP.emptyIQ XMPP.IQGet) {
XMPP.iqTo = Just to,
XMPP.iqFrom = Just from,
XMPP.iqPayload = Just $ XML.Element (s"{http://jabber.org/protocol/disco#items}query") [
(s"{http://jabber.org/protocol/disco#items}node", [XML.ContentText $ s"http://jabber.org/protocol/commands"])
] []
}
queryDiscoWithNode' :: Maybe Text -> XMPP.JID -> XMPP.JID -> XMPP.IQ
queryDiscoWithNode' node to from =
(XMPP.emptyIQ XMPP.IQGet) {
XMPP.iqTo = Just to,
XMPP.iqFrom = Just from,
XMPP.iqPayload = Just $ XML.Element
(s"{http://jabber.org/protocol/disco#info}query")
(map (\node -> (s"{http://jabber.org/protocol/disco#info}node", [XML.ContentText node])) $ maybeToList node)
[]
}
| singpolyma/cheogram | Util.hs | agpl-3.0 | 10,295 | 192 | 22 | 1,646 | 3,837 | 1,982 | 1,855 | 235 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Static.Service
( Static(..)
, initStatic
) where
import qualified Crypto.Hash.Algorithms as Hash
import Crypto.MAC.HMAC (HMAC, hmac)
import qualified Data.ByteString as BS
import Data.Maybe (fromMaybe)
import qualified Network.HTTP.Client as HC
import Network.HTTP.Types (methodPost, hContentType)
import qualified Store.Config as C
data Static = Static
{ staticAuthorizeAddr :: !BS.ByteString
, staticAssistAddr :: !BS.ByteString
, staticInvestigator :: !(Maybe HC.Request)
, staticKey :: !(BS.ByteString -> HMAC Hash.SHA256)
}
initStatic :: C.Config -> IO Static
initStatic conf = do
fillin <- mapM HC.parseRequest $ conf C.! "fillin"
return $ Static
{ staticAuthorizeAddr = conf C.! "authorize"
, staticAssistAddr = conf C.! "assist"
, staticInvestigator = fmap (\f -> f
{ HC.method = methodPost
, HC.requestHeaders = (hContentType, "application/x-www-form-urlencoded") : HC.requestHeaders f
, HC.cookieJar = Nothing
, HC.redirectCount = 0
}) fillin
, staticKey = hmac $ fromMaybe ("databrary" :: BS.ByteString) $ conf C.! "key"
}
| databrary/databrary | src/Static/Service.hs | agpl-3.0 | 1,150 | 0 | 17 | 218 | 330 | 193 | 137 | 37 | 1 |
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts #-}
module IntegrationTests
( integrationTests
) where
import GHC.Generics ( Generic, Generic1 )
import GHC.TypeLits ( KnownNat )
import Data.Proxy ( Proxy(..) )
import Data.Vector ( Vector )
import qualified Data.Vector as V
import qualified Data.Vector.Storable as SV
import qualified Numeric.GSL.ODE as ODE
import qualified Numeric.LinearAlgebra.Data as D
import qualified Test.HUnit.Base as HUnit
import Test.Framework ( Test, testGroup )
import Test.Framework.Providers.HUnit ( testCase )
import Linear ( Additive(..) )
import Dyno.Vectorize ( Vectorize(..), None(..), devectorize, vpure, vapply )
import Dyno.View.View ( View(..), J, splitJV )
import Dyno.Solvers
import Dyno.Nlp ( NlpOut(..) )
import Dyno.NlpUtils
import Dyno.Ocp
import Dyno.DirectCollocation.Formulate
import Dyno.DirectCollocation.Types ( CollTraj(..) )
import Dyno.DirectCollocation.Quadratures ( QuadratureRoots(..) )
data PendX a = PendX a a deriving (Functor, Generic, Generic1, Show)
data PendP a = PendP a deriving (Functor, Generic, Generic1, Show)
instance Vectorize PendX
instance Vectorize PendP
instance Applicative PendX where {pure = vpure; (<*>) = vapply}
instance Applicative PendP where {pure = vpure; (<*>) = vapply}
instance Additive PendX where
zero = pure 0
over :: Vectorize f => (a -> a -> a) -> f a -> f a -> f a
over f x y = devectorize $ V.zipWith f (vectorize x) (vectorize y)
minus :: (Vectorize f, Num a) => f a -> f a -> f a
minus = over (-)
--divv :: (Vectorize f, Fractional a) => f a -> f a -> f a
--divv = over (/)
data IntegrationOcp (x :: * -> *) (p :: * -> *)
type instance X (IntegrationOcp x p) = x
type instance Z (IntegrationOcp x p) = None
type instance U (IntegrationOcp x p) = None
type instance P (IntegrationOcp x p) = p
type instance R (IntegrationOcp x p) = x
type instance O (IntegrationOcp x p) = None
type instance C (IntegrationOcp x p) = x
type instance H (IntegrationOcp x p) = None
type instance Q (IntegrationOcp x p) = None
type instance QO (IntegrationOcp x p) = None
type instance FP (IntegrationOcp x p) = None
type instance PO (IntegrationOcp x p) = None
runIntegration ::
forall x p deg n
. ( Vectorize x, Vectorize p, KnownNat deg, KnownNat n )
=> Proxy n -> Proxy deg
-> DirCollOptions
-> (forall a . Floating a => x a -> p a -> a -> x a)
-> x Double -> p Double -> Double
-> IO (Either String (x Double))
runIntegration _ _ dirCollOpts ode x0 p tf = do
let ocp :: OcpPhase' (IntegrationOcp x p)
ocp =
OcpPhase
{ ocpMayer = \_ _ _ _ _ _ -> 0
, ocpLagrange = \_ _ _ _ _ _ _ _ -> 0
, ocpDae = \x' x _ _ pp _ t -> ((ode x pp t) `minus` x', None)
, ocpQuadratures = \_ _ _ _ _ _ _ _ -> None
, ocpQuadratureOutputs = \_ _ _ _ _ _ _ _ -> None
, ocpBc = \x0' _ _ _ _ _ -> x0'
, ocpPathC = \_ _ _ _ _ _ _ -> None
, ocpPlotOutputs = \_ _ _ _ _ _ _ _ _ _ _ -> None
, ocpObjScale = Nothing
, ocpTScale = Nothing
, ocpXScale = Nothing
, ocpZScale = Nothing
, ocpUScale = Nothing
, ocpPScale = Nothing
, ocpResidualScale = Nothing
, ocpBcScale = Nothing
, ocpPathCScale = Nothing
}
ocpInputs :: OcpPhaseInputs' (IntegrationOcp x p)
ocpInputs =
OcpPhaseInputs
{ ocpPathCBnds = None
, ocpBcBnds = fmap (\x -> (Just x, Just x)) x0
, ocpXbnd = pure (Nothing, Nothing)
, ocpUbnd = None
, ocpZbnd = None
, ocpPbnd = fmap (\x -> (Just x, Just x)) p
, ocpTbnd = (Just tf, Just tf)
, ocpFixedP = None
}
let guess :: J (CollTraj x None None p n deg) (Vector Double)
guess = cat $ makeGuessSim (collocationRoots dirCollOpts) tf x0 (\_ x _ -> ode x p 0) (\_ _ -> None) p
cp <- makeCollProblem dirCollOpts ocp ocpInputs guess :: IO (CollProblem x None None p x None x None None None None None n deg)
(_, eopt) <- solveNlp "test_ocp_integrator" solver (cpNlp cp) Nothing
return $ case eopt of
Left m -> Left m
Right opt -> Right (toXf (xOpt opt))
pendOde :: Floating a => PendX a -> PendP a -> a -> PendX a
pendOde (PendX theta omega) (PendP mass) t = PendX omega ((9.8 * sin theta + force) / mass)
where
force = 0.3 * sin t
solver :: Solver
solver = ipoptSolver { options = [ ("expand", GBool True)
--, ("ipopt.linear_solver", GString "ma86")
--, ("ipopt.ma86_order", GString "metis")
, ("ipopt.tol", GDouble 1e-11)
] }
pendX0 :: PendX Double
pendX0 = PendX 0 0.2
pendP :: PendP Double
pendP = PendP 2.3
rk45 :: Vectorize x
=> (x Double -> p Double -> Double -> x Double)
-> Double -> p Double -> x Double -> x Double
rk45 f h p x0 = devectorize $ sv $ last sol
where
vs :: V.Vector Double -> SV.Vector Double
vs = SV.fromList . V.toList
sv :: SV.Vector Double -> V.Vector Double
sv = V.fromList . SV.toList
sol = D.toRows $
ODE.odeSolveV
ODE.RKf45
h 1e-10 1e-8 f'
(vs (vectorize x0))
(SV.fromList [0.0, h])
f' :: Double -> SV.Vector Double -> SV.Vector Double
f' t x = vs $ vectorize $ f (devectorize (sv x)) p t
toXf :: ( Vectorize x, Vectorize z, Vectorize u, Vectorize p
, KnownNat n, KnownNat deg
) => J (CollTraj x z u p n deg) (Vector Double)-> x Double
toXf traj = splitJV xf
where
CollTraj _ _ _ xf = split traj
integrationTests :: Test
integrationTests =
testGroup "integration tests"
[ testGroup (show roots)
[ testGroup (show mapStrat)
[ testGroup ("unroll in haskell: " ++ show unrollInHaskell)
[ testCase "pendulum" $ compareIntegration (Proxy :: Proxy 80) (Proxy :: Proxy 3) dirCollOpts pendOde pendX0 pendP tf
]
| unrollInHaskell <- [True, False]
, let dirCollOpts =
def
{ mapStrategy = mapStrat
, collocationRoots = roots
, unrollMapInHaskell = unrollInHaskell
}
]
| mapStrat <- [Unroll, Serial, OpenMP]
]
| roots <- [Radau, Legendre]
]
where
tf = 3.0
compareIntegration ::
forall x p n deg
. (Vectorize x, Vectorize p, KnownNat n, KnownNat deg)
=> Proxy n -> Proxy deg
-> DirCollOptions
-> (forall a . Floating a => x a -> p a -> a -> x a)
-> x Double -> p Double -> Double -> HUnit.Assertion
compareIntegration pn pdeg dirCollOpts ode x0 p tf = HUnit.assert $ do
x' <- runIntegration pn pdeg dirCollOpts ode x0 p tf
let xGsl = rk45 ode tf p x0
ret :: HUnit.Assertion
ret = case x' of
Left err -> HUnit.assertString $ "failed with: " ++ show err
Right x
| worstErr <= 1e-6 -> HUnit.assert True
| otherwise -> HUnit.assertString $ "insufficient accuracy: " ++ show worstErr
where
worstErr :: Double
worstErr = V.maximum $ V.map abs $ vectorize $ x `minus` xGsl
return ret :: IO HUnit.Assertion
| ghorn/dynobud | dynobud/tests/IntegrationTests.hs | lgpl-3.0 | 7,379 | 0 | 21 | 2,083 | 2,642 | 1,424 | 1,218 | -1 | -1 |
module Network.Haskoin.Wallet.Transaction
(
-- *Database transactions
txPage
, addrTxPage
, getTx
, getAccountTx
, importTx
, importNetTx
, signKeyRingTx
, createTx
, signOfflineTx
, getOfflineTxData
, killTxs
, reviveTx
, getPendingTxs
-- *Database blocks
, importMerkles
, getBestBlock
-- *Database coins and balances
, spendableCoins
, spendableCoinsSource
, accountBalance
, addressBalances
-- *Rescan
, resetRescan
-- *Helpers
, splitSelect
, splitUpdate
, splitDelete
, join2
, InCoinData(..)
) where
import Control.Arrow (second)
import Control.Monad (forM, forM_, when, liftM, unless)
import Control.Monad.Trans (MonadIO, liftIO)
import Control.Monad.Base (MonadBase)
import Control.Monad.Catch (MonadThrow)
import Control.Monad.Trans.Resource (MonadResource)
import Control.Exception (throwIO, throw)
import Data.Time (UTCTime, getCurrentTime)
import Data.Word (Word32, Word64)
import Data.Either (rights)
import Data.List ((\\), nub, nubBy, find)
import Data.List.Split (chunksOf)
import Data.Text (unpack)
import Data.Conduit (Source, mapOutput, ($$))
import Data.Maybe (isNothing, isJust, fromMaybe, listToMaybe)
import qualified Data.Map.Strict as M
( Map, toList, map, unionWith, fromListWith )
import Data.String.Conversions (cs)
import qualified Database.Persist as P
( Filter
, selectFirst
, deleteWhere, insertBy, insertMany_, PersistEntity
, PersistEntityBackend
)
import Database.Esqueleto
( Value(..), SqlQuery, SqlExpr, SqlBackend
, InnerJoin(..), LeftOuterJoin(..), OrderBy, update, sum_, groupBy
, select, from, where_, val, valList, sub_select, countRows, count
, orderBy, limit, asc, desc, set, offset, selectSource
, in_, unValue, not_, coalesceDefault, just, on
, case_, when_, then_, else_, distinct
, (^.), (=.), (==.), (&&.), (||.), (<.)
, (<=.), (>=.), (-.), (?.), (!=.)
-- Reexports from Database.Persist
, SqlPersistT, Entity(..)
, getBy, replace
)
import qualified Database.Esqueleto as E (isNothing, delete)
import Database.Esqueleto.Internal.Sql (SqlSelect)
import Network.Haskoin.Block
import Network.Haskoin.Transaction
import Network.Haskoin.Script
import Network.Haskoin.Crypto
import Network.Haskoin.Util
import Network.Haskoin.Constants
import Network.Haskoin.Node.STM
import Network.Haskoin.Node.HeaderTree
import Network.Haskoin.Wallet.KeyRing
import Network.Haskoin.Wallet.Model
import Network.Haskoin.Wallet.Types
import Network.Haskoin.Wallet.Database
-- Input coin type with transaction and address information
data InCoinData = InCoinData
{ inCoinDataCoin :: !(Entity KeyRingCoin)
, inCoinDataTx :: !KeyRingTx
, inCoinDataAddr :: !KeyRingAddr
}
instance Coin InCoinData where
coinValue (InCoinData (Entity _ c) _ _) = keyRingCoinValue c
-- Output coin type with address information
data OutCoinData = OutCoinData
{ outCoinDataAddr :: !(Entity KeyRingAddr)
, outCoinDataPos :: !KeyIndex
, outCoinDataValue :: !Word64
, outCoinDataScript :: !ScriptOutput
}
{- List transaction -}
-- | Get transactions by page
txPage :: MonadIO m
=> KeyRingAccountId -- ^ Account ID
-> PageRequest -- ^ Page request
-> SqlPersistT m ([KeyRingTx], Word32)
-- ^ Page result
txPage ai page@PageRequest{..}
| validPageRequest page = do
cntRes <- select $ from $ \t -> do
where_ $ t ^. KeyRingTxAccount ==. val ai
return countRows
let cnt = maybe 0 unValue $ listToMaybe cntRes
(d, m) = cnt `divMod` pageLen
maxPage = max 1 $ d + min 1 m
when (pageNum > maxPage) $ liftIO . throwIO $ WalletException $
unwords [ "Invalid page number", show pageNum ]
res <- liftM (map entityVal) $ select $ from $ \t -> do
where_ $ t ^. KeyRingTxAccount ==. val ai
let order = if pageReverse then asc else desc
orderBy [ order (t ^. KeyRingTxId) ]
limit $ fromIntegral pageLen
offset $ fromIntegral $ (pageNum - 1) * pageLen
return t
let f = if pageReverse then id else reverse
return (f res, maxPage)
| otherwise = liftIO . throwIO $ WalletException $
concat [ "Invalid page request"
, " (Page: ", show pageNum, ", Page size: ", show pageLen, ")"
]
addrTxPage :: MonadIO m
=> Entity KeyRingAccount -- ^ Account entity
-> KeyRingAddrId -- ^ Address Id
-> PageRequest -- ^ Page request
-> SqlPersistT m ([(KeyRingTx, BalanceInfo)], Word32)
addrTxPage (Entity ai _) addrI page@PageRequest{..}
| validPageRequest page = do
let joinSpentCoin c2 s =
c2 ?. KeyRingCoinAccount ==. s ?. KeyRingSpentCoinAccount
&&. c2 ?. KeyRingCoinHash ==. s ?. KeyRingSpentCoinHash
&&. c2 ?. KeyRingCoinPos ==. s ?. KeyRingSpentCoinPos
&&. c2 ?. KeyRingCoinAddr ==. just (val addrI)
joinSpent s t =
s ?. KeyRingSpentCoinSpendingTx ==. just (t ^. KeyRingTxId)
joinCoin c t =
c ?. KeyRingCoinTx ==. just (t ^. KeyRingTxId)
&&. c ?. KeyRingCoinAddr ==. just (val addrI)
joinAll t c c2 s = do
on $ joinSpentCoin c2 s
on $ joinSpent s t
on $ joinCoin c t
-- Find all the tids
tids <- liftM (map unValue) $ select $ distinct $ from $
\(t `LeftOuterJoin` c `LeftOuterJoin`
s `LeftOuterJoin` c2) -> do
joinAll t c c2 s
where_ ( t ^. KeyRingTxAccount ==. val ai
&&. ( not_ (E.isNothing (c ?. KeyRingCoinId))
||. not_ (E.isNothing (c2 ?. KeyRingCoinId))
)
)
orderBy [ asc (t ^. KeyRingTxId) ]
return $ t ^. KeyRingTxId
let cnt = fromIntegral $ length tids
(d, m) = cnt `divMod` pageLen
maxPage = max 1 $ d + min 1 m
when (pageNum > maxPage) $ liftIO . throwIO $ WalletException $
unwords [ "Invalid page number", show pageNum ]
let fOrd = if pageReverse then reverse else id
toDrop = fromIntegral $ (pageNum - 1) * pageLen
-- We call fOrd twice to reverse the page back to ASC
tidPage =
fOrd $ take (fromIntegral pageLen) $ drop toDrop $ fOrd tids
-- Use a sliptSelect query here with the exact tids to speed up the
-- query.
res <- splitSelect tidPage $ \tid ->
from $ \(t `LeftOuterJoin` c `LeftOuterJoin`
s `LeftOuterJoin` c2) -> do
joinAll t c c2 s
where_ $ t ^. KeyRingTxId `in_` valList tid
groupBy $ t ^. KeyRingTxId
orderBy [ asc (t ^. KeyRingTxId) ]
return ( t
-- Incoming value
, coalesceDefault [sum_ (c ?. KeyRingCoinValue)] (val 0)
-- Outgoing value
, coalesceDefault [sum_ (c2 ?. KeyRingCoinValue)] (val 0)
-- Number of new coins created
, count $ c ?. KeyRingCoinId
-- Number of coins spent
, count $ c2 ?. KeyRingCoinId
)
let f (t, Value inVal, Value outVal, Value newCount, Value spentCount) =
( entityVal t
, BalanceInfo
{ balanceInfoInBalance = floor (inVal :: Double)
, balanceInfoOutBalance = floor (outVal :: Double)
, balanceInfoCoins = newCount
, balanceInfoSpentCoins = spentCount
}
)
return (map f res, maxPage)
| otherwise = liftIO . throwIO $ WalletException $
concat [ "Invalid page request"
, " (Page: ", show pageNum, ", Page size: ", show pageLen, ")"
]
-- Helper function to get a transaction from the wallet database. The function
-- will look across all accounts and return the first available transaction. If
-- the transaction does not exist, this function will throw a wallet exception.
getTx :: MonadIO m => TxHash -> SqlPersistT m (Maybe Tx)
getTx txid = do
res <- select $ from $ \t -> do
where_ $ t ^. KeyRingTxHash ==. val txid
limit 1
return $ t ^. KeyRingTxTx
case res of
(Value tx:_) -> return $ Just tx
_ -> return Nothing
getAccountTx :: MonadIO m
=> KeyRingAccountId -> TxHash -> SqlPersistT m KeyRingTx
getAccountTx ai txid = do
res <- select $ from $ \t -> do
where_ ( t ^. KeyRingTxAccount ==. val ai
&&. t ^. KeyRingTxHash ==. val txid
)
return t
case res of
(Entity _ tx:_) -> return tx
_ -> liftIO . throwIO $ WalletException $ unwords
[ "Transaction does not exist:", cs $ txHashToHex txid ]
-- Helper function to get all the pending transactions from the database. It is
-- used to re-broadcast pending transactions in the wallet that have not been
-- included into blocks yet.
getPendingTxs :: MonadIO m => Int -> SqlPersistT m [TxHash]
getPendingTxs i =
liftM (map unValue) $ select $ from $ \t -> do
where_ $ t ^. KeyRingTxConfidence ==. val TxPending
limit $ fromIntegral i
return $ t ^. KeyRingTxHash
{- Transaction Import -}
-- | Import a transaction into the wallet from an unknown source. If the
-- transaction is standard, valid, all inputs are known and all inputs can be
-- spent, then the transaction will be imported as a network transaction.
-- Otherwise, the transaction will be imported into the local account as an
-- offline transaction.
importTx :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m)
=> Tx -- ^ Transaction to import
-> KeyRingAccountId -- ^ Account ID
-> SqlPersistT m ([KeyRingTx], [KeyRingAddr])
-- ^ New transactions and addresses created
importTx tx ai = importTx' tx ai =<< getInCoins tx (Just ai)
importTx' :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m)
=> Tx -- ^ Transaction to import
-> KeyRingAccountId -- ^ Account ID
-> [InCoinData] -- ^ Input coins
-> SqlPersistT m ([KeyRingTx], [KeyRingAddr])
-- ^ Transaction hash (after possible merges)
importTx' origTx ai origInCoins = do
-- Merge the transaction with any previously existing transactions
mergeResM <- mergeNoSigHashTxs ai origTx origInCoins
let tx = fromMaybe origTx mergeResM
origTxid = txHash origTx
txid = txHash tx
-- If the transaction was merged into a new transaction,
-- update the old hashes to the new ones. This allows us to
-- keep the spending information of our coins. It is thus possible
-- to spend partially signed multisignature transactions (as offline
-- transactions) even before all signatures have arrived.
inCoins <- if origTxid == txid then return origInCoins else do
-- Update transactions
update $ \t -> do
set t [ KeyRingTxHash =. val txid
, KeyRingTxTx =. val tx
]
where_ ( t ^. KeyRingTxAccount ==. val ai
&&. t ^. KeyRingTxHash ==. val origTxid
)
-- Update coins
update $ \t -> do
set t [ KeyRingCoinHash =. val txid ]
where_ ( t ^. KeyRingCoinAccount ==. val ai
&&. t ^. KeyRingCoinHash ==. val origTxid
)
let f (InCoinData c t x) = if keyRingTxHash t == origTxid
then InCoinData c t{ keyRingTxHash = txid, keyRingTxTx = tx } x
else InCoinData c t x
return $ map f origInCoins
spendingTxs <- getSpendingTxs tx (Just ai)
let validTx = verifyStdTx tx $ map toVerDat inCoins
validIn = length inCoins == length (txIn tx)
&& canSpendCoins inCoins spendingTxs False
if validIn && validTx
then importNetTx tx
else importOfflineTx tx ai inCoins spendingTxs
where
toVerDat (InCoinData (Entity _ c) t _) =
(keyRingCoinScript c, OutPoint (keyRingTxHash t) (keyRingCoinPos c))
-- Offline transactions are usually multisignature transactions requiring
-- additional signatures. This function will merge the signatures of
-- the same offline transactions together into one single transaction.
mergeNoSigHashTxs :: MonadIO m
=> KeyRingAccountId
-> Tx
-> [InCoinData]
-> SqlPersistT m (Maybe Tx)
mergeNoSigHashTxs ai tx inCoins = do
prevM <- getBy $ UniqueAccNoSig ai $ nosigTxHash tx
return $ case prevM of
Just (Entity _ prev) -> case keyRingTxConfidence prev of
TxOffline -> eitherToMaybe $
mergeTxs [tx, keyRingTxTx prev] outPoints
_ -> Nothing
-- Nothing to merge. Return the original transaction.
_ -> Nothing
where
buildOutpoint c t = OutPoint (keyRingTxHash t) (keyRingCoinPos c)
f (InCoinData (Entity _ c) t _) = (keyRingCoinScript c, buildOutpoint c t)
outPoints = map f inCoins
-- | Import an offline transaction into a specific account. Offline transactions
-- are imported either manually or from the wallet when building a partially
-- signed multisignature transaction. Offline transactions are only imported
-- into one specific account. They will not affect the input or output coins
-- of other accounts, including read-only accounts that may watch the same
-- addresses as this account.
--
-- We allow transactions to be imported manually by this function (unlike
-- `importNetTx` which imports only transactions coming from the network). This
-- means that it is possible to import completely crafted and invalid
-- transactions into the wallet. It is thus important to limit the scope of
-- those transactions to only the specific account in which it was imported.
--
-- This function will not broadcast these transactions to the network as we
-- have no idea if they are valid or not. Transactions are broadcast from the
-- transaction creation function and only if the transaction is complete.
importOfflineTx
:: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m)
=> Tx
-> KeyRingAccountId
-> [InCoinData]
-> [Entity KeyRingTx]
-> SqlPersistT m ([KeyRingTx], [KeyRingAddr])
importOfflineTx tx ai inCoins spendingTxs = do
-- Get all the new coins to be created by this transaction
outCoins <- getNewCoins tx $ Just ai
-- Only continue if the transaction is relevant to the account
when (null inCoins && null outCoins) err
-- Find the details of an existing transaction if it exists.
prevM <- liftM (fmap entityVal) $ getBy $ UniqueAccTx ai txid
-- Check if we can import the transaction
unless (canImport $ keyRingTxConfidence <$> prevM) err
-- Kill transactions that are spending our coins
killTxIds $ map entityKey spendingTxs
-- Create all the transaction records for this account.
-- This will spend the input coins and create the output coins
txsRes <- buildAccTxs tx TxOffline inCoins outCoins
-- use the addresses (refill the gap addresses)
newAddrs <- forM (nubBy sameKey $ map outCoinDataAddr outCoins) $
useAddress . entityVal
return (txsRes, concat newAddrs)
where
txid = txHash tx
canImport prevConfM =
-- We can only re-import offline txs through this function.
(isNothing prevConfM || prevConfM == Just TxOffline) &&
-- Check that all coins can be spent. We allow offline
-- coins to be spent by this function unlike importNetTx.
canSpendCoins inCoins spendingTxs True
sameKey e1 e2 = entityKey e1 == entityKey e2
err = liftIO . throwIO $ WalletException
"Could not import offline transaction"
-- | Import a transaction from the network into the wallet. This function
-- assumes transactions are imported in-order (parents first). It also assumes
-- that the confirmations always arrive after the transaction imports. This
-- function is idempotent.
--
-- When re-importing an existing transaction, this function will recompute
-- the inputs, outputs and transaction details for each account. A non-dead
-- transaction could be set to dead due to new inputs being double spent.
-- However, we do not allow dead transactions to be revived by reimporting them.
-- Transactions can only be revived if they make it into the main chain.
--
-- This function returns the network confidence of the imported transaction.
importNetTx
:: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m)
=> Tx -- Network transaction to import
-> SqlPersistT m ([KeyRingTx], [KeyRingAddr])
-- ^ Returns the new transactions and addresses created
importNetTx tx = do
-- Find all the coins spent by this transaction
inCoins <- getInCoins tx Nothing
-- Get all the new coins to be created by this transaction
outCoins <- getNewCoins tx Nothing
-- Only continue if the transaction is relevant to the wallet
if null inCoins && null outCoins then return ([],[]) else do
-- Update incomplete offline transactions when the completed
-- transaction comes in from the network.
updateNosigHash tx (nosigTxHash tx) txid
-- Get the transaction spending our coins
spendingTxs <- getSpendingTxs tx Nothing
-- Compute the confidence
let confidence | canSpendCoins inCoins spendingTxs False = TxPending
| otherwise = TxDead
-- Kill transactions that are spending our coins if we are not dead
when (confidence /= TxDead) $ killTxIds $ map entityKey spendingTxs
-- Create all the transaction records for this account.
-- This will spend the input coins and create the output coins
txRes <- buildAccTxs tx confidence inCoins outCoins
-- Use up the addresses of our new coins (replenish gap addresses)
newAddrs <- forM (nubBy sameKey $ map outCoinDataAddr outCoins) $
useAddress . entityVal
return (txRes, concat newAddrs)
where
sameKey e1 e2 = entityKey e1 == entityKey e2
txid = txHash tx
updateNosigHash :: MonadIO m => Tx -> TxHash -> TxHash -> SqlPersistT m ()
updateNosigHash tx nosig txid = do
res <- select $ from $ \t -> do
where_ ( t ^. KeyRingTxNosigHash ==. val nosig
&&. t ^. KeyRingTxHash !=. val txid
)
return $ t ^. KeyRingTxHash
let toUpdate = map unValue res
unless (null toUpdate) $ do
splitUpdate toUpdate $ \hs t -> do
set t [ KeyRingTxHash =. val txid
, KeyRingTxTx =. val tx
]
where_ $ t ^. KeyRingTxHash `in_` valList hs
splitUpdate toUpdate $ \hs c -> do
set c [ KeyRingCoinHash =. val txid ]
where_ $ c ^. KeyRingCoinHash `in_` valList hs
-- Check if the given coins can be spent.
canSpendCoins :: [InCoinData]
-> [Entity KeyRingTx]
-> Bool -- True for offline transactions
-> Bool
canSpendCoins inCoins spendingTxs offline =
all validCoin inCoins &&
all validSpend spendingTxs
where
-- We can only spend pending and building coins
validCoin (InCoinData _ t _)
| offline = keyRingTxConfidence t /= TxDead
| otherwise = keyRingTxConfidence t `elem` [TxPending, TxBuilding]
-- All transactions spending the same coins as us should be offline
validSpend = (== TxOffline) . keyRingTxConfidence . entityVal
-- Get the coins in the wallet related to the inputs of a transaction. You
-- can optionally provide an account to limit the returned coins to that
-- account only.
getInCoins :: MonadIO m
=> Tx
-> Maybe KeyRingAccountId
-> SqlPersistT m [InCoinData]
getInCoins tx aiM = do
res <- splitSelect ops $ \os -> from $ \(c `InnerJoin` t `InnerJoin` x) -> do
on $ x ^. KeyRingAddrId ==. c ^. KeyRingCoinAddr
on $ t ^. KeyRingTxId ==. c ^. KeyRingCoinTx
where_ $ case aiM of
Just ai ->
c ^. KeyRingCoinAccount ==. val ai &&. limitOutPoints c os
_ -> limitOutPoints c os
return (c, t, x)
return $ map (\(c, t, x) -> InCoinData c (entityVal t) (entityVal x)) res
where
ops = map prevOutput $ txIn tx
limitOutPoints c os = join2 $ map (f c) os
f c (OutPoint h i) =
c ^. KeyRingCoinHash ==. val h &&.
c ^. KeyRingCoinPos ==. val i
-- Find all the transactions that are spending the same coins as the given
-- transaction. You can optionally provide an account to limit the returned
-- transactions to that account only.
getSpendingTxs :: MonadIO m
=> Tx
-> Maybe KeyRingAccountId
-> SqlPersistT m [Entity KeyRingTx]
getSpendingTxs tx aiM
| null txInputs = return []
| otherwise =
splitSelect txInputs $ \ins -> from $ \(s `InnerJoin` t) -> do
on $ s ^. KeyRingSpentCoinSpendingTx ==. t ^. KeyRingTxId
-- Filter out the given transaction
let cond = t ^. KeyRingTxHash !=. val txid
-- Limit to only the input coins of the given tx
&&. limitSpent s ins
where_ $ case aiM of
Just ai -> cond &&. s ^. KeyRingSpentCoinAccount ==. val ai
_ -> cond
return t
where
txid = txHash tx
txInputs = map prevOutput $ txIn tx
limitSpent s ins = join2 $ map (f s) ins
f s (OutPoint h i) =
s ^. KeyRingSpentCoinHash ==. val h &&.
s ^. KeyRingSpentCoinPos ==. val i
-- Returns all the new coins that need to be created from a transaction.
-- Also returns the addresses associted with those coins.
getNewCoins :: MonadIO m
=> Tx
-> Maybe KeyRingAccountId
-> SqlPersistT m [OutCoinData]
getNewCoins tx aiM = do
-- Find all the addresses which are in the transaction outputs
addrs <- splitSelect uniqueAddrs $ \as -> from $ \x -> do
let cond = x ^. KeyRingAddrAddress `in_` valList as
where_ $ case aiM of
Just ai -> cond &&. x ^. KeyRingAddrAccount ==. val ai
_ -> cond
return x
return $ concatMap toCoins addrs
where
uniqueAddrs = nub $ map (\(addr,_,_,_) -> addr) outList
outList = rights $ map toDat txOutputs
txOutputs = zip (txOut tx) [0..]
toDat (out, pos) = getDataFromOutput out >>= \(addr, so) ->
return (addr, out, pos, so)
toCoins addrEnt@(Entity _ addr) =
let f (a,_,_,_) = a == keyRingAddrAddress addr
in map (toCoin addrEnt) $ filter f outList
toCoin addrEnt (_, out, pos, so) = OutCoinData
{ outCoinDataAddr = addrEnt
, outCoinDataPos = pos
, outCoinDataValue = outValue out
, outCoinDataScript = so
}
-- Decode an output and extract an output script and a recipient address
getDataFromOutput :: TxOut -> Either String (Address, ScriptOutput)
getDataFromOutput out = do
so <- decodeOutputBS $ scriptOutput out
addr <- scriptRecipient $ encodeOutput so
return (addr, so)
isCoinbaseTx :: Tx -> Bool
isCoinbaseTx (Tx _ tin _ _) =
length tin == 1 && outPointHash (prevOutput $ head tin) ==
"0000000000000000000000000000000000000000000000000000000000000000"
-- | Spend the given input coins. We also create dummy coins for the inputs
-- in a transaction that do not belong to us. This is to be able to detect
-- double spends when reorgs occur.
spendInputs :: MonadIO m
=> KeyRingAccountId
-> KeyRingTxId
-> Tx
-> SqlPersistT m ()
spendInputs ai ti tx = do
now <- liftIO getCurrentTime
-- Spend the coins by inserting values in KeyRingSpentCoin
P.insertMany_ $ map (buildSpentCoin now) txInputs
where
txInputs = map prevOutput $ txIn tx
buildSpentCoin now (OutPoint h p) =
KeyRingSpentCoin{ keyRingSpentCoinAccount = ai
, keyRingSpentCoinHash = h
, keyRingSpentCoinPos = p
, keyRingSpentCoinSpendingTx = ti
, keyRingSpentCoinCreated = now
}
-- Build account transaction for the given input and output coins
buildAccTxs :: MonadIO m
=> Tx
-> TxConfidence
-> [InCoinData]
-> [OutCoinData]
-> SqlPersistT m [KeyRingTx]
buildAccTxs tx confidence inCoins outCoins = do
now <- liftIO getCurrentTime
-- Group the coins by account
let grouped = groupCoinsByAccount inCoins outCoins
forM (M.toList grouped) $ \(ai, (is, os)) -> do
let atx = buildAccTx tx confidence ai is os now
-- Insert the new transaction. If it already exists, update the
-- information with the newly computed values. Also make sure that the
-- confidence is set to the new value (it could have changed to TxDead).
Entity ti newAtx <- P.insertBy atx >>= \resE -> case resE of
Left (Entity ti prev) -> do
let prevConf = keyRingTxConfidence prev
newConf | confidence == TxDead = TxDead
| prevConf == TxBuilding = TxBuilding
| otherwise = confidence
-- If the transaction already exists, preserve confirmation data
let newAtx = atx
{ keyRingTxConfidence = newConf
, keyRingTxConfirmedBy = keyRingTxConfirmedBy prev
, keyRingTxConfirmedHeight = keyRingTxConfirmedHeight prev
, keyRingTxConfirmedDate = keyRingTxConfirmedDate prev
}
replace ti newAtx
-- Spend inputs only if the previous transaction was dead
when (newConf /= TxDead && prevConf == TxDead) $
spendInputs ai ti tx
-- If the transaction changed from non-dead to dead, kill it.
-- This will remove spent coins and child transactions.
when (prevConf /= TxDead && newConf == TxDead) $ killTxIds [ti]
return (Entity ti newAtx)
Right ti -> do
when (confidence /= TxDead) $ spendInputs ai ti tx
return (Entity ti atx)
-- Insert the output coins with updated accTx key
let newOs = map (toCoin ai ti now) os
forM_ newOs $ \c -> P.insertBy c >>= \resE -> case resE of
Left (Entity ci _) -> replace ci c
_ -> return ()
-- Return the new transaction record
return newAtx
where
toCoin ai accTxId now (OutCoinData addrEnt pos vl so) = KeyRingCoin
{ keyRingCoinAccount = ai
, keyRingCoinHash = txHash tx
, keyRingCoinPos = pos
, keyRingCoinTx = accTxId
, keyRingCoinValue = vl
, keyRingCoinScript = so
, keyRingCoinAddr = entityKey addrEnt
, keyRingCoinCreated = now
}
-- | Build an account transaction given the input and output coins relevant to
-- this specific account. An account transaction contains the details of how a
-- transaction affects one particular account (value sent to and from the
-- account). The first value is Maybe an existing transaction in the database
-- which is used to get the existing confirmation values.
buildAccTx :: Tx
-> TxConfidence
-> KeyRingAccountId
-> [InCoinData]
-> [OutCoinData]
-> UTCTime
-> KeyRingTx
buildAccTx tx confidence ai inCoins outCoins now = KeyRingTx
{ keyRingTxAccount = ai
, keyRingTxHash = txHash tx
-- This is a hash of the transaction excluding signatures. This allows us
-- to track the evolution of offline transactions as we add more signatures
-- to them.
, keyRingTxNosigHash = nosigTxHash tx
, keyRingTxType = txType
, keyRingTxInValue = inVal
, keyRingTxOutValue = outVal
, keyRingTxInputs =
let f h i (InCoinData (Entity _ c) t _) =
keyRingTxHash t == h && keyRingCoinPos c == i
toInfo (a, OutPoint h i) = case find (f h i) inCoins of
Just (InCoinData (Entity _ c) _ _) ->
AddressInfo a (Just $ keyRingCoinValue c) True
_ -> AddressInfo a Nothing False
in map toInfo allInAddrs
, keyRingTxOutputs =
let toInfo (a,i,v) = AddressInfo a (Just v) $ ours i
ours i = isJust $ find ((== i) . outCoinDataPos) outCoins
in map toInfo allOutAddrs \\ changeAddrs
, keyRingTxChange = changeAddrs
, keyRingTxTx = tx
, keyRingTxIsCoinbase = isCoinbaseTx tx
, keyRingTxConfidence = confidence
-- Reuse the confirmation information of the existing transaction if
-- we have it.
, keyRingTxConfirmedBy = Nothing
, keyRingTxConfirmedHeight = Nothing
, keyRingTxConfirmedDate = Nothing
, keyRingTxCreated = now
}
where
-- The value going into the account is the sum of the output coins
inVal = sum $ map outCoinDataValue outCoins
-- The value going out of the account is the sum on the input coins
outVal = sum $ map coinValue inCoins
allMyCoins = length inCoins == length (txIn tx) &&
length outCoins == length (txOut tx)
txType
-- If all the coins belong to the same account, it is a self
-- transaction (even if a fee was payed).
| allMyCoins = TxSelf
-- This case can happen in complex transactions where the total
-- input/output sum for a given account is 0. In this case, we count
-- that transaction as a TxSelf. This should not happen with simple
-- transactions.
| inVal == outVal = TxSelf
| inVal > outVal = TxIncoming
| otherwise = TxOutgoing
-- List of all the decodable input addresses in the transaction
allInAddrs =
let f inp = do
addr <- scriptSender =<< decodeToEither (scriptInput inp)
return (addr, prevOutput inp)
in rights $ map f $ txIn tx
-- List of all the decodable output addresses in the transaction
allOutAddrs =
let f op i = do
addr <- scriptRecipient =<< decodeToEither (scriptOutput op)
return (addr, i, outValue op)
in rights $ zipWith f (txOut tx) [0..]
changeAddrs
| txType == TxIncoming = []
| otherwise =
let isInternal = (== AddressInternal) . keyRingAddrType
. entityVal . outCoinDataAddr
f = keyRingAddrAddress . entityVal . outCoinDataAddr
toInfo c = AddressInfo (f c) (Just $ outCoinDataValue c) True
in map toInfo $ filter isInternal outCoins
-- Group all the input and outputs coins from the same account together.
groupCoinsByAccount
:: [InCoinData]
-> [OutCoinData]
-> M.Map KeyRingAccountId ([InCoinData], [OutCoinData])
groupCoinsByAccount inCoins outCoins =
M.unionWith merge inMap outMap
where
-- Build a map from accounts -> (inCoins, outCoins)
f coin@(InCoinData _ t _) = (keyRingTxAccount t, [coin])
g coin = (keyRingAddrAccount $ entityVal $ outCoinDataAddr coin, [coin])
merge (is, _) (_, os) = (is, os)
inMap = M.map (\is -> (is, [])) $ M.fromListWith (++) $ map f inCoins
outMap = M.map (\os -> ([], os)) $ M.fromListWith (++) $ map g outCoins
-- Kill transactions and their child transactions by ids.
killTxIds :: MonadIO m => [KeyRingTxId] -> SqlPersistT m ()
killTxIds txIds = do
-- Find all the transactions spending the coins of these transactions
-- (Find all the child transactions)
childs <- splitSelect txIds $ \ts -> from $ \(t `InnerJoin` s) -> do
on ( s ^. KeyRingSpentCoinAccount ==. t ^. KeyRingTxAccount
&&. s ^. KeyRingSpentCoinHash ==. t ^. KeyRingTxHash
)
where_ $ t ^. KeyRingTxId `in_` valList ts
return $ s ^. KeyRingSpentCoinSpendingTx
-- Kill these transactions
splitUpdate txIds $ \ts t -> do
set t [ KeyRingTxConfidence =. val TxDead ]
where_ $ t ^. KeyRingTxId `in_` valList ts
-- This transaction doesn't spend any coins
splitDelete txIds $ \ts -> from $ \s ->
where_ $ s ^. KeyRingSpentCoinSpendingTx `in_` valList ts
-- Recursively kill all the child transactions.
-- (Recurse at the end in case there are closed loops)
unless (null childs) $ killTxIds $ nub $ map unValue childs
-- Kill transactions and their child transactions by hashes.
killTxs :: MonadIO m => [TxHash] -> SqlPersistT m ()
killTxs txHashes = do
res <- splitSelect txHashes $ \hs -> from $ \t -> do
where_ $ t ^. KeyRingTxHash `in_` valList hs
return $ t ^. KeyRingTxId
killTxIds $ map unValue res
{- Confirmations -}
importMerkles :: MonadIO m
=> BlockChainAction
-> [MerkleTxs]
-> SqlPersistT m ()
importMerkles action expTxsLs =
when (isBestChain action || isChainReorg action) $ do
case action of
ChainReorg _ os _ ->
-- Unconfirm transactions from the old chain.
let hs = map (Just . nodeBlockHash) os
in splitUpdate hs $ \h t -> do
set t [ KeyRingTxConfidence =. val TxPending
, KeyRingTxConfirmedBy =. val Nothing
, KeyRingTxConfirmedHeight =. val Nothing
, KeyRingTxConfirmedDate =. val Nothing
]
where_ $ t ^. KeyRingTxConfirmedBy `in_` valList h
_ -> return ()
-- Find all the dead transactions which need to be revived
deadTxs <- splitSelect (concat expTxsLs) $ \ts -> from $ \t -> do
where_ ( t ^. KeyRingTxHash `in_` valList ts
&&. t ^. KeyRingTxConfidence ==. val TxDead
)
return $ t ^. KeyRingTxTx
-- Revive dead transactions (in no particular order)
forM_ deadTxs $ reviveTx . unValue
-- Confirm the transactions
forM_ (zip (actionNodes action) expTxsLs) $ \(node, hs) ->
splitUpdate hs $ \h t -> do
set t [ KeyRingTxConfidence =. val TxBuilding
, KeyRingTxConfirmedBy =. val (Just (nodeBlockHash node))
, KeyRingTxConfirmedHeight =.
val (Just (nodeHeaderHeight node))
, KeyRingTxConfirmedDate =.
val (Just (blockTimestamp $ nodeHeader node))
]
where_ $ t ^. KeyRingTxHash `in_` valList h
-- Update the best height in the wallet (used to compute the number
-- of confirmations of transactions)
case reverse $ actionNodes action of
(best:_) ->
setBestBlock (nodeBlockHash best) (nodeHeaderHeight best)
_ -> return ()
-- Helper function to set the best block and best block height in the DB.
setBestBlock :: MonadIO m => BlockHash -> Word32 -> SqlPersistT m ()
setBestBlock bid i = update $ \t -> set t [ KeyRingConfigBlock =. val bid
, KeyRingConfigHeight =. val i
]
-- Helper function to get the best block and best block height from the DB
getBestBlock :: MonadIO m => SqlPersistT m (BlockHash, Word32)
getBestBlock = do
cfgM <- liftM (fmap entityVal) $ P.selectFirst [] []
return $ case cfgM of
Just KeyRingConfig{..} -> (keyRingConfigBlock, keyRingConfigHeight)
Nothing -> throw $ WalletException $ unwords
[ "Could not get the best block."
, "Wallet database is probably not initialized"
]
-- Revive a dead transaction. All transactions that are in conflict with this
-- one will be killed.
reviveTx :: MonadIO m => Tx -> SqlPersistT m ()
reviveTx tx = do
-- Kill all transactions spending our coins
spendingTxs <- getSpendingTxs tx Nothing
killTxIds $ map entityKey spendingTxs
-- Find all the KeyRingTxId that have to be revived
ids <- select $ from $ \t -> do
where_ ( t ^. KeyRingTxHash ==. val (txHash tx)
&&. t ^. KeyRingTxConfidence ==. val TxDead
)
return (t ^. KeyRingTxAccount, t ^. KeyRingTxId)
-- Spend the inputs for all our transactions
forM_ ids $ \(Value ai, Value ti) -> spendInputs ai ti tx
-- Update the transactions
splitUpdate (map (unValue . snd) ids) $ \is t -> do
set t [ KeyRingTxConfidence =. val TxPending
, KeyRingTxConfirmedBy =. val Nothing
, KeyRingTxConfirmedHeight =. val Nothing
, KeyRingTxConfirmedDate =. val Nothing
]
where_ $ t ^. KeyRingTxId `in_` valList is
{- Transaction creation and signing (local wallet functions) -}
-- | Create a transaction sending some coins to a list of recipient addresses.
createTx :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m)
=> KeyRing -- ^ KeyRing
-> Entity KeyRingAccount -- ^ Account Entity
-> [(Address,Word64)] -- ^ List of recipient addresses and amounts
-> Word64 -- ^ Fee per 1000 bytes
-> Word32 -- ^ Minimum confirmations
-> Bool -- ^ Should fee be paid by recipient
-> Bool -- ^ Should the transaction be signed
-> SqlPersistT m (KeyRingTx, [KeyRingAddr])
-- ^ (New transaction hash, Completed flag)
createTx keyRing accE@(Entity ai acc) dests fee minConf rcptFee sign = do
-- Build an unsigned transaction from the given recipient values and fee
(unsignedTx, inCoins) <- buildUnsignedTx accE dests fee minConf rcptFee
-- Sign our new transaction if signing was requested
let dat = map toCoinSignData inCoins
tx | sign = signOfflineTx keyRing acc unsignedTx dat
| otherwise = unsignedTx
-- Import the transaction in the wallet either as a network transaction if
-- it is complete, or as an offline transaction otherwise.
(res, newAddrs) <- importTx' tx ai inCoins
case res of
(txRes:_) -> return (txRes, newAddrs)
_ -> liftIO . throwIO $ WalletException
"Error while importing the new transaction"
toCoinSignData :: InCoinData -> CoinSignData
toCoinSignData (InCoinData (Entity _ c) t x) =
CoinSignData (OutPoint (keyRingTxHash t) (keyRingCoinPos c))
(keyRingCoinScript c)
(keyRingAddrDerivation x)
-- Build an unsigned transaction given a list of recipients and a fee. Returns
-- the unsigned transaction together with the input coins that have been
-- selected or spending.
buildUnsignedTx
:: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m)
=> Entity KeyRingAccount
-> [(Address, Word64)]
-> Word64
-> Word32
-> Bool
-> SqlPersistT m (Tx, [InCoinData])
buildUnsignedTx _ [] _ _ _ = liftIO . throwIO $ WalletException
"buildUnsignedTx: No transaction recipients have been provided"
buildUnsignedTx accE@(Entity ai acc) origDests origFee minConf rcptFee = do
let p = case keyRingAccountType acc of
AccountMultisig _ m n -> (m, n)
_ -> throw . WalletException $ "Invalid account type"
fee = if rcptFee then 0 else origFee
sink | isMultisigAccount acc = chooseMSCoinsSink tot fee p True
| otherwise = chooseCoinsSink tot fee True
-- TODO: Add more policies like confirmations or coin age
-- Sort coins by their values in descending order
orderPolicy c _ = [desc $ c ^. KeyRingCoinValue]
-- Find the spendable coins in the given account with the required number
-- of minimum confirmations.
selectRes <- spendableCoinsSource ai minConf orderPolicy $$ sink
-- Find a selection of spendable coins that matches our target value
let (selected, change) = either (throw . WalletException) id selectRes
totFee | isMultisigAccount acc = getMSFee origFee p (length selected)
| otherwise = getFee origFee (length selected)
-- Subtract fees from first destination if rcptFee
value = snd $ head origDests
-- First output must not be dust after deducting fees
when (rcptFee && value < totFee + 5430) $ throw $ WalletException
"First recipient cannot cover transaction fees"
-- Subtract fees from first destination if rcptFee
let dests | rcptFee =
second (const $ value - totFee) (head origDests) :
tail origDests
| otherwise = origDests
-- Make sure the first recipient has enough funds to cover the fee
when (snd (head dests) <= 0) $ throw $
WalletException "Transaction fees too high"
-- If the change amount is not dust, we need to add a change address to
-- our list of recipients.
-- TODO: Put the dust value in a constant somewhere. We also need a more
-- general way of detecting dust such as our transactions are not
-- rejected by full nodes.
allDests <- if change < 5430
then return dests
else addChangeAddr change dests
case buildAddrTx (map toOutPoint selected) $ map toBase58 allDests of
Right tx -> return (tx, selected)
Left err -> liftIO . throwIO $ WalletException err
where
tot = sum $ map snd origDests
toBase58 (a, v) = (addrToBase58 a, v)
toOutPoint (InCoinData (Entity _ c) t _) =
OutPoint (keyRingTxHash t) (keyRingCoinPos c)
addChangeAddr change dests = do
as <- unusedAddresses accE AddressInternal
case as of
(a:_) -> do
-- Use the address to prevent reusing it again
_ <- useAddress a
-- TODO: Randomize the change position
return $ (keyRingAddrAddress a, change) : dests
_ -> liftIO . throwIO $ WalletException
"No unused addresses available"
signKeyRingTx :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m)
=> KeyRing -> Entity KeyRingAccount -> TxHash
-> SqlPersistT m ([KeyRingTx], [KeyRingAddr])
signKeyRingTx keyRing (Entity ai acc) txid = do
(OfflineTxData tx dat, inCoins) <- getOfflineTxData ai txid
let signedTx = signOfflineTx keyRing acc tx dat
importTx' signedTx ai inCoins
getOfflineTxData
:: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m)
=> KeyRingAccountId
-> TxHash
-> SqlPersistT m (OfflineTxData, [InCoinData])
getOfflineTxData ai txid = do
txM <- getBy $ UniqueAccTx ai txid
case txM of
Just (Entity _ tx) -> do
unless (keyRingTxConfidence tx == TxOffline) $ liftIO . throwIO $
WalletException "Can only sign offline transactions."
inCoins <- getInCoins (keyRingTxTx tx) $ Just ai
return
( OfflineTxData (keyRingTxTx tx) $ map toCoinSignData inCoins
, inCoins
)
_ -> liftIO . throwIO $ WalletException $ unwords
[ "Invalid txid", cs $ txHashToHex txid ]
-- Sign a transaction using a list of CoinSignData. This allows an offline
-- signer without access to the coins to sign a given transaction.
signOfflineTx :: KeyRing -- ^ KeyRing
-> KeyRingAccount -- ^ Account used for signing
-> Tx -- ^ Transaction to sign
-> [CoinSignData] -- ^ Input signing data
-> Tx
signOfflineTx keyRing acc tx coinSignData
-- Fail for read-only accounts
| isReadAccount acc = throw $ WalletException
"signOfflineTx is not supported on read-only accounts"
-- Sign the transaction deterministically
| otherwise = either (throw . WalletException) id $
signTx tx sigData $ map (toPrvKeyG . xPrvKey) prvKeys
where
-- Compute all the SigInputs
sigData = map (toSigData acc) coinSignData
-- Compute all the private keys
prvKeys = map (toPrvKey (keyRingMaster keyRing) acc) coinSignData
-- Build a SigInput from a CoinSignData
toSigData acc' (CoinSignData op so deriv) =
-- TODO: Here we override the SigHash to be SigAll False all the time.
-- Should we be more flexible?
SigInput so op (SigAll False) $
if isMultisigAccount acc
then Just $ getPathRedeem acc' deriv
else Nothing
toPrvKey master acc' (CoinSignData _ _ deriv) =
case keyRingAccountDerivation acc' of
Just root -> derivePath (root ++| deriv) master
_ -> throw $ WalletException $ unwords
[ "No derivation available in account"
, unpack $ keyRingAccountName acc'
]
-- Returns unspent coins that can be spent in an account that have a minimum
-- number of confirmations. Coinbase coins can only be spent after 100
-- confirmations.
spendableCoins
:: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m)
=> KeyRingAccountId -- ^ Account key
-> Word32 -- ^ Minimum confirmations
-> ( SqlExpr (Entity KeyRingCoin)
-> SqlExpr (Entity KeyRingTx)
-> [SqlExpr OrderBy]
)
-- ^ Coin ordering policy
-> SqlPersistT m [InCoinData] -- ^ Spendable coins
spendableCoins ai minConf orderPolicy =
liftM (map f) $ select $ spendableCoinsFrom ai minConf orderPolicy
where
f (c, t, x) = InCoinData c (entityVal t) (entityVal x)
spendableCoinsSource
:: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m)
=> KeyRingAccountId -- ^ Account key
-> Word32 -- ^ Minimum confirmations
-> ( SqlExpr (Entity KeyRingCoin)
-> SqlExpr (Entity KeyRingTx)
-> [SqlExpr OrderBy]
)
-- ^ Coin ordering policy
-> Source (SqlPersistT m) InCoinData
-- ^ Spendable coins
spendableCoinsSource ai minConf orderPolicy =
mapOutput f $ selectSource $ spendableCoinsFrom ai minConf orderPolicy
where
f (c, t, x) = InCoinData c (entityVal t) (entityVal x)
spendableCoinsFrom
:: KeyRingAccountId -- ^ Account key
-> Word32 -- ^ Minimum confirmations
-> ( SqlExpr (Entity KeyRingCoin)
-> SqlExpr (Entity KeyRingTx)
-> [SqlExpr OrderBy]
)
-- ^ Coin ordering policy
-> SqlQuery ( SqlExpr (Entity KeyRingCoin)
, SqlExpr (Entity KeyRingTx)
, SqlExpr (Entity KeyRingAddr)
)
spendableCoinsFrom ai minConf orderPolicy =
from $ \(c `InnerJoin` t `InnerJoin` x `LeftOuterJoin` s) -> do
-- Joins have to be set in reverse order !
-- Left outer join on spent coins
on ( s ?. KeyRingSpentCoinAccount ==. just (c ^. KeyRingCoinAccount)
&&. s ?. KeyRingSpentCoinHash ==. just (c ^. KeyRingCoinHash)
&&. s ?. KeyRingSpentCoinPos ==. just (c ^. KeyRingCoinPos)
)
on $ x ^. KeyRingAddrId ==. c ^. KeyRingCoinAddr
-- Inner join on coins and transactions
on $ t ^. KeyRingTxId ==. c ^. KeyRingCoinTx
where_ ( c ^. KeyRingCoinAccount ==. val ai
&&. t ^. KeyRingTxConfidence
`in_` valList [ TxPending, TxBuilding ]
-- We only want unspent coins
&&. E.isNothing (s ?. KeyRingSpentCoinId)
&&. limitConfirmations (Right t) minConf
)
orderBy (orderPolicy c t)
return (c, t, x)
-- If the current height is 200 and a coin was confirmed at height 198, then it
-- has 3 confirmations. So, if we require 3 confirmations, we want coins with a
-- confirmed height of 198 or less (200 - 3 + 1).
limitConfirmations :: Either (SqlExpr (Maybe (Entity KeyRingTx)))
(SqlExpr (Entity KeyRingTx))
-> Word32
-> SqlExpr (Value Bool)
limitConfirmations txE minconf
| minconf == 0 = limitCoinbase
| minconf < 100 = limitConfs minconf &&. limitCoinbase
| otherwise = limitConfs minconf
where
limitConfs i = case txE of
Left t -> t ?. KeyRingTxConfirmedHeight
<=. just (just (selectHeight -. val (i - 1)))
Right t -> t ^. KeyRingTxConfirmedHeight
<=. just (selectHeight -. val (i - 1))
-- Coinbase transactions require 100 confirmations
limitCoinbase = case txE of
Left t ->
not_ (coalesceDefault [t ?. KeyRingTxIsCoinbase] (val False)) ||.
limitConfs 100
Right t ->
not_ (t ^. KeyRingTxIsCoinbase) ||. limitConfs 100
selectHeight :: SqlExpr (Value Word32)
selectHeight = sub_select $ from $ \co -> do
limit 1
return $ co ^. KeyRingConfigHeight
{- Balances -}
accountBalance :: MonadIO m
=> KeyRingAccountId
-> Word32
-> Bool
-> SqlPersistT m Word64
accountBalance ai minconf offline = do
res <- select $ from $ \(c `InnerJoin`
t `LeftOuterJoin` s `LeftOuterJoin` st) -> do
on $ st ?. KeyRingTxId ==. s ?. KeyRingSpentCoinSpendingTx
on ( s ?. KeyRingSpentCoinAccount ==. just (c ^. KeyRingCoinAccount)
&&. s ?. KeyRingSpentCoinHash ==. just (c ^. KeyRingCoinHash)
&&. s ?. KeyRingSpentCoinPos ==. just (c ^. KeyRingCoinPos)
)
on $ t ^. KeyRingTxId ==. c ^. KeyRingCoinTx
let unspent = E.isNothing ( s ?. KeyRingSpentCoinId )
spentOffline = st ?. KeyRingTxConfidence ==. just (val TxOffline)
cond = c ^. KeyRingCoinAccount ==. val ai
&&. t ^. KeyRingTxConfidence `in_` valList validConfidence
-- For non-offline balances, we have to take into account
-- the coins which are spent by offline transactions.
&&. if offline then unspent else unspent ||. spentOffline
where_ $ if minconf == 0
then cond
else cond &&. limitConfirmations (Right t) minconf
return $ sum_ (c ^. KeyRingCoinValue)
case res of
(Value (Just s):_) -> return $ floor (s :: Double)
_ -> return 0
where
validConfidence = TxPending : TxBuilding : [ TxOffline | offline ]
addressBalances :: MonadIO m
=> Entity KeyRingAccount
-> KeyIndex
-> KeyIndex
-> AddressType
-> Word32
-> Bool
-> SqlPersistT m [(KeyIndex, BalanceInfo)]
addressBalances accE@(Entity ai _) iMin iMax addrType minconf offline = do
-- We keep our joins flat to improve performance in SQLite.
res <- select $ from $ \(x `LeftOuterJoin` c `LeftOuterJoin`
t `LeftOuterJoin` s `LeftOuterJoin` st) -> do
let joinCond = st ?. KeyRingTxId ==. s ?. KeyRingSpentCoinSpendingTx
-- Do not join the spending information for offline transactions if we
-- request the online balances. This will count the coin as unspent.
on $ if offline
then joinCond
else joinCond &&. st ?. KeyRingTxConfidence !=. just (val TxOffline)
on $ s ?. KeyRingSpentCoinAccount ==. c ?. KeyRingCoinAccount
&&. s ?. KeyRingSpentCoinHash ==. c ?. KeyRingCoinHash
&&. s ?. KeyRingSpentCoinPos ==. c ?. KeyRingCoinPos
let txJoin = t ?. KeyRingTxId ==. c ?. KeyRingCoinTx
&&. t ?. KeyRingTxConfidence `in_` valList validConfidence
on $ if minconf == 0
then txJoin
else txJoin &&. limitConfirmations (Left t) minconf
on $ c ?. KeyRingCoinAddr ==. just (x ^. KeyRingAddrId)
let limitIndex
| iMin == iMax = x ^. KeyRingAddrIndex ==. val iMin
| otherwise = x ^. KeyRingAddrIndex >=. val iMin
&&. x ^. KeyRingAddrIndex <=. val iMax
where_ ( x ^. KeyRingAddrAccount ==. val ai
&&. limitIndex
&&. x ^. KeyRingAddrIndex <. subSelectAddrCount accE addrType
&&. x ^. KeyRingAddrType ==. val addrType
)
groupBy $ x ^. KeyRingAddrIndex
let unspent = E.isNothing $ st ?. KeyRingTxId
invalidTx = E.isNothing $ t ?. KeyRingTxId
return ( x ^. KeyRingAddrIndex -- Address index
, sum_ $ case_
[ when_ invalidTx
then_ (val (Just 0))
] (else_ $ c ?. KeyRingCoinValue) -- Out value
, sum_ $ case_
[ when_ (unspent ||. invalidTx)
then_ (val (Just 0))
] (else_ $ c ?. KeyRingCoinValue) -- Out value
, count $ t ?. KeyRingTxId -- New coins
, count $ case_
[ when_ invalidTx
then_ (val Nothing)
] (else_ $ st ?. KeyRingTxId) -- Spent coins
)
return $ map f res
where
validConfidence = Just TxPending : Just TxBuilding :
[ Just TxOffline | offline ]
f (Value i, Value inM, Value outM, Value newC, Value spentC) =
let b = BalanceInfo
{ balanceInfoInBalance =
floor $ fromMaybe (0 :: Double) inM
, balanceInfoOutBalance =
floor $ fromMaybe (0 :: Double) outM
, balanceInfoCoins = newC
, balanceInfoSpentCoins = spentC
}
in (i, b)
{- Rescans -}
resetRescan :: MonadIO m => SqlPersistT m ()
resetRescan = do
P.deleteWhere ([] :: [P.Filter KeyRingCoin])
P.deleteWhere ([] :: [P.Filter KeyRingSpentCoin])
P.deleteWhere ([] :: [P.Filter KeyRingTx])
setBestBlock (headerHash genesisHeader) 0
{- Helpers -}
-- Join AND expressions with OR conditions in a binary way
join2 :: [SqlExpr (Value Bool)] -> SqlExpr (Value Bool)
join2 xs = case xs of
[] -> val False
[x] -> x
_ -> let (ls,rs) = splitAt (length xs `div` 2) xs
in join2 ls ||. join2 rs
splitSelect :: (SqlSelect a r, MonadIO m)
=> [t]
-> ([t] -> SqlQuery a)
-> SqlPersistT m [r]
splitSelect ts queryF =
liftM concat $ forM vals $ select . queryF
where
vals = chunksOf paramLimit ts
splitUpdate :: ( MonadIO m
, P.PersistEntity val
, P.PersistEntityBackend val ~ SqlBackend
)
=> [t]
-> ([t] -> SqlExpr (Entity val) -> SqlQuery ())
-> SqlPersistT m ()
splitUpdate ts updateF =
forM_ vals $ update . updateF
where
vals = chunksOf paramLimit ts
splitDelete :: MonadIO m => [t] -> ([t] -> SqlQuery ()) -> SqlPersistT m ()
splitDelete ts deleteF =
forM_ vals $ E.delete . deleteF
where
vals = chunksOf paramLimit ts
| plaprade/haskoin-wallet | Network/Haskoin/Wallet/Transaction.hs | unlicense | 55,944 | 0 | 25 | 17,651 | 13,283 | 6,823 | 6,460 | -1 | -1 |
-- Geoffrey Corey
-- Eric Timmerman
module Hw5 where
-- 1.)
-- 0 []
-- 1 [x:?]
-- 2 [y:?, x:?]
-- 3 [y:1, x:?]
-- 11 [f:{}, y:1, x:?]
-- 11 >>
-- 5 [x:2, f:{}, y:1, x:?]
-- 8 [x:2, f:{}, y:1, x:?]
-- 4 >>
-- 5 [x:1, x:2, f:{}, y:1, x:?]
-- 8 [x:1, x:2, f:{}, y:1, x:?]
-- 4 >>
-- 5 [x:0, x:1, x:2, f:{}, y:1, x:?]
-- 6 [x:0, x:1, x:2, f:{}, y:1, x:?]
-- 9 [res:1, x:0, x:1, x:2, f:{}, y:1, x:?]
-- <<
-- 8 [x:1, x:2, f:{}, y:2, x:?]
-- 9 [res:2, x:1, x:2, f:{}, y:2, x:?]
-- <<
-- 8 [x:2, f:{}, y:5, x:?]
-- 9 [res:5, x:2, f:{}, y:5, x:?]
-- <<
-- 11 [f:{}, y:5, x:5]
-- 12 [y:5, x:5]
-- 13 []
--
-- 2.)
-- a) Call by Name
-- 0 []
-- 1 [y:?]
-- 2 [z:?, y:?]
-- 3 [z:?, y:7]
-- 4 [f:{}, z:?, y:7]
-- 8 [g:{}, f:{}, z:?, y:7]
-- 13 [g:{}, f:{}, z:?, y:7]
-- >>
-- 8 [x:y*2, g:{}, f:{}, z:?, y:7]
-- 9 >>
-- 4 [a:x+1, x:y*2, g:{}, f:{}, z:?, y:7]
-- 5 [a:x+1, x:y*2, g:{}, f:{}, z:?, y:16]
-- 6 [res:49, a:x+1, x:y*2, g:{}, f:{}, z:?, y:16]
-- <<
-- 9 [x:y*2, g:{}, f:{}, z:?, y:50]
-- 10 >>
-- 4 [a:x-y+3, x:y*2, g:{}, f:{}, z:?, y:50]
-- 5 [a:x-y+3, x:y*2, g:{}, f:{}, z:?, y:55]
-- 6 [res:113, a:x-y+3, x:y*2, g:{}, f:{}, z:?, y:55]
-- <<
-- 10 [x:y*2, g:{}, f:{}, z:113, y:55]
-- 11 [res:114, x:y*2, g:{}, f:{}, z:113, y:55]
-- <<
-- 13 [g:{}, f:{}, z:114, y:55]
-- 14 [z:114, y:55]
-- 15 [ ]
--
-- y:55, z:114
-- b) Call by Need
-- 1 [y:?]
-- 2 [z:?, y:?]
-- 3 [z:?, y:7]
-- 4 [f:{}, z:?, y:7]
-- 8 [g:{}, f:{}, z:?, y:7]
-- 13 [g:{}, f:{}, z:g(y*2), y:7]
-- >>
-- 8 [x:y*2, g:{}, f:{}, z:g(14), y:7]
-- 9 [y:(f(15)+1), x:14, g:{}, f:{}, z:g(14), y:7]
-- >>
-- 4 [a:15, y:(f(15)+1), x:14, g:{}, f:{}, z:g(14), y:7]
-- 5 [y:16, a:15, y:(f(15)+1), x:14, g:{}, f:{}, z:g(14), y:7]
-- 6 [y:32, x:14, g:{}, f:{}, z:g(14), y:7]
-- 10 [z:f(-15), y:32, x:14, g:{}, f:{}, z:g(14), y:7]
-- >>
-- 4 [a:-15, z:f(-15), y:32, x:14, g:{}, f:{}, z:g(14), y:7]
-- 5 [y:-14, a:-15, z:f(-15), y:32, x:14, g:{}, f:{}, z:g(14), y:7]
-- 6 [z:-29, y:32, x:14, g:{}, f:{}, z:g(14), y:7]
-- 11 [g:{}, f:{}, z:-28, y:7]
-- 14 [z:-28, y:7]
-- 15 []
--
-- y:7, z:-28
-- 3.
-- (a)
-- y = 7
-- z = g(y*2)
-- y = f((y * 2) + 1)
-- y = (y * 2) + 2
-- y = (((y * 2) + 2) + ((y * 2) + 2)) + 1
-- y = y * 4 + 5
-- z = f((y * 2) - y + 3)
-- 8 * y + 10 - (4 * y + 5) + 3
-- 4 * y + 8
-- y = 4 * y + 9
-- z = 8 * y + 17
-- z = 8 * y + 18
-- y = 37, z = 70
--
-- (b) y = 2, z = 4
| stumped2/school | CS381/hw5/Hw5.hs | apache-2.0 | 2,722 | 0 | 2 | 924 | 104 | 103 | 1 | 1 | 0 |
import Control.Concurrent.CachedIO (cachedIO)
import Data.List (isInfixOf)
crawlTheInternet :: IO [String]
crawlTheInternet = do
putStrLn "Scanning pages.."
putStrLn "Parsing HTML.."
putStrLn "Following links.."
return ["website about Haskell", "website about Ruby", "slashdot.org",
"The Monad.Reader", "haskellwiki"]
searchEngine :: String -> IO [String] -> IO [String]
searchEngine query internet = do
pages <- internet
return $ filter (query `isInfixOf`) pages
main :: IO ()
main = do
cachedInternet <- cachedIO 600 crawlTheInternet -- 10 minute cache
print =<< searchEngine "Haskell" cachedInternet
print =<< searchEngine "C#" cachedInternet
| glasserc/haskell-cached-io | test/test-cachedIO.hs | apache-2.0 | 699 | 0 | 9 | 135 | 189 | 95 | 94 | 18 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
module FloydWarshallTest where
import FloydWarshall
import Test.HUnit
import Data.List (nub)
import Data.Map (Map,keys)
import qualified Data.Map as Map
import Data.Array
import Data.Maybe (catMaybes)
data Unit = A | B | C | D | E | F | G
deriving (Read,Show,Ord,Ix,Eq,Enum)
type ExchangePair = (Unit,Unit)
type ExchangeData = Map ExchangePair Double
data Exchange = Exchange ExchangeData
instance Graph Exchange Unit where
vertices = vertices'
edge = edge'
fromInt = fromInt'
vertices' :: Exchange -> [Unit]
vertices' (Exchange d) = nub $ map snd (keys d)
edge' :: Exchange -> Unit -> Unit -> Maybe Double
edge' (Exchange d) x y = Map.lookup (x,y) d
fromInt' :: Exchange -> Int -> Unit
fromInt' _ = toEnum
basicExchangeData :: Exchange
basicExchangeData = Exchange (Map.fromList d)
where
d = [((A,B), 1.2)
,((A,C), 0.89)
,((B,A), 0.88)
,((B,C), 5.10)
,((C,A), 1.1)
,((C,B), 0.15)]
moreComplex :: Exchange
moreComplex = Exchange (Map.fromList d)
where
d = [((A,B), 3.1)
,((A,C), 0.0023)
,((A,D), 0.35)
,((B,A), 0.21)
,((B,C), 0.00353)
,((B,D), 8.13)
,((C,A), 200)
,((C,B), 180.559)
,((C,D), 10.339)
,((D,A), 2.11)
,((D,B), 0.089)
,((D,C), 0.06111)]
noOpportunity :: Exchange
noOpportunity = Exchange (Map.fromList d)
where
d = [((A,B), 2.0), ((B,A), 0.45)]
simpleOpportunity :: Exchange
simpleOpportunity = Exchange (Map.fromList d)
where
d = [((A,B), 1.1), ((B,A), 0.95)]
test1 :: Test
test1 = TestCase (do
assertEqual "Basic test case 1" (Just [A,B,A]) (findArbitrage basicExchangeData)
assertBool "Makes money" (runOpportunity basicExchangeData [A,B,A] > 1.0))
test2 :: Test
test2 = TestCase (do
assertEqual "Basic test case 1" (Just [A,B,D,A]) (findArbitrage moreComplex)
assertBool "Makes money" (runOpportunity moreComplex [A,B,D,A] > 1.0))
test3 :: Test
test3 = TestCase (assertEqual "Basic test case 1" Nothing (findArbitrage noOpportunity))
test4 :: Test
test4 = TestCase (do
assertEqual "Basic test case 1" (Just [A,B,A]) (findArbitrage simpleOpportunity)
assertBool "Makes money" (runOpportunity simpleOpportunity [A,B,A] > 1.0))
tests :: Test
tests = TestList [TestLabel "test1" test1
,TestLabel "test2" test2
,TestLabel "test3" test3
,TestLabel "test4" test4]
-- If there is an opportunity it should make money!
runOpportunity :: Exchange -> [Unit] -> Double
runOpportunity (Exchange m) x = product $ catMaybes (map (flip Map.lookup m) (zip x (tail x)))
| fffej/haskellprojects | arbitrage/FloydWarshallTest.hs | bsd-2-clause | 2,850 | 0 | 13 | 788 | 1,103 | 638 | 465 | 73 | 1 |
module AppleBlas(blasMMult) where
import Foreign hiding (unsafePerformIO)
import Foreign.C.Types
import Unsafe.Coerce
import Prelude hiding (replicate)
--import Data.Storable
import System.IO.Unsafe
import Data.Vector.Storable.Mutable
import GHC.Ptr (castPtr)
import Numerics.Simple.Util
foreign import ccall unsafe "cblas.c simple_dgemm"
dgemm :: Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> CInt -> IO ()
saphWrapper :: (Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> CInt -> IO ())-> ( Ptr Double -> Ptr Double -> Ptr Double -> Int -> IO ())
saphWrapper f = (\c a b n -> f (castPtr c ) (castPtr a) (castPtr c ) (CInt $ fromIntegral n ))
-- this is always safe/ok because CDouble is a newtyped Double, and CInt is a newtyped Int
dgemm_wrapped :: Ptr Double -> Ptr Double -> Ptr Double -> Int -> IO ()
dgemm_wrapped = saphWrapper dgemm
blasMMult :: IOVector Double -> IOVector Double -> IOVector Double -> Int -> IO ()
blasMMult aVect bVect cVect n =
unsafeWith aVect $! \aPtr ->
unsafeWith bVect $! \bPtr ->
unsafeWith cVect $! \cPtr ->
dgemm_wrapped aPtr bPtr cPtr n | ekmett/sparse | benchmarks/AppleBlas.hs | bsd-2-clause | 1,150 | 0 | 12 | 257 | 384 | 197 | 187 | 21 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Application
( makeApplication
, getApplicationDev
, makeFoundation
) where
import Import
import Settings
import Yesod.Auth
import Yesod.Default.Config
import Yesod.Default.Main
import Yesod.Default.Handlers
import Network.Wai.Middleware.RequestLogger
import qualified Database.Persist
import Database.Persist.Sql (runMigration)
import Network.HTTP.Conduit (newManager, def)
import Control.Monad.Logger (runLoggingT)
import System.IO (stdout)
import System.Log.FastLogger (mkLogger)
import Yesod.Comments.Management
import Yesod.Comments.Storage (migrateComments)
-- Import all relevant handler modules here.
-- Don't forget to add new modules to your cabal file!
import Handler.Archives
import Handler.Feed
import Handler.Posts
import Handler.Profile
import Handler.Root
import Handler.Tags
import Handler.Users
import Handler.GoogleVerify
-- 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 creates a WAI application. This is also the
-- place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
makeApplication :: AppConfig DefaultEnv () -> IO Application
makeApplication conf = do
foundation <- makeFoundation conf
-- Initialize the logging middleware
logWare <- mkRequestLogger def
{ outputFormat =
if development
then Detailed True
else Apache FromSocket
, destination = Logger $ appLogger foundation
}
-- Create the WAI application and apply middlewares
app <- toWaiAppPlain foundation
return $ logWare app
-- | Loads up any necessary settings, creates your foundation datatype, and
-- performs some initialization.
makeFoundation :: AppConfig DefaultEnv () -> IO App
makeFoundation conf = do
manager <- newManager def
s <- staticSite
dbconf <- withYamlEnvironment "config/postgresql.yml" (appEnv conf)
Database.Persist.loadConfig >>=
Database.Persist.applyEnv
p <- Database.Persist.createPoolConfig (dbconf :: Settings.PersistConf)
logger <- mkLogger True stdout
let foundation = App conf s p manager dbconf logger
-- Perform database migration using our application's logging settings.
runLoggingT
(Database.Persist.runPool dbconf (runMigration migrateAll) p)
(messageLoggerSource foundation logger)
-- TODO: combine this with above
runLoggingT
(Database.Persist.runPool dbconf (runMigration migrateComments) p)
(messageLoggerSource foundation logger)
return foundation
-- for yesod devel
getApplicationDev :: IO (Int, Application)
getApplicationDev =
defaultDevelApp loader makeApplication
where
loader = Yesod.Default.Config.loadConfig (configSettings Development)
| pbrisbin/devsite | Application.hs | bsd-2-clause | 3,073 | 0 | 12 | 574 | 547 | 298 | 249 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DeriveDataTypeable #-}
module Propellor.Property.Apt where
import Data.Maybe
import Data.List
import Data.Typeable
import System.IO
import Control.Monad
import Control.Applicative
import Prelude
import Propellor.Base
import qualified Propellor.Property.File as File
import qualified Propellor.Property.Service as Service
import Propellor.Property.File (Line)
import Propellor.Types.Info
data HostMirror = HostMirror Url
deriving (Eq, Show, Typeable)
-- | Indicate host's preferred apt mirror (e.g. an apt cacher on the host's LAN)
mirror :: Url -> Property (HasInfo + UnixLike)
mirror u = pureInfoProperty (u ++ " apt mirror selected")
(InfoVal (HostMirror u))
getMirror :: Propellor Url
getMirror = do
mirrorInfo <- getMirrorInfo
osInfo <- getOS
return $ case (osInfo, mirrorInfo) of
(_, Just (HostMirror u)) -> u
(Just (System (Debian _ _) _), _) ->
"http://deb.debian.org/debian"
(Just (System (Buntish _) _), _) ->
"mirror://mirrors.ubuntu.com/"
(Just (System dist _), _) ->
error ("no Apt mirror defined for " ++ show dist)
_ -> error "no Apt mirror defined for this host or OS"
where
getMirrorInfo :: Propellor (Maybe HostMirror)
getMirrorInfo = fromInfoVal <$> askInfo
withMirror :: Desc -> (Url -> Property DebianLike) -> Property DebianLike
withMirror desc mkp = property' desc $ \w -> do
u <- getMirror
ensureProperty w (mkp u)
sourcesList :: FilePath
sourcesList = "/etc/apt/sources.list"
type Url = String
type Section = String
type SourcesGenerator = DebianSuite -> [Line]
showSuite :: DebianSuite -> String
showSuite (Stable s) = s
showSuite Testing = "testing"
showSuite Unstable = "unstable"
showSuite Experimental = "experimental"
backportSuite :: DebianSuite -> Maybe String
backportSuite (Stable s) = Just (s ++ "-backports")
backportSuite _ = Nothing
stableUpdatesSuite :: DebianSuite -> Maybe String
stableUpdatesSuite (Stable s) = Just (s ++ "-updates")
stableUpdatesSuite _ = Nothing
debLine :: String -> Url -> [Section] -> Line
debLine suite url sections = unwords $
["deb", url, suite] ++ sections
srcLine :: Line -> Line
srcLine l = case words l of
("deb":rest) -> unwords $ "deb-src" : rest
_ -> ""
stdSections :: [Section]
stdSections = ["main", "contrib", "non-free"]
binandsrc :: String -> SourcesGenerator
binandsrc url suite = catMaybes
[ Just l
, Just $ srcLine l
, bl
, srcLine <$> bl
]
where
l = debLine (showSuite suite) url stdSections
bl = do
bs <- backportSuite suite
return $ debLine bs url stdSections
stdArchiveLines :: Propellor SourcesGenerator
stdArchiveLines = return . binandsrc =<< getMirror
-- | Only available for Stable and Testing
securityUpdates :: SourcesGenerator
securityUpdates suite
| isStable suite || suite == Testing =
let l = "deb http://security.debian.org/ " ++ showSuite suite ++ "/updates " ++ unwords stdSections
in [l, srcLine l]
| otherwise = []
-- | Makes sources.list have a standard content using the Debian mirror CDN
-- (or other host specified using the `mirror` property), with the
-- Debian suite configured by the os.
stdSourcesList :: Property Debian
stdSourcesList = withOS "standard sources.list" $ \w o -> case o of
(Just (System (Debian _ suite) _)) ->
ensureProperty w $ stdSourcesListFor suite
_ -> unsupportedOS'
stdSourcesListFor :: DebianSuite -> Property Debian
stdSourcesListFor suite = stdSourcesList' suite []
-- | Adds additional sources.list generators.
--
-- Note that if a Property needs to enable an apt source, it's better
-- to do so via a separate file in </etc/apt/sources.list.d/>
stdSourcesList' :: DebianSuite -> [SourcesGenerator] -> Property Debian
stdSourcesList' suite more = tightenTargets $
withMirror desc $ \u -> setSourcesList
(concatMap (\gen -> gen suite) (generators u))
where
generators u = [binandsrc u, securityUpdates] ++ more
desc = ("standard sources.list for " ++ show suite)
type PinPriority = Int
-- | Adds an apt source for a suite, and pins that suite to a given pin value
-- (see apt_preferences(5)). Revert to drop the source and unpin the suite.
--
-- If the requested suite is the host's OS suite, the suite is pinned, but no
-- source is added. That apt source should already be available, or you can use
-- a property like 'Apt.stdSourcesList'.
suiteAvailablePinned
:: DebianSuite
-> PinPriority
-> RevertableProperty Debian Debian
suiteAvailablePinned s pin = available <!> unavailable
where
available :: Property Debian
available = tightenTargets $ combineProperties (desc True) $ props
& File.hasContent prefFile (suitePinBlock "*" s pin)
& setSourcesFile
unavailable :: Property Debian
unavailable = tightenTargets $ combineProperties (desc False) $ props
& File.notPresent sourcesFile
`onChange` update
& File.notPresent prefFile
setSourcesFile :: Property Debian
setSourcesFile = tightenTargets $ withMirror (desc True) $ \u ->
withOS (desc True) $ \w o -> case o of
(Just (System (Debian _ hostSuite) _))
| s /= hostSuite -> ensureProperty w $
File.hasContent sourcesFile (sources u)
`onChange` update
_ -> noChange
-- Unless we are pinning a backports suite, filter out any backports
-- sources that were added by our generators. The user probably doesn't
-- want those to be pinned to the same value
sources u = dropBackports $ concatMap (\gen -> gen s) (generators u)
where
dropBackports
| "-backports" `isSuffixOf` (showSuite s) = id
| otherwise = filter (not . isInfixOf "-backports")
generators u = [binandsrc u, securityUpdates]
prefFile = "/etc/apt/preferences.d/20" ++ showSuite s ++ ".pref"
sourcesFile = "/etc/apt/sources.list.d/" ++ showSuite s ++ ".list"
desc True = "Debian " ++ showSuite s ++ " pinned, priority " ++ show pin
desc False = "Debian " ++ showSuite s ++ " not pinned"
setSourcesList :: [Line] -> Property DebianLike
setSourcesList ls = sourcesList `File.hasContent` ls `onChange` update
setSourcesListD :: [Line] -> FilePath -> Property DebianLike
setSourcesListD ls basename = f `File.hasContent` ls `onChange` update
where
f = "/etc/apt/sources.list.d/" ++ basename ++ ".list"
runApt :: [String] -> UncheckedProperty DebianLike
runApt ps = tightenTargets $ cmdPropertyEnv "apt-get" ps noninteractiveEnv
noninteractiveEnv :: [(String, String)]
noninteractiveEnv =
[ ("DEBIAN_FRONTEND", "noninteractive")
, ("APT_LISTCHANGES_FRONTEND", "none")
]
-- | Have apt update its lists of packages, but without upgrading anything.
update :: Property DebianLike
update = combineProperties ("apt update") $ props
& pendingConfigured
& runApt ["update"]
`assume` MadeChange
-- | Have apt upgrade packages, adding new packages and removing old as
-- necessary. Often used in combination with the `update` property.
upgrade :: Property DebianLike
upgrade = upgrade' "dist-upgrade"
upgrade' :: String -> Property DebianLike
upgrade' p = combineProperties ("apt " ++ p) $ props
& pendingConfigured
& runApt ["-y", p]
`assume` MadeChange
-- | Have apt upgrade packages, but never add new packages or remove
-- old packages. Not suitable for upgrading acrocess major versions
-- of the distribution.
safeUpgrade :: Property DebianLike
safeUpgrade = upgrade' "upgrade"
-- | Have dpkg try to configure any packages that are not fully configured.
pendingConfigured :: Property DebianLike
pendingConfigured = tightenTargets $
cmdPropertyEnv "dpkg" ["--configure", "--pending"] noninteractiveEnv
`assume` MadeChange
`describe` "dpkg configured pending"
type Package = String
installed :: [Package] -> Property DebianLike
installed = installed' ["-y"]
installed' :: [String] -> [Package] -> Property DebianLike
installed' params ps = robustly $ check (not <$> isInstalled' ps) go
`describe` unwords ("apt installed":ps)
where
go = runApt (params ++ ["install"] ++ ps)
installedBackport :: [Package] -> Property Debian
installedBackport ps = withOS desc $ \w o -> case o of
(Just (System (Debian _ suite) _)) -> case backportSuite suite of
Nothing -> unsupportedOS'
Just bs -> ensureProperty w $
runApt (["install", "-t", bs, "-y"] ++ ps)
`changesFile` dpkgStatus
_ -> unsupportedOS'
where
desc = unwords ("apt installed backport":ps)
-- | Minimal install of package, without recommends.
installedMin :: [Package] -> Property DebianLike
installedMin = installed' ["--no-install-recommends", "-y"]
removed :: [Package] -> Property DebianLike
removed ps = check (any (== IsInstalled) <$> getInstallStatus ps)
(runApt (["-y", "remove"] ++ ps))
`describe` unwords ("apt removed":ps)
buildDep :: [Package] -> Property DebianLike
buildDep ps = robustly $ go
`changesFile` dpkgStatus
`describe` unwords ("apt build-dep":ps)
where
go = runApt $ ["-y", "build-dep"] ++ ps
-- | Installs the build deps for the source package unpacked
-- in the specifed directory, with a dummy package also
-- installed so that autoRemove won't remove them.
buildDepIn :: FilePath -> Property DebianLike
buildDepIn dir = cmdPropertyEnv "sh" ["-c", cmd] noninteractiveEnv
`changesFile` dpkgStatus
`requires` installedMin ["devscripts", "equivs"]
where
cmd = "cd '" ++ dir ++ "' && mk-build-deps debian/control --install --tool 'apt-get -y --no-install-recommends' --remove"
-- | The name of a package, a glob to match the names of packages, or a regexp
-- surrounded by slashes to match the names of packages. See
-- apt_preferences(5), "Regular expressions and glob(7) syntax"
type AptPackagePref = String
-- | Pins a list of packages, package wildcards and/or regular expressions to a
-- list of suites and corresponding pin priorities (see apt_preferences(5)).
-- Revert to unpin.
--
-- Each package, package wildcard or regular expression will be pinned to all of
-- the specified suites.
--
-- Note that this will have no effect unless there is an apt source for each of
-- the suites. One way to add an apt source is 'Apt.suiteAvailablePinned'.
--
-- For example, to obtain Emacs Lisp addon packages not present in your release
-- of Debian from testing, falling back to sid if they're not available in
-- testing, you could use
--
-- > & Apt.suiteAvailablePinned Testing (-10)
-- > & Apt.suiteAvailablePinned Unstable (-10)
-- > & ["elpa-*"] `Apt.pinnedTo` [(Testing, 100), (Unstable, 50)]
pinnedTo
:: [AptPackagePref]
-> [(DebianSuite, PinPriority)]
-> RevertableProperty Debian Debian
pinnedTo ps pins = mconcat (map (\p -> pinnedTo' p pins) ps)
`describe` unwords (("pinned to " ++ showSuites):ps)
where
showSuites = intercalate "," $ showSuite . fst <$> pins
pinnedTo'
:: AptPackagePref
-> [(DebianSuite, PinPriority)]
-> RevertableProperty Debian Debian
pinnedTo' p pins =
(tightenTargets $ prefFile `File.hasContent` prefs)
<!> (tightenTargets $ File.notPresent prefFile)
where
prefs = foldr step [] pins
step (suite, pin) ls = ls ++ suitePinBlock p suite pin ++ [""]
prefFile = "/etc/apt/preferences.d/10propellor_"
++ File.configFileName p <.> "pref"
-- | Package installation may fail becuse the archive has changed.
-- Run an update in that case and retry.
robustly :: Property DebianLike -> Property DebianLike
robustly p = p `fallback` (update `before` p)
isInstalled :: Package -> IO Bool
isInstalled p = isInstalled' [p]
isInstalled' :: [Package] -> IO Bool
isInstalled' ps = all (== IsInstalled) <$> getInstallStatus ps
data InstallStatus = IsInstalled | NotInstalled
deriving (Show, Eq)
{- Returns the InstallStatus of packages that are installed
- or known and not installed. If a package is not known at all to apt
- or dpkg, it is not included in the list. -}
getInstallStatus :: [Package] -> IO [InstallStatus]
getInstallStatus ps = mapMaybe parse . lines <$> policy
where
parse l
| "Installed: (none)" `isInfixOf` l = Just NotInstalled
| "Installed: " `isInfixOf` l = Just IsInstalled
| otherwise = Nothing
policy = do
environ <- addEntry "LANG" "C" <$> getEnvironment
readProcessEnv "apt-cache" ("policy":ps) (Just environ)
autoRemove :: Property DebianLike
autoRemove = runApt ["-y", "autoremove"]
`changesFile` dpkgStatus
`describe` "apt autoremove"
-- | Enables unattended upgrades. Revert to disable.
unattendedUpgrades :: RevertableProperty DebianLike DebianLike
unattendedUpgrades = enable <!> disable
where
enable = setup True
`before` Service.running "cron"
`before` configure
-- work around http://bugs.debian.org/812380
`before` File.notPresent "/etc/apt/apt.conf.d/50unattended-upgrades.ucf-dist"
disable = setup False
setup enabled = (if enabled then installed else removed) ["unattended-upgrades"]
`onChange` reConfigure "unattended-upgrades"
[("unattended-upgrades/enable_auto_updates" , "boolean", v)]
`describe` ("unattended upgrades " ++ v)
where
v
| enabled = "true"
| otherwise = "false"
configure :: Property DebianLike
configure = propertyList "unattended upgrades configured" $ props
& enableupgrading
& unattendedconfig `File.containsLine` "Unattended-Upgrade::Mail \"root\";"
where
enableupgrading :: Property DebianLike
enableupgrading = withOS "unattended upgrades configured" $ \w o ->
case o of
-- the package defaults to only upgrading stable
(Just (System (Debian _ suite) _))
| not (isStable suite) -> ensureProperty w $
unattendedconfig
`File.containsLine`
("Unattended-Upgrade::Origins-Pattern { \"o=Debian,a="++showSuite suite++"\"; };")
_ -> noChange
unattendedconfig = "/etc/apt/apt.conf.d/50unattended-upgrades"
-- | Enable periodic updates (but not upgrades), including download
-- of packages.
periodicUpdates :: Property DebianLike
periodicUpdates = tightenTargets $ "/etc/apt/apt.conf.d/02periodic" `File.hasContent`
[ "APT::Periodic::Enable \"1\";"
, "APT::Periodic::Update-Package-Lists \"1\";"
, "APT::Periodic::Download-Upgradeable-Packages \"1\";"
, "APT::Periodic::Verbose \"1\";"
]
type DebconfTemplate = String
type DebconfTemplateType = String
type DebconfTemplateValue = String
-- | Preseeds debconf values and reconfigures the package so it takes
-- effect.
reConfigure :: Package -> [(DebconfTemplate, DebconfTemplateType, DebconfTemplateValue)] -> Property DebianLike
reConfigure package vals = tightenTargets $
reconfigure
`requires` setselections
`describe` ("reconfigure " ++ package)
where
setselections :: Property DebianLike
setselections = property "preseed" $
if null vals
then noChange
else makeChange $
withHandle StdinHandle createProcessSuccess
(proc "debconf-set-selections" []) $ \h -> do
forM_ vals $ \(tmpl, tmpltype, value) ->
hPutStrLn h $ unwords [package, tmpl, tmpltype, value]
hClose h
reconfigure = cmdPropertyEnv "dpkg-reconfigure" ["-fnone", package] noninteractiveEnv
`assume` MadeChange
-- | Ensures that a service is installed and running.
--
-- Assumes that there is a 1:1 mapping between service names and apt
-- package names.
serviceInstalledRunning :: Package -> Property DebianLike
serviceInstalledRunning svc = Service.running svc `requires` installed [svc]
data AptKey = AptKey
{ keyname :: String
, pubkey :: String
}
trustsKey :: AptKey -> RevertableProperty DebianLike DebianLike
trustsKey k = trustsKey' k <!> untrustKey k
trustsKey' :: AptKey -> Property DebianLike
trustsKey' k = check (not <$> doesFileExist f) $ property desc $ makeChange $ do
withHandle StdinHandle createProcessSuccess
(proc "gpg" ["--no-default-keyring", "--keyring", f, "--import", "-"]) $ \h -> do
hPutStr h (pubkey k)
hClose h
nukeFile $ f ++ "~" -- gpg dropping
where
desc = "apt trusts key " ++ keyname k
f = aptKeyFile k
untrustKey :: AptKey -> Property DebianLike
untrustKey = tightenTargets . File.notPresent . aptKeyFile
aptKeyFile :: AptKey -> FilePath
aptKeyFile k = "/etc/apt/trusted.gpg.d" </> keyname k ++ ".gpg"
-- | Cleans apt's cache of downloaded packages to avoid using up disk
-- space.
cacheCleaned :: Property DebianLike
cacheCleaned = tightenTargets $ cmdProperty "apt-get" ["clean"]
`assume` NoChange
`describe` "apt cache cleaned"
-- | Add a foreign architecture to dpkg and apt.
hasForeignArch :: String -> Property DebianLike
hasForeignArch arch = check notAdded (add `before` update)
`describe` ("dpkg has foreign architecture " ++ arch)
where
notAdded = (notElem arch . lines) <$> readProcess "dpkg" ["--print-foreign-architectures"]
add = cmdProperty "dpkg" ["--add-architecture", arch]
`assume` MadeChange
-- | Disable the use of PDiffs for machines with high-bandwidth connections.
noPDiffs :: Property DebianLike
noPDiffs = tightenTargets $ "/etc/apt/apt.conf.d/20pdiffs" `File.hasContent`
[ "Acquire::PDiffs \"false\";" ]
suitePin :: DebianSuite -> String
suitePin s = prefix s ++ showSuite s
where
prefix (Stable _) = "n="
prefix _ = "a="
suitePinBlock :: AptPackagePref -> DebianSuite -> PinPriority -> [Line]
suitePinBlock p suite pin =
[ "Explanation: This file added by propellor"
, "Package: " ++ p
, "Pin: release " ++ suitePin suite
, "Pin-Priority: " ++ val pin
]
dpkgStatus :: FilePath
dpkgStatus = "/var/lib/dpkg/status"
| ArchiveTeam/glowing-computing-machine | src/Propellor/Property/Apt.hs | bsd-2-clause | 17,105 | 156 | 19 | 2,868 | 4,329 | 2,307 | 2,022 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
-- | Contains basic operations related to the GUI
module View
( module View
, module Exported
)
where
-- External libraries
import Control.Monad
import Graphics.UI.Gtk
import Hails.MVC.View.GtkView
import Graphics.UI.Gtk.Extra.BuilderTH
import Hails.MVC.View.GladeView
import Hails.MVC.View.GtkView as Exported
-- Internal libraries
import Config.Config
import Graphics.UI.Gtk.Display.GlossIO
import Graphics.UI.Gtk.Display.SoOSiMState
import View.InitAnimationArea
import View.InitIconsInfoArea
import View.Tooltips
import View.Objects as Builder
-- | Initialises the GUI. This must be called before
-- any other GUI operation.
initView :: IO ()
initView = void unsafeInitGUIForThreadedRTS -- initGUI
-- | Starts a thread for the view.
startView :: IO ()
startView = mainGUI
-- | Executes an operation on the view thread synchronously
onViewSync :: IO a -> IO a
onViewSync = postGUISync
-- | Executes an operation on the view thread asynchronously
onViewAsync :: IO () -> IO ()
onViewAsync = postGUIAsync
-- | Destroys the view thread
destroyView :: IO ()
destroyView = mainQuit
instance GtkGUI View where
initialise = createView
instance GladeView View where
ui = uiBuilder
-- | This datatype should hold the elements that we must track in the future
-- (for instance, treeview models)
data View = View
{ uiBuilder :: Builder
, soosimView :: SoOSiMState
, thumbView :: GlossIO
}
-- | Initialised the glade GUI and all the view components that are not
-- included directly in it
createView :: IO View
createView = do
-- Certain aspects of the visual interface can be configured with a config file
cfg <- readConfigFile
-- Load Glade builder
bldr <- loadInterface
-- Intialise interface
widgetShowAll =<< Builder.mainWindow bldr
(soosim, thumb) <- initialiseAnimationArea cfg bldr
initIconsInfoArea bldr
initialiseTooltips bldr
return View
{ uiBuilder = bldr
, soosimView = soosim
, thumbView = thumb
}
-- gtkViewAccessor element name type name
gtkViewAccessor "Builder" "uiBuilder" "mainWindow" "Window"
gtkViewAccessor "Builder" "uiBuilder" "animationViewport" "Viewport"
gtkViewAccessor "Builder" "uiBuilder" "pauseToolBtn" "ToolButton"
gtkViewAccessor "Builder" "uiBuilder" "runToolBtn" "ToolButton"
gtkViewAccessor "Builder" "uiBuilder" "runSlowToolBtn" "ToolButton"
gtkViewAccessor "Builder" "uiBuilder" "stopToolBtn" "ToolButton"
gtkViewAccessor "Builder" "uiBuilder" "slowDownToolBtn" "ToolButton"
gtkViewAccessor "Builder" "uiBuilder" "speedUpToolBtn" "ToolButton"
gtkViewAccessor "Builder" "uiBuilder" "stepForwardToolBtn" "ToolButton"
-- gtkViewAccessor "Builder" "uiBuilder" "stepForwardSmallToolBtn" "ToolButton"
gtkViewAccessor "Builder" "uiBuilder" "stepBackToolBtn" "ToolButton"
gtkViewAccessor "Builder" "uiBuilder" "fullScreenToolBtn" "ToolButton"
gtkViewAccessor "Builder" "uiBuilder" "fullScreenMenuItem" "ImageMenuItem"
gtkViewAccessor "Builder" "uiBuilder" "quitMenuItem" "ImageMenuItem"
-- gtkViewAccessor "Builder" "uiBuilder" "showFlowChartMenuItem" "MenuItem"
gtkViewAccessor "Builder" "uiBuilder" "menuBar" "MenuBar"
gtkViewAccessor "Builder" "uiBuilder" "speedScale" "HScale"
gtkViewAccessor "Builder" "uiBuilder" "infoNotebook" "Notebook"
gtkViewAccessor "Builder" "uiBuilder" "infoSelNotebook" "Notebook"
gtkViewAccessor "Builder" "uiBuilder" "overviewEventBox" "EventBox"
gtkViewAccessor "Builder" "uiBuilder" "fixed1" "Fixed"
gtkViewAccessor "Builder" "uiBuilder" "infoIconView" "IconView"
gtkViewAccessor "Builder" "uiBuilder" "infoTextView" "TextView"
gtkViewAccessor "Builder" "uiBuilder" "traceTextView" "TextView"
gtkViewAccessor "Builder" "uiBuilder" "statusLbl" "Label"
-- Flowchart Window
-- gtkViewAccessor "Builder" "uiBuilder" "flowChartWindow" "Window"
| ivanperez-keera/SoOSiM-ui | src/View.hs | bsd-3-clause | 4,011 | 0 | 9 | 708 | 638 | 331 | 307 | 70 | 1 |
------------------------------------------------------------------------------
-- CPP macros for common instances
------------------------------------------------------------------------------
-- XXX use template haskell instead and include Monoid and IsStream instances
-- as well.
#define MONADPARALLEL , MonadAsync m
#define MONAD_APPLICATIVE_INSTANCE(STREAM,CONSTRAINT) \
instance (Monad m CONSTRAINT) => Applicative (STREAM m) where { \
{-# INLINE pure #-}; \
pure = STREAM . K.yield; \
{-# INLINE (<*>) #-}; \
(<*>) = ap }
#define MONAD_COMMON_INSTANCES(STREAM,CONSTRAINT) \
instance Monad m => Functor (STREAM m) where { \
fmap = map }; \
\
instance (MonadBase b m, Monad m CONSTRAINT) => MonadBase b (STREAM m) where {\
liftBase = liftBaseDefault }; \
\
instance (MonadIO m CONSTRAINT) => MonadIO (STREAM m) where { \
liftIO = lift . liftIO }; \
\
instance (MonadThrow m CONSTRAINT) => MonadThrow (STREAM m) where { \
throwM = lift . throwM }; \
\
{- \
instance (MonadError e m CONSTRAINT) => MonadError e (STREAM m) where { \
throwError = lift . throwError; \
catchError m h = \
fromStream $ withCatchError (toStream m) (\e -> toStream $ h e) }; \
-} \
\
instance (MonadReader r m CONSTRAINT) => MonadReader r (STREAM m) where { \
ask = lift ask; \
local f m = fromStream $ K.withLocal f (toStream m) }; \
\
instance (MonadState s m CONSTRAINT) => MonadState s (STREAM m) where { \
get = lift get; \
put x = lift (put x); \
state k = lift (state k) }
------------------------------------------------------------------------------
-- Lists
------------------------------------------------------------------------------
-- Serial streams can act like regular lists using the Identity monad
-- XXX Show instance is 10x slower compared to read, we can do much better.
-- The list show instance itself is really slow.
-- XXX The default definitions of "<" in the Ord instance etc. do not perform
-- well, because they do not get inlined. Need to add INLINE in Ord class in
-- base?
#if MIN_VERSION_deepseq(1,4,3)
#define NFDATA1_INSTANCE(STREAM) \
instance NFData1 (STREAM Identity) where { \
{-# INLINE liftRnf #-}; \
liftRnf r = runIdentity . P.foldl' (\_ x -> r x) () }
#else
#define NFDATA1_INSTANCE(STREAM)
#endif
#define LIST_INSTANCES(STREAM) \
instance IsList (STREAM Identity a) where { \
type (Item (STREAM Identity a)) = a; \
{-# INLINE fromList #-}; \
fromList = P.fromList; \
{-# INLINE toList #-}; \
toList = runIdentity . P.toList }; \
\
instance Eq a => Eq (STREAM Identity a) where { \
{-# INLINE (==) #-}; \
(==) xs ys = runIdentity $ P.eqBy (==) xs ys }; \
\
instance Ord a => Ord (STREAM Identity a) where { \
{-# INLINE compare #-}; \
compare xs ys = runIdentity $ P.cmpBy compare xs ys; \
{-# INLINE (<) #-}; \
x < y = case compare x y of { LT -> True; _ -> False }; \
{-# INLINE (<=) #-}; \
x <= y = case compare x y of { GT -> False; _ -> True }; \
{-# INLINE (>) #-}; \
x > y = case compare x y of { GT -> True; _ -> False }; \
{-# INLINE (>=) #-}; \
x >= y = case compare x y of { LT -> False; _ -> True }; \
{-# INLINE max #-}; \
max x y = if x <= y then y else x; \
{-# INLINE min #-}; \
min x y = if x <= y then x else y; }; \
\
instance Show a => Show (STREAM Identity a) where { \
showsPrec p dl = showParen (p > 10) $ \
showString "fromList " . shows (toList dl) }; \
\
instance Read a => Read (STREAM Identity a) where { \
readPrec = parens $ prec 10 $ do { \
Ident "fromList" <- lexP; \
fromList <$> readPrec }; \
readListPrec = readListPrecDefault }; \
\
instance (a ~ Char) => IsString (STREAM Identity a) where { \
{-# INLINE fromString #-}; \
fromString = P.fromList }; \
\
instance NFData a => NFData (STREAM Identity a) where { \
{-# INLINE rnf #-}; \
rnf = runIdentity . P.foldl' (\_ x -> rnf x) () }; \
-------------------------------------------------------------------------------
-- Foldable
-------------------------------------------------------------------------------
-- XXX the foldable instance seems to be quit slow. We can try writing
-- custom implementations of foldr and foldl'. If nothing works we can also try
-- writing a Foldable for Identity monad rather than for "Foldable m".
#define FOLDABLE_INSTANCE(STREAM) \
instance (Foldable m, Monad m) => Foldable (STREAM m) where { \
{-# INLINE foldMap #-}; \
foldMap f = fold . P.foldr mappend mempty . fmap f }
-------------------------------------------------------------------------------
-- Traversable
-------------------------------------------------------------------------------
#define TRAVERSABLE_INSTANCE(STREAM) \
instance Traversable (STREAM Identity) where { \
{-# INLINE traverse #-}; \
traverse f s = runIdentity $ P.foldr consA (pure mempty) s \
where { consA x ys = liftA2 K.cons (f x) ys }}
| harendra-kumar/asyncly | src/Streamly/Streams/Instances.hs | bsd-3-clause | 8,334 | 0 | 2 | 4,431 | 35 | 34 | 1 | 1 | 0 |
{-# LANGUAGE DeriveDataTypeable, RecordWildCards #-}
{-# OPTIONS -Wall #-}
module Main where
import Control.Concurrent (forkIO,threadDelay)
import Control.Concurrent.Chan (Chan,writeChan,newChan,getChanContents)
import Control.Monad (forever, unless)
import Data.Data (Data,Typeable)
import Network (PortID(PortNumber),listenOn)
import Network.Socket hiding (listen,recv,send)
import Network.Socket.ByteString (recv,sendAll)
import System.Console.CmdArgs (cmdArgs,(&=),help,summary,def,opt)
import System.Posix (Handler(Ignore),installHandler,sigPIPE)
import qualified Data.ByteString as B
data Throttle = Throttle
{ listen :: Int
, host :: String
, port :: Int
, speed :: Float
, logging :: Bool
} deriving (Show,Data,Typeable)
options :: Throttle
options = Throttle
{ speed = def &= opt (1.6::Float) &= help "Speed in KB/s, e.g. 1.6 (0 for no limit)"
, host = "127.0.0.1"
, port = 80
, listen = 8000
, logging = def &= help "Log about events on the console."
}
&= summary "Throttle v1.0, (C) Chris Done 2010"
&= help "Listens on port <listen> and proxies a throttled \
\connection to <host> on <port> at speed <speed>KB/s."
main :: IO ()
main = do
_ <- installHandler sigPIPE Ignore Nothing
cmdArgs options >>= start
start :: Throttle -> IO ()
start Throttle{..} = withSocketsDo $ do
c <- newTeller logging
listener <- listenOn (PortNumber . fromIntegral $ listen)
forever $ do
(client,_) <- accept listener
tell c $ [show client,": New connection on port ",show port]
_ <- forkIO $ do
server <- connectToServer
tell c $ [show client,": ",show server,": Connected to server at "
,host,":",show port, " with delay ", show delay]
let proxyTo f t = forkIO (proxyToWithChan c f t) >> return ()
client `proxyTo` server
server `proxyTo` client
return ()
where connectToServer = do
addrinfos <- getAddrInfo Nothing (Just host) (Just $ show port)
let serveraddr = head addrinfos
server <- socket (addrFamily serveraddr) Stream defaultProtocol
connect server (addrAddress serveraddr)
return server
proxyToWithChan c from to = do
mapData from to
close c from to
return ()
mapData from to = do
msg <- recv from bufferSize
unless (B.null msg) $ do
_ <- sendAll to msg
unless (speed == 0) $ threadDelay delay
mapData from to
bufferSize = 1024 * 4 :: Int
delay = round $ (fromIntegral $ (1000*1000) * bufferSize) / (speed * 1024)
close c a b = do
tell c $ [show a,":",show b,": Closing connections."]
sClose a
sClose b
-- | Create a new console logger.
newTeller :: Bool -> IO (Maybe (Chan String))
newTeller False = return Nothing
newTeller True = do
c <- newChan
_ <- forkIO $ do
getChanContents c >>= mapM_ putStrLn
return $ Just c
-- | Tell the user something on the console.
tell :: Maybe (Chan String) -> [String] -> IO ()
tell (Just c) = writeChan c . concat
tell Nothing = const $ return ()
| paul-r-ml/throttle | src/Main.hs | bsd-3-clause | 3,227 | 0 | 21 | 887 | 1,046 | 539 | 507 | 80 | 1 |
-- Copyright 2019 Google LLC
--
-- Use of this source code is governed by a BSD-style
-- license that can be found in the LICENSE file or at
-- https://developers.google.com/open-source/licenses/bsd
{-# LANGUAGE CPP #-}
module GHC.SourceGen.Binds.Internal where
#if MIN_VERSION_ghc(9,0,0)
import GHC.Types.Basic (Origin(Generated))
import GHC.Data.Bag (listToBag)
#else
import BasicTypes (Origin(Generated))
import Bag (listToBag)
#endif
import GHC.Hs.Binds
import GHC.Hs.Decls
import GHC.Hs.Expr (MatchGroup(..), Match(..), GRHSs(..))
#if !MIN_VERSION_ghc(8,6,0)
import PlaceHolder (PlaceHolder(..))
#endif
import GHC.SourceGen.Pat.Internal (parenthesize)
import GHC.SourceGen.Syntax.Internal
-- | A binding definition inside of a @let@ or @where@ clause.
--
-- 'RawValBind' definitions may be constructed using its instance of
-- 'HasValBind'. For more details, see the documentation of that function, and
-- of "GHC.SourceGen.Binds" overall.
data RawValBind
= SigV Sig'
| BindV HsBind'
valBinds :: [RawValBind] -> HsLocalBinds'
-- This case prevents GHC from printing an empty "where" clause:
valBinds [] = noExt EmptyLocalBinds
valBinds vbs =
withEpAnnNotUsed HsValBinds
#if MIN_VERSION_ghc(8,6,0)
$ withNoAnnSortKey ValBinds
#else
$ noExt ValBindsIn
#endif
(listToBag $ map mkLocated binds)
(map mkLocated sigs)
where
sigs = [s | SigV s <- vbs]
binds = [b | BindV b <- vbs]
-- | A single function pattern match, including an optional "where" clause.
--
-- For example:
--
-- > f x
-- > | cond = y
-- > | otherwise = z
-- > where
-- > y = ...
-- > z = ...
data RawMatch = RawMatch
{ rawMatchPats :: [Pat']
, rawMatchGRHSs :: RawGRHSs
}
-- | A set of match guards plus an optional "where" clause.
--
-- This type is used in matches and in multi-way if expressions.
--
-- For example:
--
-- > | cond = y
-- > | otherwise = z
-- > where
-- > y = ...
-- > z = ...
data RawGRHSs = RawGRHSs
{ rawGRHSs :: [GuardedExpr]
, rawGRHSWhere :: [RawValBind]
}
matchGroup :: HsMatchContext' -> [RawMatch] -> MatchGroup' LHsExpr'
matchGroup context matches =
noExt MG (mkLocated $ map (mkLocated . mkMatch) matches)
#if !MIN_VERSION_ghc(8,6,0)
[] PlaceHolder
#endif
Generated
where
mkMatch :: RawMatch -> Match' LHsExpr'
mkMatch r = withEpAnnNotUsed Match context
(map builtPat $ map parenthesize $ rawMatchPats r)
(mkGRHSs $ rawMatchGRHSs r)
mkGRHSs :: RawGRHSs -> GRHSs' LHsExpr'
mkGRHSs g = withEmptyEpAnnComments GRHSs
(map builtLoc $ rawGRHSs g)
(fromLocalBinds $ valBinds $ rawGRHSWhere g)
where
#if MIN_VERSION_ghc(9,2,0)
fromLocalBinds = id
#else
fromLocalBinds = builtLoc
#endif
-- | An expression with a single guard.
--
-- For example:
--
-- > | otherwise = ()
type GuardedExpr = GRHS' LHsExpr'
-- | Syntax types which can declare/define functions. For example:
-- declarations, or the body of a class declaration or class instance.
--
-- To declare the type of a function or value, use
-- 'GHC.SourceGen.Binds.typeSig' or 'GHC.SourceGen.Binds.typeSigs'.
--
-- To define a function, use
-- 'GHC.SourceGen.Binds.funBind' or 'GHC.SourceGen.Binds.funBinds'.
--
-- To define a value, use
-- 'GHC.SourceGen.Binds.valBind' or 'GHC.SourceGen.Binds.valBindGuarded'.
class HasValBind t where
sigB :: Sig' -> t
bindB :: HsBind' -> t
instance HasValBind HsDecl' where
sigB = noExt SigD
bindB = noExt ValD
instance HasValBind RawValBind where
sigB = SigV
bindB = BindV
| google/ghc-source-gen | src/GHC/SourceGen/Binds/Internal.hs | bsd-3-clause | 3,661 | 0 | 11 | 819 | 601 | 359 | 242 | 52 | 1 |
module Automaton.NFA (
NFA(..)
, isAcceptState
, step'
, alphabets
, reachableStateSets
, module Automaton
) where
import qualified Data.Map as M
import qualified Data.Set as S
import Automaton
-- 非決定性有限オートマトン
data NFA state alpha = NFA {
nfaTransTable :: M.Map (state, alpha) (S.Set state)
, nfaStart :: state
, nfaAccepts :: S.Set state
} deriving (Show, Read)
isAcceptState :: (State state, Alphabet alpha)
=> NFA state alpha -> state -> Bool
isAcceptState nfa s = S.member s $ nfaAccepts nfa
-- デフォルト付き lookup
lookup' :: Ord k => k -> M.Map k (S.Set a) -> S.Set a
lookup' k map = case M.lookup k map of
Nothing -> S.empty
Just s -> s
-- 状態 s で文字 a を入力したときの(ε遷移も含めた)遷移先を返す。
step' :: (State state, Alphabet alpha)
=> NFA state alpha -> state -> alpha -> S.Set state
step' nfa s a = lookup' (s, a) $ nfaTransTable nfa
instance Automaton NFA where
type F NFA s = S.Set s
step nfa states a =
S.fold (\s states' -> S.union states' $ step' nfa s a) S.empty states
initStates nfa = S.singleton $ nfaStart nfa
isAcceptStates nfa states =
any (isAcceptState nfa) $ S.toList states
-- nfa が認識する言語の文字集合
alphabets :: (State state, Alphabet alpha)
=> NFA state alpha -> S.Set alpha
alphabets nfa =
S.fromList $ map snd $ M.keys $ nfaTransTable nfa
-- nfa がある時点で取りうる状態集合としてありうるものを全て返す。
reachableStateSets :: (State state, Alphabet alpha)
=> NFA state alpha -> S.Set (S.Set state)
reachableStateSets nfa@NFA{..} = traverse S.empty $ S.singleton nfaStart
where
alphas = S.toList $ alphabets nfa
traverse visited states
| S.member states visited = visited
| otherwise =
foldl traverse (S.insert states visited) $ map (step nfa states) alphas
| monamonamonad/RegexDSL | src/Automaton/NFA.hs | bsd-3-clause | 1,948 | 0 | 12 | 424 | 659 | 338 | 321 | -1 | -1 |
module Syntax where
import Data.List
------------------------------------------------------------------
-- Abstract syntax -----------------------------------------------
------------------------------------------------------------------
-- info for all primops; the totality of the info in primops.txt(.pp)
data Info
= Info [Option] [Entry] -- defaults, primops
deriving Show
-- info for one primop
data Entry
= PrimOpSpec { cons :: String, -- PrimOp name
name :: String, -- name in prog text
ty :: Ty, -- type
cat :: Category, -- category
desc :: String, -- description
opts :: [Option] } -- default overrides
| PseudoOpSpec { name :: String, -- name in prog text
ty :: Ty, -- type
desc :: String, -- description
opts :: [Option] } -- default overrides
| PrimTypeSpec { ty :: Ty, -- name in prog text
desc :: String, -- description
opts :: [Option] } -- default overrides
| Section { title :: String, -- section title
desc :: String } -- description
deriving Show
is_primop :: Entry -> Bool
is_primop (PrimOpSpec _ _ _ _ _ _) = True
is_primop _ = False
-- a binding of property to value
data Option
= OptionFalse String -- name = False
| OptionTrue String -- name = True
| OptionString String String -- name = { ... unparsed stuff ... }
| OptionInteger String Int -- name = <int>
deriving Show
-- categorises primops
data Category
= Dyadic | Monadic | Compare | GenPrimOp
deriving Show
-- types
data Ty
= TyF Ty Ty
| TyApp TyCon [Ty]
| TyVar TyVar
| TyUTup [Ty] -- unboxed tuples; just a TyCon really,
-- but convenient like this
deriving (Eq,Show)
type TyVar = String
type TyCon = String
------------------------------------------------------------------
-- Sanity checking -----------------------------------------------
------------------------------------------------------------------
{- Do some simple sanity checks:
* all the default field names are unique
* for each PrimOpSpec, all override field names are unique
* for each PrimOpSpec, all overriden field names
have a corresponding default value
* that primop types correspond in certain ways to the
Category: eg if Comparison, the type must be of the form
T -> T -> Bool.
Dies with "error" if there's a problem, else returns ().
-}
myseqAll :: [()] -> a -> a
myseqAll (():ys) x = myseqAll ys x
myseqAll [] x = x
sanityTop :: Info -> ()
sanityTop (Info defs entries)
= let opt_names = map get_attrib_name defs
primops = filter is_primop entries
in
if length opt_names /= length (nub opt_names)
then error ("non-unique default attribute names: " ++ show opt_names ++ "\n")
else myseqAll (map (sanityPrimOp opt_names) primops) ()
sanityPrimOp :: [String] -> Entry -> ()
sanityPrimOp def_names p
= let p_names = map get_attrib_name (opts p)
p_names_ok
= length p_names == length (nub p_names)
&& all (`elem` def_names) p_names
ty_ok = sane_ty (cat p) (ty p)
in
if not p_names_ok
then error ("attribute names are non-unique or have no default in\n" ++
"info for primop " ++ cons p ++ "\n")
else
if not ty_ok
then error ("type of primop " ++ cons p ++ " doesn't make sense w.r.t" ++
" category " ++ show (cat p) ++ "\n")
else ()
sane_ty :: Category -> Ty -> Bool
sane_ty Compare (TyF t1 (TyF t2 td))
| t1 == t2 && td == TyApp "Bool" [] = True
sane_ty Monadic (TyF t1 td)
| t1 == td = True
sane_ty Dyadic (TyF t1 (TyF t2 td))
| t1 == td && t2 == td = True
sane_ty GenPrimOp _
= True
sane_ty _ _
= False
get_attrib_name :: Option -> String
get_attrib_name (OptionFalse nm) = nm
get_attrib_name (OptionTrue nm) = nm
get_attrib_name (OptionString nm _) = nm
get_attrib_name (OptionInteger nm _) = nm
lookup_attrib :: String -> [Option] -> Maybe Option
lookup_attrib _ [] = Nothing
lookup_attrib nm (a:as)
= if get_attrib_name a == nm then Just a else lookup_attrib nm as
| nomeata/ghc | utils/genprimopcode/Syntax.hs | bsd-3-clause | 4,448 | 0 | 16 | 1,352 | 993 | 545 | 448 | 86 | 3 |
module AD where
import AD.Server
| hlian/afterdark | src/AD.hs | bsd-3-clause | 34 | 0 | 4 | 6 | 9 | 6 | 3 | 2 | 0 |
{-# LANGUAGE FlexibleInstances #-}
module Database.Redis.RedisT where
import Control.Monad
import Control.Monad.Trans
import Data.Conduit
import Database.Redis
data RedisT r m a = RedisT { runRedisT :: r -> m a }
instance (Functor m) => Functor (RedisT r m) where
fmap f v = RedisT $ \ r -> fmap f (runRedisT v r)
instance (Monad m) => Applicative (RedisT r m) where
pure a = RedisT $ \ r -> do (pure a)
(<*>) = ap
instance (Monad m) => Monad (RedisT r m) where
return a = RedisT $ \ r -> do return a
v >>= f = RedisT $ \ r -> do
b <- (runRedisT v r)
runRedisT (f b) r
instance MonadTrans (RedisT Connection) where
lift = liftRedisT
instance MonadRedis (RedisT Connection IO) where
liftRedis r = RedisT $ \ conn -> runRedis conn r
instance (MonadRedis m) => MonadRedis (ConduitM i o m) where
liftRedis = lift . liftRedis
instance (MonadIO m) => MonadIO (RedisT Connection m) where
liftIO = lift . liftIO
liftRedisT :: m a -> RedisT r m a
liftRedisT m = RedisT (const m) | ppp4ppp/test3 | src/Database/Redis/RedisT.hs | bsd-3-clause | 1,054 | 0 | 12 | 268 | 429 | 224 | 205 | 27 | 1 |
{-# LANGUAGE RecordWildCards #-}
module Math.Algebra.AbGroupPres.IsoClass (
IsoClass(..),
invariantFactorsToElementaryDivisors,
elementaryDivisorsToInvariantFactors
) where
import Data.List (intercalate, group, groupBy, sort, transpose)
import Data.Function (on)
data IsoClass = IsoClass
{
rank :: Integer,
torsion :: [(Integer, Integer)] -- Should be sorted prime + power pairs
} deriving (Eq)
instance Show IsoClass where
show IsoClass{..} =
if rank > 0 || length torsion > 0 then
intercalate " ⊕ " $ (replicate (fromIntegral rank) "ℤ") ++
fmap (\(prime, power) -> if power == 1 then
"ℤ/" ++ show prime
else
"ℤ/(" ++ show prime ++ "^" ++ show power ++ ")"
) torsion
else
"0"
factorsOf :: Integer -> [Integer]
factorsOf = f (head primes) (tail primes) where
f n ns m
| m < 2 = []
| m < n^2 = [m]
| m `mod` n == 0 = n : f n ns (m `div` n)
| otherwise = f (head ns) (tail ns) m
primes :: [Integer]
primes = 2 : filter (\n -> head (factorsOf n) == n) [3,5..]
splitFactors :: Integer -> [(Integer, Integer)]
splitFactors = fmap (\gp -> (head gp, fromIntegral $ length gp)) . group . factorsOf
invariantFactorsToElementaryDivisors :: [Integer] -> [(Integer, Integer)]
invariantFactorsToElementaryDivisors factors = sort $ factors >>= splitFactors
elementaryDivisorsToInvariantFactors :: [(Integer, Integer)] -> [Integer]
elementaryDivisorsToInvariantFactors = reverse .
fmap (product . fmap (\(prime, power) -> prime^power)) .
transpose .
fmap reverse .
groupBy ((==) `on` fst)
| mvr/at | src/Math/Algebra/AbGroupPres/IsoClass.hs | bsd-3-clause | 1,910 | 0 | 16 | 661 | 605 | 332 | 273 | 39 | 1 |
{-|
Module : AERN2.Real
Description : Exact real numbers
Copyright : (c) Michal Konecny
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : portable
Exact real numbers represented by Cauchy sequences of MPBalls.
-}
module AERN2.Real
(
-- * real numbers and conversions
CReal,
CSequence (..),
creal, HasCReals, CanBeCReal,
cseqPrecisions, cseqIndexForPrecision,
cseqFromWithCurrentPrec, cseqFromPrecFunction,
pi,
crealFromWithCurrentPrec, crealFromPrecFunction,
-- * limits
HasLimits(..),
-- * lazy Kleeneans
CKleenean, CanBeCKleenean, ckleenean, CanSelect(..),
-- * extracting approximations
CanExtractApproximation(..), (?), bits, prec,
-- * abstract real numbers
RealNumber
)
where
import AERN2.Limit
import AERN2.Select
import AERN2.MP
import AERN2.MP.WithCurrentPrec
import AERN2.Real.Type
import AERN2.Real.Comparisons ()
import AERN2.Real.CKleenean
import AERN2.Real.Field ()
import AERN2.Real.Limit ()
import AERN2.Real.Elementary (pi)
-- import AERN2.Real.Tests ()
import MixedTypesNumPrelude
-- import qualified Prelude as P
import GHC.TypeLits
-- import Text.Printf
-- -- import AERN2.MP.Dyadic
class
(OrderedField r
, HasLimits Int r
, HasLimits Integer r
, HasLimits Rational r
, CanSelect (OrderCompareType r r)
, (CanTestCertainly (SelectType (OrderCompareType r r))))
=>
RealNumber r
instance RealNumber CReal
instance
(KnownNat p) =>
RealNumber (WithCurrentPrec p (CN MPBall))
| michalkonecny/aern2 | aern2-real/src/AERN2/Real.hs | bsd-3-clause | 1,582 | 0 | 10 | 325 | 294 | 181 | 113 | -1 | -1 |
;
; HSP help managerp HELP\[Xt@C
; (檪u;vÌsÍRgƵijêÜ·)
;
%type
à ½ß
%ver
3.5
%note
ver3.5W½ß
%date
2016/07/13
%author
onitama
%url
http://hsp.tv/
%port
Win
Cli
Let
%index
getstr
obt@©ç¶ñÇÝoµ
%group
¶ñì½ß
%prm
p1,p2,p3,p4,p5
p1=Ï : àeðÇÝo·æÌϼ
p2=Ï : obt@ðèĽϼ
p3=0` : obt@ÌCfbNX(BytePÊ)
p4=0`255 : æØèLN^ÌASCIIR[h
p5=0`(1024) : ÇÝoµðsȤÅå¶
%inst
ãÌobt@ÌCÓÌêÉ éàeð¶ñƵÄÏÉÇÝoµÜ·B
¶ñÍA00Æ¢¤R[h©AüsR[hª éÜÅÇÝo³êÜ·BüsR[hͶñÉÍÜÜêܹñB
^
ܽAæØèLN^R[hðwè·é±ÆªÅ«CÓÌ¶ÅæØçê½¶ñðæèo·±ÆàūܷB
^
±Ì½ßÅÇÝo³ê½ByteÍ©®IÉ strsizeÆ¢¤VXeÏÉãü³êÜ·BstrsizeÍAÌCfbNXÜÅÌÚ®Êð¾éÉgpµÜ·B
^
½Æ¦ÎAÏbÌobt@É'A' 'B' 'C' ',' 'D' 'E' 'F' 00(I¹R[h)Æ¢¤f[^ªüÁÄ¢éêA
^p
getstr a,b,0,','
^p
ðÀs·éÆAÏaÌàeÍA'A' 'B' 'C' ̪ªÇÝo³êÄ"ABC"Æ¢¤¶ñÉÈèAstrsize Í4ÉÈèÜ·B
^
p5p[^[ÉæèAÇÝoµðsȤÅå¶(byte)ðwè·é±ÆªÅ«Ü·B
p5p[^[ªÈª³ê½êÉÍA1024¶(byte)ÜÅÌÇÝoµðsȢܷB
(p1Åwè³ê½ÏÌobt@Í©®IÉmÛ³êéÌÅAsdim½ßÅobt@ÌÝèðsÈÁĨKvÍ èܹñB)
^
±Ì½ßÍA¡sðÜÞeLXg¶ñf[^âAÁèÌ¶ÅæØçê½f[^ðø¦æØèo·½ßÌàÌÅ·B
¡sðÜÞeLXg𵤽ßÉÍA¼Éàm[gpbh½ßZbgª èÜ·BܽA¶ñ©çÁè̶ðæèo·½ßÉÍAstrmid½ßªpÓ³êĢܷB
%href
strmid
%index
noteadd
wèsÌÇÁEÏX
%group
¶ñì½ß
%prm
p1,p2,p3
p1=¶ñ : ÇÁEÏXð·é¶ñܽÍϼ
p2=0`(-1) : ÇÁ·éCfbNX
p3=0`1(0) : ã«[hwè(0=ÇÁE1=ã«)
%inst
m[gpbhÌàeðÇÁEÏXµÜ·B
^
p1ÉÇÁEÏX·é½ß̶ñðwèµÜ·Bp2ÅAÎÛÆÈéCfbNXðwèµÜ·B
p2p[^ðȪ·é©A-1ðwè·éÆÅIsªÎÛÉÈèÜ·B
p3p[^ÅAÇÁ©ã«©ðwèµÜ·BȪ·é©A0ðwè·éÆAÇÁ[hÆÈèAÎÛÆÈéCfbNXÈ~ªPÂÃÂVtgµÜ·B
p3ª1ÌêÍAã«[hÆÈèA ÎÛÆÈéCfbNXÌàeÍÁ³êAwèµ½¶ñÉu«·¦çêÜ·B
^
noteaddÍA Ïobt@Ésdim½ßÈÇÅ ç©¶ßmÛ³ê½eÊð´¦ÄàeðÇÁµæ¤Æµ½êÍA©®IÉmÛeÊðÁ³¹Äi[µÜ·B
ÂÜèAusdim a,64v ÅUS¶Üŵ©L¯Å«È¢obt@Å ÁÄàAÇÁ·éTCYɶĩ®IÉTCYð²ßµÄÀSÉL¯³¹é±ÆªÅ«Ü·B
^
m[gpbh½ß(noteget,noteadd,notedel,noteinfo)ðgp·é½ßÉÍAÅÉnotesel½ßÅÎÛÆÈéobt@ðÝèµÈ¯êÎÈèܹñB
%href
notesel
%sample
sdim a,10000
notesel a
noteadd "newidx1"
noteadd "newidx3"
noteadd "newidx2",1
mes a
stop
%index
notedel
sÌí
%group
¶ñì½ß
%prm
p1
p1=0` : í·éCfbNX
%inst
m[gpbhÌwèµ½CfbNXðíµÜ·B
p1Åwèµ½CfbNXÌàeÍí³êAÈ~ÌCfbNXªPÂÃÂVtgµÜ·B
^
m[gpbh½ß(noteget,noteadd,notedel,noteinfo)ðgp·é½ßÉÍAÅÉnotesel½ßÅÎÛÆÈéobt@ðÝèµÈ¯êÎÈèܹñB
%href
notesel
%index
noteget
wèsðÇÝÝ
%group
¶ñì½ß
%prm
p1,p2
p1=Ï : ÇÝoµæÌϼ
p2=0`(0) : ÇÝo·CfbNX
%inst
m[gpbhàÌAp2Åwèµ½CfbNXÌàeðp1Åwè³ê½ÏÉãüµÜ·Bm[gpbhàÌCÓÌsÉ éàeðÇÝo·±ÆªÅ«Ü·B
^
CfbNXÍ0©çnÜéÌÅӵľ³¢B
p1Åwè·éÏÉÍAÏobt@Ésdim½ßÈÇÅ ç©¶ßmÛ³ê½eÊð´¦ÄàeðÇÁµæ¤Æµ½êÍA©®IÉmÛeÊðÁ³¹Äi[µÜ·BܽAp1ÌÏͧIɶñ^ÉÏX³êÜ·B
^
m[gpbh½ß(noteget,noteadd,notedel,noteinfo)ðgp·é½ßÉÍAÅÉnotesel½ßÅÎÛÆÈéobt@ðÝèµÈ¯êÎÈèܹñB
%href
notesel
%sample
a="idx0\nidx1\nidx2"
notesel a
noteget b,1
mes b
stop
%index
noteinfo
m[gpbhîñæ¾
%group
¶ñìÖ
%prm
(p1)
p1(0) : îñæ¾[h
%inst
noteinfoÖÍA»ÝÎÛÆÈÁÄ¢ém[gpbhÉ¢ÄÌîñðæ¾µÜ·B
p1Åîñæ¾[hðwèµÜ·BܽA»ê¼êÌ[hÉε½}Nªè`³êĢܷB
^p
[h : }N àe
-----------------------------------------------------------
0 : notemax SÌÌs
1 : notesize SÌ̶(oCg)
^p
notemax}NÍA ¡s̶ñÅ·×ÄÌsÉεÄJèÔµðsÈ¢½¢êÈÇÉgpµÜ·B
SÌÌsÆÍAÂÜèm[gpbhàÉ évfÌÅ·B
uAPPLEvuORANGEvuGRAPEvÆ¢¤sª éêÉÍA3ÉÈèÜ·B
±ÌêACfbNXÍ0`2ÜÅÉÈèÜ·B
^
m[gpbh½ß(noteget,noteadd,notedel,noteinfo)ðgp·é½ßÉÍAÅÉnotesel½ßÅÎÛÆÈéobt@ðÝèµÈ¯êÎÈèܹñB
%href
notesel
noteget
notedel
notemax
notesize
%sample
nmax=0
notesel a
noteload "aaa.txt"
idx=0
repeat notemax
noteget b,idx
print "index"+idx+"="+b
idx++
loop
stop
%index
notesel
ÎÛobt@wè
%group
¶ñì½ß
%prm
p1
p1=Ï : obt@ðèĽϼ
%inst
p1Åwèµ½Ïðm[gpbh½ßÌobt@ÉÝèµÜ·B
^
p1Åwèµ½ÏÍA§Iɶñ^ÉÏX³êÜ·B
¼Ìm[gpbh½ß(noteget,noteadd,notedel,noteinfo)ðgp·é½ßÉÍAÅÉ notesel½ßÅÎÛÆÈéobt@ðÝèµÈ¯êÎÈèܹñB
%href
noteunsel
noteget
noteadd
notedel
noteinfo
notemax
notesize
notefind
%sample
notesel a
noteadd "test strings"
mes a
stop
%index
noteunsel
ÎÛobt@ÌA
%group
¶ñì½ß
%prm
%inst
noteunsel½ßÍAnotesel½ßÅÎÛÆÈéobt@ðÝè·éOÉÝè³êÄ¢½obt@ÝèÉߵܷB
noteunsel½ßÍK¸üêĨKvÍ èܹñªAnotesel½ßÅÝèµ½obt@ðg¢IíÁ½ãÉüêĨ±ÆÅAnoteselÉæéobt@w誽dÉsÈíê鱯ðh~µÜ·B
%href
notesel
%index
strmid
¶ñÌêðæèo·
%group
¶ñìÖ
%prm
(p1,p2,p3)
p1=ϼ : æèo·àÆÌ¶ñªi[³êÄ¢éϼ
p2=-1` : æèoµnßÌCfbNX
p3=0` : æèo·¶
%inst
p1Åwèµ½¶ñ^ÏÌ©çA p2,p3Åwèµ½ðŶðæèoµ½àÌðԵܷB
p2ÅæèoµnßéCfbNXðwèµÜ·B±êÍA¶ñÌnÜèP¶Úð0ƵÄA1,2,3...ÆÔɦĢàÌÅ·B1©çnÜèÅÍÈ¢ÌÅӵľ³¢B
p3Åæèo·¶ðwèµÜ·BÀÛÉi[³êĢ鶿èà½wèµ½êÍAÀÛ̶ÜŪæèo³êÜ·B
ܽAp2É-1ðwè·éƶñÌE©çp3Åwèµ½¶¾¯æèoµÜ·B
%sample
b="ABCDEF"
a=strmid(b,-1,3) ; E©çR¶ðæèo·
a=strmid(b,1,3) ; ¶©çQ¶Ú©çR¶ðæèo·
%href
getstr
%index
instr
¶ñÌõð·é
%group
¶ñìÖ
%prm
(p1,p2,"string")
p1=ϼ : õ³êé¶ñªi[³êÄ¢é¶ñ^ϼ
p2=0`(0) : õðnßéCfbNX
"string" : õ·é¶ñ
%inst
p1Åwèµ½¶ñ^ÏÌÉA"string"Åwèµ½¶ñª é©Ç¤©²×ÄACfbNXðԵܷB
^
wèµ½¶ñª©Â©Á½êÉÍACfbNXlªÔ³êÜ·B±êÍA¶ñÌnÜèP¶Úð0ƵÄA1,2,3...ÆÔɦĢàÌÅ·(strmid½ßÅwè·éCfbNXƯlÅ·)B
1©çnÜèÅÍÈ¢ÌÅӵľ³¢B
(p2ðwèµ½êACfbNXÍp2ðN_(0)Æ·éàÌÉÈèÜ·B)
(p2ª}CiXlÌêÍíÉ-1ªÔ³êÜ·B)
àµAwèµ½¶ñª©Â©çÈ©Á½êÉÍ-1ªÔ³êÜ·B
%href
strmid
strrep
notefind
%index
notesave
ÎÛobt@Û¶
%group
¶ñì½ß
%prm
"filename"
"filename" : «Ýt@C¼
%inst
m[gpbh½ßÌobt@Ìàeðwèµ½t@CÉeLXgt@CƵÄÛ¶µÜ·B
K¸ÅÉnotesel½ßÅÎÛÆÈéobt@ðÝè·éKvª éÌÅӵľ³¢B
notesave½ßÍAwèobt@ÉÜÜêé¶ñÌ·³ÅÛ¶µÜ·B
%href
notesel
noteload
noteget
noteadd
notedel
noteinfo
%port-
Let
%index
noteload
ÎÛobt@ÇÝÝ
%group
¶ñì½ß
%prm
"filename",p1
"filename" : ÇÝÝt@C¼
p1(-1) : ÇÝÝTCYÌãÀl
%inst
wèµ½t@Cðm[gpbh½ßÌobt@ÉÇÝÝÜ·B
ÊíÍAeLXgt@CðÇÝÝAm[gpbh½ßÅÇÝo·ÎÛÆµÜ·B
m[gpbh½ßÌobt@ÍA©®IÉt@CÌTCYÉ]ÁÄmÛTCYª²ß³êé½ßAobt@ÌTCYð ç©¶ßwèµÄ¨KvÍ èܹñB
p1ÅAÇÝÞt@CÌÅåTCYðwè·é±ÆªÅ«Ü·B
wèðȪܽÍ}CiXlɵ½êÍAÇñÈTCYÅàÇÝÝÜ·B
eLXgt@CÈOÌt@CðÇÝÞ±ÆàÂ\Å·B
K¸ÅÉnotesel½ßÅÎÛÆÈéobt@ðÝè·éKvª éÌÅӵľ³¢B
%href
notesel
notesave
noteget
noteadd
notedel
noteinfo
notemax
notesize
notefind
%index
getpath
pXÌêðæ¾
%group
¶ñìÖ
%prm
(p1,p2)
p1=¶ñ : æèo·³Ì¶ñ
p2=0` : îñÌ^Cvwè
%inst
p1Åwèµ½t@CpX𦷶ñðp2Åwèµ½^CvÌîñÉÏ·µ½àÌð¶ñƵÄԵܷB
^p
á :
a="c:\\disk\\test.bmp"
b = getpath(a,8+1)
mes b
«(Ê)
"test"ÆÈé
^p
^CvwèÌÚ×ÍȺÌÊèÅ·B
^p
^Cv : àe
-----------------------------------------------------------
0 : ¶ñÌRs[(ìȵ)
1 : g£qðt@C¼
2 : g£qÌÝ(.???)
8 : fBNgîñðæè
16 : ¶ñð¬¶ÉÏ··é
32 : fBNgîñÌÝ
^p
^CvlÍAv·é±ÆÅ¡wèðsȤ±ÆªÂ\Å·B
^Cv16ªwè³ê½êÍA·×ÄÌp¶ñð¬¶ÉÏ·µÜ·B
%href
getstr
instr
%index
strf
®t«¶ñðÏ·
%group
¶ñìÖ
%prm
("format",p1...)
"format" : ®wè¶ñ
p1 : ®wèp[^[
%inst
®Ü½ÍÀlðKØÈ®Å¶ñÉÏ·µ½¶ñðԵܷB
"format"ÅAÈºÌæ¤È®wè¶ñðwèµÜ·B
^p
á :
a=123
mes strf("10i[%d]",a)
mes strf("16i[%x]",a)
mes strf("10i
wèt«[%05d]",a)
mes strf("16i
wèt«[%05x]",a)
a=sqrt(2)
mes strf("10iÀ[%f]",a)
mes strf("10iÀ
wèt«[%3.10f]",a)
^p
p1È~Åwèµ½p[^[𦷪ÉÍAu%vɱwèðsȢܷB
u%dvÍ®lðAu%xvÍPUi®lðAu%cvͶR[hAu%fvÍÀlð»ê¼ê\¦³¹é±ÆªÅ«Ü·B
¡Ìp[^[ð®Åwèµ½êÍA»Ì¾¯u,vÅæØÁÄp[^[ð±¯ÄLqµÄ¾³¢B
ÊíÌu%vLð\¦µ½¢êÍAu%%vðwèµÄ¾³¢B
^p
á :
a=1:b=2.0:c="ABC"
mes strf("[%03d] [%f] [%s]",a,b,c)
^p
®wè¶ñÍAC^CCuªT|[gµÄ¢ésprintfÌ®ÆÙÚ¯lÅ·B
^p
%[width][.precision][I64]type
width : oÍ·éŬ¶
precision : oÍ·éÅå¶
(typeªfÌêͬ_ȺÌ
)
I64 : 64bitlð¦·vtBbNX
type : üͳêép[^[Ì^
^p
Ìæ¤È`®ÆÈèA[]àÌLqÍȪ·é±ÆªÂ\Å·B
typeÅwèÂ\ȶÍȺÌÊèÅ·B
^p
¶ àe
---------------------------------------------
c 1oCg¶R[h
d t« 10 i®
i t« 10 i®
u ȵ 10 i®
o ȵ 8 i®
x ȵ 16 i®(¬¶)
X ȵ 16 i®(å¶)
e [sign]dd[d] `®Ìt«ÌÀl
E [sign]dd[d] `®Ìt«ÌÀl(å¶)
f dddd.dddd `®Ìt«ÌÀl
(®Ì
ÍA»ÌlÌâÎlÉæÁÄè³êA
¬Ì
Ív³êé¸xÉæÁÄè³êÜ·B)
g ®fܽÍeÅoͳêét«Ìl̤¿A
wè³ê½l¨æÑ¸xð\»Å«éZ¢ûÌ®
G ®GƯlÅå¶ðgp·é
p 16iÌøªw·AhXðo͵ܷ
s ¶ñ
^p
®wè¶ñÍA1023¶ÜÅ̶ñÌÝF¯³êÜ·ÌÅӵľ³¢B
%href
mes
print
%index
cnvwtos
unicodeðÊí¶ñÉÏ·
%group
¶ñìÖ
%prm
(p1)
p1=Ï : àeðÇÝo·³Ìϼ
%inst
ÏÉÛ¶³ê½f[^ðunicode(UTF-16)ƵÄÇÝæèA Êí̶ñÉÏ·µ½àÌðԵܷB
unicodef[^ðµ¤êâAODLLA COMIuWFNgÆÌf[^Ï·ÈÇÅgp·é±ÆªÅ«Ü·B
%href
cnvstow
cnvstoa
cnvatos
str
%port-
Let
%index
cnvstow
Êí¶ñðunicodeÉÏ·
%group
¶ñì½ß
%prm
p1,"string"
p1=Ï : Êð«Þϼ
"string" : Ï·³Ì¶ñ
%inst
"¶ñ"Åwè³ê½f[^ðunicode(UTF-16)¶ñÉÏ·µÄÏobt@ÉÛ¶µÜ·B
p1Åwè³êéÏÉÍA ç©¶ß¶ñ^ƵÄÏ·É\ªÈobt@TCYðm۵ĨKvª èÜ·B
unicodef[^ðµ¤êâAODLLA COMIuWFNgÖÌf[^Ï·ÈÇÅgp·é±ÆªÅ«Ü·B
%href
cnvwtos
cnvstoa
cnvatos
str
%port-
Let
%index
strtrim
wèµ½¶¾¯ðæè
%group
¶ñìÖ
%prm
(p1,p2,p3)
p1=Ï : ³Ì¶ñªãü³ê½Ï
p2=0`3(0) : ·éÊuÌwè
p3=0`65535(32) : ¶R[h
%inst
p1Åwèµ½ÏÉi[³êÄ¢é¶ñÌ©çwèµ½¶¾¯ðæè«Ü·B
p2ÅA·éÊuÌwèðsȤ±ÆªÅ«Ü·B
p2ªÈª³ê½êÍA¶ñ̼[ªwè¶¾Á½êÌݳêÜ·B
p3Å·é¶R[hðwè·é±ÆªÅ«Ü·B
p3ªÈª³ê½êÍA¼pXy[X(32)ÆÈèÜ·B
^p
á :
a=" ABC DEF "
b = strtrim(a,0,' ')
mes b
^p
p2Åwè·éAÊuð¦·lÌÚ×ÍȺÌÊèÅ·B
^p
^Cv : àe
-----------------------------------------------------------
0 : ¼[É éwè¶ð·é(ftHg)
1 : ¶[É éwè¶ð·é
2 : E[É éwè¶ð·é
3 : ¶ñàÉ é·×ÄÌwè¶ð·é
^p
p3Åwè·é¶R[hÉÍASp¶ð¦·2oCgR[hðwè·é±ÆªÅ«Ü·B
^p
á :
s="@±ñÉ¿Í@Sp¶Å·@"
zenspace="@" ; SpXy[X
code = wpeek(zenspace,0) ; SpXy[XÌR[hðæ¾
mes strtrim(s,3,code)
^p
%href
strmid
instr
%index
split
¶ñ©çª³ê½vfðãü
%group
¶ñì½ß
%prm
p1,"string",p2...
p1=Ï : ³Ì¶ñªãü³ê½Ï
"string" : æØèp¶ñ
p2=Ï : ª³ê½vfªãü³êéÏ
%inst
wèµ½¶ñŪ³ê½vfðÏÉãüµÜ·B
½Æ¦ÎAu12,34,56vÌæ¤Éu,vÅæØçê½¶ñ©çAu12vu34vu56vÌvfðæèoµÄAÊXÌÏÉãü·é±ÆªÅ«Ü·B
p1ÅAàÆÌ¶ñªãü³ê½Ï¼ðwèµÜ·B(ÏÍA¶ñ^Å éKvª èÜ·)
"string"ÉæØé½ß̶ñðwèµÜ·B
p2È~ÉAª³ê½vfªãü³êéϼðwèµÜ·B
ãü³êéÏÍAu,vÅæØÁÄ¢ÂÅàwè·é±ÆªÅ«Ü·B
ÅÉw赽ϩçÔÉAª³ê½vfªãü³êÜ·B
^p
á :
buf="12,34,56"
split buf, ",", a, b, c
mes a
mes b
mes c
^p
wè³ê½ÏÌæèàAàÆàÆÌvf̪ȢêÍAcèÌÏÉó̶ñ("")ªãü³êÜ·B
wè³ê½ÏÌæèàAª³ê½vfª½¢êÍAwè³ê½ÏÌzñÉãü³êÄ¢«Ü·B
^p
á :
buf="12,34,56,78"
split buf, ",", results
repeat stat
mes "zñ("+cnt+")="+results(cnt)
loop
^p
ÀsãÉAVXeÏstatɪū½ªãü³êÜ·B
%href
getstr
csvnote
%port-
Let
%index
strrep
¶ñÌu·ð·é
%group
¶ñì½ß
%prm
p1,"õ¶ñ","u·¶ñ"
p1=ϼ : õ³êé¶ñªi[³êÄ¢é¶ñ^ϼ
"õ¶ñ" : õ·é¶ñ
"u·¶ñ" : u··é¶ñ
%inst
p1Åwèµ½¶ñ^ÏÌàe·×Äɨ¢ÄA
"õ¶ñ"Åwèµ½¶ñðA"u·¶ñ"Éu«·¦Ü·B
^
ÀsãAVXeÏstatɶñðu·µ½ñªãü³êÜ·B
%href
instr
%index
notefind
m[gpbhõ
%group
¶ñìÖ
%prm
("string",p1)
"string" : õ·é¶ñ
p1(0) : õ[h
%inst
»ÝÎÛÆÈÁÄ¢ém[gpbhÌ©çAÁè̶ñðÜÞsðõµÜ·B
p1Åõ[hðwèµÜ·B»ê¼êÌ[hÉε½}Nªè`³êĢܷB
^p
[h : }N àe
-----------------------------------------------------------
0 : notefind_match "string"Æ®SÉêvµ½sðõ
1 : notefind_first "string"ÅnÜésðõ
2 : notefind_instr "string"ðÜÞsðõ
^p
m[gpbhÌ·×ÄÌs©çAwè³ê½¶ñÆêv·és(CfbNX)ªßèlÆÈèÜ·B
õÉêv·ésªÈ¢êÍA-1ªÔ³êÜ·B
^
notefindÖðgp·é½ßÉÍAÅÉnotesel½ßÅÎÛÆÈéobt@ðÝèµÈ¯êÎÈèܹñB
%href
notesel
noteget
notedel
notemax
notesize
%index
cnvatos
ANSI¶ñðÊí¶ñÉÏ·
%note
hsp3utf.asðCN[h·é±ÆB
%group
¶ñìÖ
%prm
(p1)
p1=Ï : àeðÇÝo·³Ìϼ
%inst
ÏÉÛ¶³ê½f[^ðANSI(ShiftJIS)¶ñƵÄÇÝæèA Êí̶ñÉÏ·µ½àÌðԵܷB
±Ì½ßÍAUTF-8ðW̶ñR[hƵĵ¤^C(hsp3utf)ãÅÌÝ®ìµÜ·BWÌHSP3ÅÍG[ÆÈèÜ·ÌÅӵľ³¢B
%href
cnvstow
cnvwtos
cnvstoa
str
%port-
Let
%index
cnvstoa
Êí¶ñðANSI¶ñÉÏ·
%note
hsp3utf.asðCN[h·é±ÆB
%group
¶ñì½ß
%prm
p1,"string"
p1=Ï : Êð«Þϼ
"string" : Ï·³Ì¶ñ
%inst
"¶ñ"Åwè³ê½f[^ðANSI(ShiftJIS)¶ñÉÏ·µÄÏobt@ÉÛ¶µÜ·B
p1Åwè³êéÏÉÍA ç©¶ß¶ñ^ƵÄÏ·É\ªÈobt@TCYðm۵ĨKvª èÜ·B
±Ì½ßÍAUTF-8ðW̶ñR[hƵĵ¤^C(hsp3utf)ãÅÌÝ®ìµÜ·BWÌHSP3ÅÍG[ÆÈèÜ·ÌÅӵľ³¢B
%href
cnvstow
cnvwtos
cnvatos
str
%port-
Let
| zakki/openhsp | package/hsphelp/i_string.hs | bsd-3-clause | 17,870 | 6,849 | 14 | 2,085 | 14,311 | 8,361 | 5,950 | -1 | -1 |
{-
- 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 FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Data.Quantum.Circuit.QC (
GateToQCBuilder(..),
QCComponentId, QCComponent(..), Step(..), Item(..),
QCBuilder, runQCBuilder, runQCBuilderToBlazeBuilder) where
import Blaze.ByteString.Builder
import Blaze.ByteString.Builder.Char8
import Control.Applicative (Applicative)
import Control.Monad.State.Strict (StateT, evalStateT)
import qualified Control.Monad.State.Strict as State
import Control.Monad.Writer.Strict (Writer, runWriter)
import qualified Control.Monad.Writer.Strict as Writer
import Data.ByteString.Lazy (ByteString)
import qualified Data.Foldable as Foldable
import Data.Functor ((<$>))
import Data.Monoid (Monoid, (<>), mempty)
import Data.Sequence (Seq, (><))
import qualified Data.Sequence as Seq
import Data.Set (Set)
import qualified Data.Set as Set
import qualified System.IO as IO
import Data.Quantum.Circuit.Class (Wire(..), IsGate(..), Gate(..), IsCircuit(..))
import Util ((!))
type QCComponentId = Int
data QCComponent g = QCComponent !(Set Integer) !(Seq (Step g)) -- steps are run sequentially
newtype Step g = Step (Seq (Item g)) -- items are run in parallel inside each step
data Item g = IGate !(g Wire) | IComponent !QCComponentId !(Set Integer)
parallelSteps :: Step g -> Step g -> Step g
parallelSteps (Step items1) (Step items2) =
Step (items1 >< items2)
newtype QCBuilder g a = QCBuilder {
unwrapQCBuilder :: StateT QCComponentId (Writer (Seq (QCComponentId, QCComponent g))) a
} deriving (Functor, Applicative, Monad)
instance IsGate g => IsCircuit g Wire (QCBuilder g (QCComponent g)) where
empty =
return $ QCComponent Set.empty Seq.empty
{-# INLINABLE empty #-}
singleton g =
return $ QCComponent touched $ Seq.singleton $ Step $ Seq.singleton $ IGate g
where
touched = Set.fromList (getWire <$> Foldable.toList g)
{-# INLINABLE singleton #-}
newWire (Wire wi) _ = return $ QCComponent (Set.singleton wi) Seq.empty
{-# INLINABLE newWire #-}
ancilla (Wire wi) _ = return $ QCComponent (Set.singleton wi) Seq.empty
{-# INLINABLE ancilla #-}
sequential (QCBuilder m1) (QCBuilder m2) = QCBuilder $ do
QCComponent touched1 l1 <- m1
QCComponent touched2 l2 <- m2
return $ QCComponent (Set.union touched1 touched2) (l1 >< l2)
{-# INLINABLE sequential #-}
parallel (QCBuilder m1) (QCBuilder m2) = QCBuilder $ do
comp1@(QCComponent touched1 steps1) <- m1
comp2@(QCComponent touched2 steps2) <- m2
if not $ Set.null $ Set.intersection touched1 touched2 then
error "Circuit.QC.parallel: subcircuits touch the same wire"
else if Seq.null steps1 then
return comp2
else if Seq.null steps2 then
return comp1
else do
step1 <-
if Seq.length steps1 == 1 then
return $ steps1 ! 0
else do
compId1 <- State.get
State.put $! compId1 + 1
Writer.tell $! Seq.singleton (compId1, comp1)
return $ Step $ Seq.singleton $ IComponent compId1 touched1
step2 <-
if Seq.length steps2 == 1 then
return $ steps2 ! 0
else do
compId2 <- State.get
State.put $! compId2 + 1
Writer.tell $! Seq.singleton (compId2, comp2)
return $ Step $ Seq.singleton $ IComponent compId2 touched2
return $ QCComponent (Set.union touched1 touched2) $ Seq.singleton $ parallelSteps step1 step2
{-# INLINABLE parallel #-}
class GateToQCBuilder g where
gateToQCBuilder :: g Wire -> Builder
instance GateToQCBuilder Gate where
gateToQCBuilder (GateX (Wire wi)) =
fromString "tof " <> fromShow wi
gateToQCBuilder (GateXC (Wire wi) (Wire wi1) neg1) =
fromString "tof " <> fromShow wi1 <> (if neg1 then fromChar '\'' else mempty) <> fromChar ' ' <> fromShow wi
gateToQCBuilder (GateXCC (Wire wi) (Wire wi1) neg1 (Wire wi2) neg2) =
fromString "tof " <>
fromShow wi1 <> (if neg1 then fromChar '\'' else mempty) <> fromChar ' ' <>
fromShow wi2 <> (if neg2 then fromChar '\'' else mempty) <> fromChar ' ' <> fromShow wi
gateToQCBuilder (GateH (Wire wi)) =
fromString "H " <> fromShow wi
gateToQCBuilder (GateY (Wire wi)) =
fromString "Y " <> fromShow wi
gateToQCBuilder (GateZ (Wire wi)) =
fromString "Z " <> fromShow wi
gateToQCBuilder (GateS (Wire wi) False) =
fromString "P " <> fromShow wi
gateToQCBuilder (GateS (Wire wi) True) =
fromString "P* " <> fromShow wi
gateToQCBuilder (GateT (Wire wi) False) =
fromString "T " <> fromShow wi
gateToQCBuilder (GateT (Wire wi) True) =
fromString "T* " <> fromShow wi
runQCBuilder :: (IsGate g, GateToQCBuilder g) => IO.Newline -> QCBuilder g (QCComponent g) -> ByteString
runQCBuilder nl = toLazyByteString . runQCBuilderToBlazeBuilder newlineBuilder
where
newlineBuilder =
case nl of
IO.LF -> fromChar '\n'
IO.CRLF -> fromString "\r\n"
{-# INLINABLE runQCBuilder #-}
runQCBuilderToBlazeBuilder :: GateToQCBuilder g => Builder -> QCBuilder g (QCComponent g) -> Builder
runQCBuilderToBlazeBuilder nl circuit =
fromString ".v " <> vars <> nl <>
fromString ".i " <> vars <> nl <>
fromString ".o " <> vars <> nl <>
fromString ".ol " <> vars <> nl <>
Foldable.foldMap (uncurry (subcomponentToQCBuilder nl)) subcomps <>
fromString "BEGIN" <> nl <>
stepsToQCBuilder nl mainSteps <>
fromString "END" <> nl
where
(QCComponent mainTouched mainSteps, subcomps) =
runWriter $ evalStateT (unwrapQCBuilder circuit) 0
vars =
touchedToQCBuilder mainTouched
{-# INLINABLE runQCBuilderToBlazeBuilder #-}
subcomponentToQCBuilder :: GateToQCBuilder g => Builder -> QCComponentId -> QCComponent g -> Builder
subcomponentToQCBuilder nl compId (QCComponent touched steps) =
fromString "BEGIN C" <> fromShow compId <> fromChar '(' <> touchedToQCBuilder touched <> fromChar ')' <> nl <>
stepsToQCBuilder nl steps <>
fromString "END C" <> fromShow compId <> nl
stepsToQCBuilder :: GateToQCBuilder g => Builder -> Seq (Step g) -> Builder
stepsToQCBuilder nl =
Foldable.foldMap (\step -> stepToQCBuilder step <> nl)
where
stepToQCBuilder (Step items) =
builderFromList (fromChar ';') itemToQCBuilder (Foldable.toList items)
itemToQCBuilder (IGate g) = gateToQCBuilder g
itemToQCBuilder (IComponent compId touched) =
fromChar 'C' <> fromShow compId <> fromChar ' ' <> touchedToQCBuilder touched
touchedToQCBuilder :: Set Integer -> Builder
touchedToQCBuilder =
builderFromList (fromChar ' ') fromShow . Set.toAscList
builderFromList :: Builder -> (a -> Builder) -> [a] -> Builder
builderFromList _ _ [] = mempty
builderFromList separator build (x : xs) = go x xs
where
go y [] = build y
go y (y' : ys) = build y <> separator <> go y' ys
| ti1024/hacq | src/Data/Quantum/Circuit/QC.hs | bsd-3-clause | 7,149 | 0 | 22 | 1,558 | 2,253 | 1,157 | 1,096 | 150 | 2 |
module Handler.Admin
( getAdminR
, postAdminR
) where
import Import
import Utils
import qualified Handler.Media as Media (adminWidget)
getAdminR :: Handler Html
getAdminR = do
at <- (liftM2 (,) `on` lookupGetParam) "action" "target"
case at of
(Just "noapprove_user", Just u) -> setApprove u False >> redirect AdminR
(Just "approve_user" , Just u) -> setApprove u True >> redirect AdminR
(Just "update_media" , _) -> giveUrlRenderer mempty
(Just _,_) -> invalidArgs ["Unknown action!"]
( _,_) -> do
(formWidget, encType) <- generateFormPost newboardForm
let form = renderFormH $ myForm
MsgBoardCreate encType AdminR
formWidget (submitButtonI MsgBoardCreate) FormMissing
users <- runDB $ selectList [] [Asc UserUsername]
defaultLayout $ do
navigation "Admin"
setTitle "Adminstration"
$(widgetFile "admin")
where
(disapprove, approve) = ("disapprove_user", "approve_user") :: (Text, Text)
usert = ((,,) <$> userUsername
<*> userComment
<*> (\v -> if' (userValid v) disapprove approve)
) . entityVal
setApprove name value = runDB $
updateWhere [UserUsername ==. name] [UserValid =. value]
postAdminR :: Handler Html
postAdminR = do
((result, _), _) <- runFormPost newboardForm
case result of
FormSuccess board -> do
void . runDB $ insert board
setMessage $ toHtml $ "New board added: " <> boardName board
_ -> setMessage "Something went wrong while creating the board"
redirect AdminR
newboardForm :: Form Board
newboardForm = renderBootstrap $ Board
<$> areq textField "Name" Nothing
<*> areq textField "Description" Nothing
| SimSaladin/rnfssp | Handler/Admin.hs | bsd-3-clause | 1,906 | 0 | 18 | 602 | 540 | 273 | 267 | 44 | 5 |
module Exercises1110 where
-- Exercises: Pity the Bool
-- 1. Cardinality: 4. Bool is 2 and sum type is addition.
-- 2. The cardinality is 2 + 256 = 258.
-- If you try to create a numeric literal less than -128
-- or greater than 127, you get an error:
-- "Literal 130 is out of the Int8 range -128..127"
-- needed to have Int8 in scope
import Data.Int
data NumberOrBool =
Numba Int8
| BoolyBool Bool deriving (Eq, Show)
-- Example use of Numba, parentheses due to
-- syntactic collision between (-) minus and
-- the negate function
-- let myNumba = Numba (-128) | pdmurray/haskell-book-ex | src/ch11/Exercises11.10.hs | bsd-3-clause | 595 | 0 | 6 | 139 | 45 | 31 | 14 | 5 | 0 |
{-# LANGUAGE FlexibleInstances, UndecidableInstances, DuplicateRecordFields #-}
module Main where
helloWorldNTimes :: [String] -> [String]
helloWorldNTimes xs = xs >>= (\s -> replicate (read s :: Int) "Hello World")
main :: IO ()
main = interact (unlines . helloWorldNTimes . lines)
| everyevery/programming_study | hackerrank/functional/HelloWorldNTimes/solution.hs | mit | 288 | 0 | 10 | 45 | 83 | 46 | 37 | 6 | 1 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
{- |
Module : ./HasCASL/MatchingWithDefinitions.hs
Description : matching of terms modulo definition expansion
Copyright : (c) Ewaryst Schulz, DFKI Bremen 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : non-portable (see extensions)
Matching of terms modulo constant definition expansion and constraints
-}
module HasCASL.MatchingWithDefinitions where
import HasCASL.Subst
import HasCASL.PrintSubst
import HasCASL.As
import HasCASL.Le
import HasCASL.PrintAs ()
import Common.Id
import Common.ConvertGlobalAnnos ()
import Common.Doc
import Common.DocUtils
import qualified Data.Map as Map
import qualified Data.Set as Set
-- For candidate generation and DG navigation
import Data.List
import Data.Maybe
import Static.DGNavigation
import Logic.Grothendieck
import Logic.Coerce
import HasCASL.Logic_HasCASL
{- | We need two classes:
1. A class for lookup definitions and checking for good functions
2. A class for storing the match (substitution plus constraints)
-}
class DefStore a where
isGood :: a -> Term -> Bool
isMapable :: a -> (Id, TypeScheme) -> Bool
getDefinition :: a -> (Id, TypeScheme) -> Maybe Term
getEnv :: a -> Env
logMsg :: a -> Doc -> IO ()
class Match a where
addMatch :: a -> SubstConst -> Term -> a
addConstraint :: a -> Term -> Term -> a
newtype DefinitionStore = DefinitionStore (Env, Set.Set Symbol)
initialDefStore :: Env -> Set.Set Symbol -> DefinitionStore
initialDefStore e syms = DefinitionStore (e, syms)
instance DefStore DefinitionStore where
isGood _ _ = True
isMapable (DefinitionStore (_, syms)) (opid, typ) =
Set.member (idToOpSymbol opid typ) syms
getDefinition (DefinitionStore (e, _)) = getOpDefinition e
getEnv (DefinitionStore (e, _)) = e
-- logMsg _ _ = return ()
logMsg def d = let e = getEnv def
in appendFile "/tmp/matcher.out" $ (++ "\n") $ show
$ useGlobalAnnos (globAnnos e) d
newtype MatchResult = MatchResult (Subst, [(Term, Term)]) deriving Show
getMatchResult :: MatchResult -> (Subst, [(Term, Term)])
getMatchResult (MatchResult x) = x
emptyMatchResult :: MatchResult
emptyMatchResult = MatchResult (emptySubstitution, [])
instance PrettyInEnv MatchResult where
prettyInEnv e (MatchResult (sb, ctrts)) =
vcat [ prettyInEnv e sb
, if null ctrts then empty else text "Constraints"
, prettyTermMapping e ctrts ]
instance Match MatchResult where
addMatch mr@(MatchResult (sb, ctrts)) sc t =
case lookupContent sb sc of
Just t' | t == t' -> mr
| otherwise ->
addConstraint mr t t'
_ -> MatchResult (addTerm sb sc t, ctrts)
addConstraint (MatchResult (sb, ctrts)) t1 t2 = MatchResult (sb, (t1, t2) : ctrts)
{- | The rules of matching:
f,g are functions
c is a constant
v is a variable
t1, t2 are arbitrary terms
"good" functions are the list-constructor, the solidworks datatype constructors and all other constructors.
f != g
1a. f(x_i) f(y_i) -> match x_i y_i, if f is a "good" function
AddConstraint f(x_i) = f(y_i), otherwise
1b. f(...) g(...) -> AddConstraint f(...) = g(...)
2a. c t2 -> match t1 t2, if c is defined by term t1
AddMatch c t2, if c is mapable
AddConstraint c = t2, otherwise
2b. t1 c -> match t1 t2, if c is defined by term t2
AddConstraint t1 = c, otherwise
3. v t2 -> AddMatch v t2
-}
match :: (DefStore d, Match a) => d -> a -> Term -> Term -> IO (Either String a)
match def mtch t1 t2 =
case (t1, t2) of
-- handle the 'skip-cases' first
(TypedTerm term _ _ _, _) -> match' term t2 -- logg "typed1" $ match' term t2
(_, TypedTerm term _ _ _) -> match' t1 term -- logg "typed2" $ match' t1 term
-- check for clash, handle constraints and definition expansion
(ApplTerm f1 a1 _, _) ->
case t2 of
ApplTerm f2 a2 _
-- 1a1.
| f1 == f2 && isGood def f1 -> logg msg1a1 $ match' a1 a2
-- 1a2., 1b.
| otherwise -> logg msg1a21b addLocalConstraint
-- eventually 2b.
_ -> logg msg2b tryDefExpand2
(TupleTerm l _, _) ->
case t2 of
TupleTerm l' _ | length l == length l' ->
logg msg1aT $ matchfold mtch $ zip l l'
| otherwise ->
logg "tclash" tupleClash
-- eventually 2b.
_ -> logg msg2bT tryDefExpand2
-- 3.: add the mapping v->t2 to output
(QualVar v, _) -> logg "mapped" $ addMapping v
-- 2a.: follow the definition of pattern
(QualOp _ (PolyId opid _ _) typ _ _ _, _) ->
logg msg2a $ tryDefExpand1 (opid, typ)
-- all other terms are not expected and accepted here
_ -> return $ Left "match: unhandled term"
where match' = match def mtch
{- The definition expansion application case
(for ApplTerm and TupleTerm) is handled uniformly -}
tryDefExpand1 oi = case getTermDef t1 of
Just t1' -> match' t1' t2
_ | isMapable def oi -> addMapping oi
| otherwise -> addLocalConstraint
tryDefExpand2 = case getTermDef t2 of
Just t2' -> match' t1 t2'
_ -> addLocalConstraint
getTermDef t = getTermOp t >>= getDefinition def
addLocalConstraint
-- Do not add constraints for equal terms
| t1 == t2 = return $ Right mtch
| otherwise = return $ Right $ addConstraint mtch t1 t2
addMapping t = return $ Right $ addMatch mtch (toSC t) t2
matchfold mtch' (x : l) = do
res <- uncurry (match def mtch') x
case res of
Right mtch'' -> matchfold mtch'' l
err -> return err
matchfold mtch' [] = return $ Right mtch'
-- clash = return $ Left $ "match: Clash for " ++ show (pretty (t1,t2))
tupleClash = return $ Left $ "match: Clash for tuples "
++ show (pretty (t1, t2))
-- Logging stuff
logg s a = do
let e = getEnv def
logMsg def $ text "Log" <+> text s
$++$ text "t1:" $+$ prettyInEnv e t1 $++$ text "t2:"
$+$ prettyInEnv e t2 $++$ text "==============="
a
msg1a1 = "1a1: good same function"
msg1a21b = "1a2, 1b: not good or not same function"
msg1aT = "1aT: tuple: same tuple"
msg2bT = "2bT:"
msg2a = "2a: pattern constant"
msg2b = "2b: term constant"
-- ----------------------- term tools -------------------------
getTermOp :: Term -> Maybe (Id, TypeScheme)
getTermOp (QualOp _ (PolyId opid _ _) typ _ _ _) = Just (opid, typ)
getTermOp _ = Nothing
getOpInfo :: Env -> (Id, TypeScheme) -> Maybe OpInfo
getOpInfo e (opid, typ) =
case Map.lookup opid (assumps e) of
Just soi ->
let fs = Set.filter f soi
in if Set.null fs then Nothing
else Just $ Set.findMin fs
_ -> Nothing
where
f oi = opType oi == typ
getOpDefinition :: Env -> (Id, TypeScheme) -> Maybe Term
getOpDefinition e t =
case fmap opDefn $ getOpInfo e t of
Just (Definition _ t') -> Just t'
_ -> Nothing
-- * Match Candidates
-- ** 1. Injections
newtype Injection a b = Injection [(a, b)]
instance (Show a, Show b) => Show (Injection a b) where
show (Injection l) = "{" ++ intercalate ", " (map sf l) ++ "}"
where sf (x, y) = show x ++ " --> " ++ show y
toList :: Injection a b -> [(a, b)]
toList (Injection l) = l
insertMapping :: (a, b) -> Injection a b -> Injection a b
insertMapping p (Injection l) = Injection (p : l)
combine :: Injection a b -> Injection a b -> Injection a b
combine (Injection l) (Injection l') = Injection (l ++ l')
singleton :: (a, b) -> Injection a b
singleton p = Injection [p]
-- Build all injections from source list to target list
injections :: [a] -> [b] -> [Injection a b]
injections l l'
| length l > length l' = []
| otherwise =
case l of
[] -> [Injection []]
[x] -> [ singleton (x, y) | y <- l' ]
x : xl -> f [] l'
where
f a (y : b) = f (y : a) b ++
map (insertMapping (x, y)) (injections xl $ a ++ b)
f _ [] = []
crossInjs :: [[Injection a b]] -> [Injection a b]
crossInjs = crosscombine combine
-- Build all combinations from the list of lists
crosscombine :: (a -> a -> a) -> [[a]] -> [a]
crosscombine _ [] = []
crosscombine _ [x] = x
crosscombine f cl@(x : l)
| any null cl = []
| otherwise = [ f a b | a <- x, b <- crosscombine f l ]
-- ** 2. Candidates from operators
{- | Candidate generation
a. For a symbol set make a map from Types to 'MatchOp'-lists: 'typePartition'
b. From two such maps make a list of 'Injection's, each injection is a candidate
(a list of 'MatchOp' pairs, wich will be matched using their definitions):
'candidatesAux'
-}
type MatchOp = (Id, TypeScheme, Term)
instance PrettyInEnv MatchOp where
prettyInEnv e (opid, typ, t) = pretty opid <> text ":" <+> pretty typ
<+> text "=" <+> prettyInEnv e t
candType :: MatchOp -> TypeScheme
candType (_, typ, _) = typ
candTerm :: MatchOp -> Term
candTerm (_, _, t) = t
-- *** a.
typePartition :: ((Id, TypeScheme) -> Maybe Term) -- ^ Definiens extractor
-> (TypeScheme -> Bool) -- ^ Filter predicate for types
-> Set.Set Symbol -- ^ MatchOp symbol set
-> Map.Map TypeScheme [MatchOp]
typePartition df tPred s =
Map.fromListWith (++) $ mapMaybe g $ Set.toList s
where f x = let typ = candType x
in if tPred typ then Just (typ, [x]) else Nothing
g x = candFromSymbol df x >>= f
candFromSymbol :: ((Id, TypeScheme) -> Maybe Term) -- ^ Definiens extractor
-> Symbol -> Maybe MatchOp
candFromSymbol df (Symbol {symName = opid, symType = OpAsItemType typ}) =
fmap ((,,) opid typ) $ df (opid, typ)
candFromSymbol _ _ = Nothing
-- *** b.
candidatesAux :: Map.Map TypeScheme [MatchOp]
-> Map.Map TypeScheme [MatchOp]
-> [Injection MatchOp MatchOp]
candidatesAux patMap cMap = crossInjs $ Map.foldWithKey f [] patMap where
f typ l injL = let l' = Map.findWithDefault err typ cMap
err = error $ "candidates: No concrete ops for type: "
++ show (pretty typ)
in injections l l' : injL
candidates :: ((Id, TypeScheme) -> Maybe Term) -- ^ Definiens extractor
-> (TypeScheme -> Bool) -- ^ Filter predicate for types
-> Set.Set Symbol -> Set.Set Symbol -> [[(MatchOp, MatchOp)]]
candidates df tPred s1 s2 = map toList $ candidatesAux tp1 tp2
where (tp1, tp2) = (typePartition df tPred s1, typePartition df tPred s2)
-- ** 3. Matching of candidates
matchCandidate :: (DefStore d) => d -> [(MatchOp, MatchOp)]
-> IO (Either String MatchResult)
matchCandidate def = f emptyMatchResult where
f mtch [] = return $ Right mtch
f mtch ((pat, c) : l) = do
let e = getEnv def
logMsg def $ text "Matching Candidate Pattern"
$+$ prettyInEnv e pat $+$ text " with" $+$ prettyInEnv e c
res <- match def mtch (candTerm pat) $ candTerm c
case res of
Right mtch' -> f mtch' l
x -> return x
matchCandidates :: (DefStore d) => d -> [[(MatchOp, MatchOp)]]
-> IO (Either String MatchResult, [[(MatchOp, MatchOp)]])
matchCandidates _ [] = return (Left "matchCandidates: Out of candidates", [])
matchCandidates def (cand : l) = do
res <- matchCandidate def cand
case res of
Left _ -> matchCandidates def l
x -> return (x, l)
getCandidates :: (DefStore d, DevGraphNavigator nav) =>
d -> nav
-> (TypeScheme -> Bool) -- ^ Filter predicate for types
-> String -- ^ Name of pattern spec
-> String -- ^ Name of concrete spec
-> Maybe [[(MatchOp, MatchOp)]]
getCandidates def dgnav tFilter patN cN =
let
-- g s dgnav' = getInLibEnv dgnav' lookupLocalNodeByName s
g = getNamedSpec
f s = fromSearchResult (g s) getLocalSyms dgnav
mGp = f patN
mGc = f cN
pSyms = Set.map gsymToSym $ fromJust mGp
cSyms = Set.map gsymToSym $ fromJust mGc
cands = candidates (getDefinition def) tFilter pSyms cSyms
in if isJust mGp && isJust mGc then Just cands else Nothing
-- | Utility function for symbol conversion
gsymToSym :: G_symbol -> Symbol
gsymToSym (G_symbol lid sym) = coerceSymbol lid HasCASL sym
{- | The main matching function using specifications:
The pattern specification is expected to be a parameterized specification
containing the constants to be mapped in the actual parameter specification.
The candidates for the matching stem from those operators which have a
definition and a certain type satisfying the given type predicate.
A typical such predicate is:
'(flip elem ["typename1", "typename2", ...]) . show . pretty'
Only operators with the same type can be matched, and all possible
combinations of matching candidates are computed.
With the given Number (> 0) you can constrain the number of candidates to
try before giving up the matching (0 means all candidates).
If one candidate gives a correct match result the following candidates are
not tried and the 'MatchResult' is returned together with the list of non
tried candidates.
-}
matchSpecs :: (DefStore d, DevGraphNavigator nav) =>
d -> nav
-> (TypeScheme -> Bool) -- ^ Filter predicate for types
-> Int -- ^ Number of candidates to try
-> String -- ^ Name of pattern spec
-> String -- ^ Name of concrete spec
-> IO (Either String MatchResult, [[(MatchOp, MatchOp)]])
matchSpecs def dgnav tFilter n patN cN =
case getCandidates def dgnav tFilter patN cN of
Nothing -> return (Left "matchSpecs: specs not found.", [])
Just cl
| null cl ->
return (Left "matchSpecs: no candidates available.", [])
| otherwise -> do
let (cands, remC) = if n > 0 then splitAt n cl else (cl, [])
(mr, l) <- matchCandidates def cands
return (mr, l ++ remC)
| spechub/Hets | HasCASL/MatchingWithDefinitions.hs | gpl-2.0 | 15,049 | 0 | 16 | 4,698 | 4,036 | 2,073 | 1,963 | 251 | 13 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Lamdu.Data.Db.Layout
( DbM(DbM), runDbTransaction
, ViewM, runViewTransaction
, GuiAnchors, guiAnchors, guiIRefs
, CodeAnchors, codeAnchors, codeIRefs
, RevisionProps, revisionProps, revisionIRefs
, guiState
, dbSchemaVersion, curDbSchemaVersion
, module Lamdu.Data.Anchors
) where
import Control.Monad.IO.Class (MonadIO)
import Data.ByteString.Char8 ()
import GUI.Momentu.State (GUIState)
import Lamdu.Data.Anchors (Gui(..), Code(..), Revision(..))
import qualified Lamdu.Data.Anchors as Anchors
import Revision.Deltum.IRef (IRef)
import qualified Revision.Deltum.IRef as IRef
import Revision.Deltum.Rev.View (View)
import qualified Revision.Deltum.Rev.View as View
import Revision.Deltum.Transaction (Transaction)
import qualified Revision.Deltum.Transaction as Transaction
import Lamdu.Prelude
type T = Transaction
newtype DbM a = DbM { dbM :: IO a }
deriving newtype (Functor, Applicative, Monad, MonadIO)
newtype ViewM a = ViewM { viewM :: T DbM a }
deriving newtype (Functor, Applicative, Monad)
runDbTransaction :: Transaction.Store DbM -> T DbM a -> IO a
runDbTransaction store = dbM . Transaction.run store
runViewTransaction :: View DbM -> T ViewM a -> T DbM a
runViewTransaction v = viewM . (Transaction.run . Transaction.onStoreM ViewM . View.store) v
codeIRefs :: Code (IRef ViewM) ViewM
codeIRefs = Code
{ repl = IRef.anchor "repl"
, panes = IRef.anchor "panes"
, globals = IRef.anchor "globals"
, tags = IRef.anchor "tags"
, tids = IRef.anchor "tids"
}
guiIRefs :: Gui (IRef ViewM)
guiIRefs = Gui
{ preJumps = IRef.anchor "prejumps"
, preGuiState = IRef.anchor "preguistate"
, postGuiState = IRef.anchor "postguistate"
}
revisionIRefs :: Revision (IRef DbM) DbM
revisionIRefs = Revision
{ branches = IRef.anchor "branches"
, currentBranch = IRef.anchor "currentBranch"
, redos = IRef.anchor "redos"
, view = IRef.anchor "view"
}
type GuiAnchors = Anchors.GuiAnchors (T ViewM) (T ViewM)
type CodeAnchors = Anchors.CodeAnchors ViewM
type RevisionProps = Anchors.RevisionProps DbM
guiAnchors :: GuiAnchors
guiAnchors = Anchors.onGui Transaction.mkPropertyFromIRef guiIRefs
codeAnchors :: CodeAnchors
codeAnchors = Anchors.onCode Transaction.mkPropertyFromIRef codeIRefs
revisionProps :: RevisionProps
revisionProps = Anchors.onRevision Transaction.mkPropertyFromIRef revisionIRefs
guiState :: IRef DbM GUIState
guiState = IRef.anchor "guiState"
dbSchemaVersion :: IRef DbM Int
dbSchemaVersion = IRef.anchor "dbSchemaVersion"
curDbSchemaVersion :: Int
curDbSchemaVersion = 15
| lamdu/lamdu | src/Lamdu/Data/Db/Layout.hs | gpl-3.0 | 2,739 | 0 | 11 | 515 | 744 | 427 | 317 | -1 | -1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE UndecidableInstances #-}
-- | Monad class for caching of combined keys
module Network.Tox.Crypto.Keyed where
import Control.Monad.RWS (RWST)
import Control.Monad.Random (RandT)
import Control.Monad.Reader (ReaderT)
import Control.Monad.State (StateT)
import Control.Monad.Trans (lift)
import Control.Monad.Writer (WriterT)
import qualified Network.Tox.Crypto.CombinedKey as CombinedKey
import Network.Tox.Crypto.Key (CombinedKey, PublicKey,
SecretKey)
class (Monad m, Applicative m) => Keyed m where
getCombinedKey :: SecretKey -> PublicKey -> m CombinedKey
instance Keyed m => Keyed (ReaderT r m) where
getCombinedKey = (lift .) . getCombinedKey
instance (Monoid w, Keyed m) => Keyed (WriterT w m) where
getCombinedKey = (lift .) . getCombinedKey
instance Keyed m => Keyed (StateT s m) where
getCombinedKey = (lift .) . getCombinedKey
instance (Monoid w, Keyed m) => Keyed (RWST r w s m) where
getCombinedKey = (lift .) . getCombinedKey
instance Keyed m => Keyed (RandT s m) where
getCombinedKey = (lift .) . getCombinedKey
-- | trivial instance: the trivial monad, with no caching of keys
newtype NullKeyed a = NullKeyed { runNullKeyed :: a }
instance Functor NullKeyed where
fmap f (NullKeyed x) = NullKeyed (f x)
instance Applicative NullKeyed where
pure = NullKeyed
(NullKeyed f) <*> (NullKeyed x) = NullKeyed (f x)
instance Monad NullKeyed where
return = NullKeyed
NullKeyed x >>= f = f x
instance Keyed NullKeyed where
getCombinedKey = (NullKeyed .) . CombinedKey.precompute
| iphydf/hs-toxcore | src/Network/Tox/Crypto/Keyed.hs | gpl-3.0 | 1,874 | 0 | 9 | 487 | 494 | 277 | 217 | 38 | 0 |
{-# 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.STS.GetSessionToken
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns a set of temporary credentials for an AWS account or IAM user.
-- The credentials consist of an access key ID, a secret access key, and a
-- security token. Typically, you use 'GetSessionToken' if you want to use
-- MFA to protect programmatic calls to specific AWS APIs like Amazon EC2
-- 'StopInstances'. MFA-enabled IAM users would need to call
-- 'GetSessionToken' and submit an MFA code that is associated with their
-- MFA device. Using the temporary security credentials that are returned
-- from the call, IAM users can then make programmatic calls to APIs that
-- require MFA authentication.
--
-- The 'GetSessionToken' action must be called by using the long-term AWS
-- security credentials of the AWS account or an IAM user. Credentials that
-- are created by IAM users are valid for the duration that you specify,
-- between 900 seconds (15 minutes) and 129600 seconds (36 hours);
-- credentials that are created by using account credentials have a maximum
-- duration of 3600 seconds (1 hour).
--
-- We recommend that you do not call 'GetSessionToken' with root account
-- credentials. Instead, follow our
-- <http://docs.aws.amazon.com/IAM/latest/UserGuide/IAMBestPractices.html#create-iam-users best practices>
-- by creating one or more IAM users, giving them the necessary
-- permissions, and using IAM users for everyday interaction with AWS.
--
-- The permissions associated with the temporary security credentials
-- returned by 'GetSessionToken' are based on the permissions associated
-- with account or IAM user whose credentials are used to call the action.
-- If 'GetSessionToken' is called using root account credentials, the
-- temporary credentials have root account permissions. Similarly, if
-- 'GetSessionToken' is called using the credentials of an IAM user, the
-- temporary credentials have the same permissions as the IAM user.
--
-- For more information about using 'GetSessionToken' to create temporary
-- credentials, go to
-- <http://docs.aws.amazon.com/STS/latest/UsingSTS/CreatingSessionTokens.html Creating Temporary Credentials to Enable Access for IAM Users>.
--
-- /See:/ <http://docs.aws.amazon.com/STS/latest/APIReference/API_GetSessionToken.html AWS API Reference> for GetSessionToken.
module Network.AWS.STS.GetSessionToken
(
-- * Creating a Request
getSessionToken
, GetSessionToken
-- * Request Lenses
, gstTokenCode
, gstDurationSeconds
, gstSerialNumber
-- * Destructuring the Response
, getSessionTokenResponse
, GetSessionTokenResponse
-- * Response Lenses
, gstrsCredentials
, gstrsResponseStatus
) where
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
import Network.AWS.STS.Types
import Network.AWS.STS.Types.Product
-- | /See:/ 'getSessionToken' smart constructor.
data GetSessionToken = GetSessionToken'
{ _gstTokenCode :: !(Maybe Text)
, _gstDurationSeconds :: !(Maybe Nat)
, _gstSerialNumber :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'GetSessionToken' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gstTokenCode'
--
-- * 'gstDurationSeconds'
--
-- * 'gstSerialNumber'
getSessionToken
:: GetSessionToken
getSessionToken =
GetSessionToken'
{ _gstTokenCode = Nothing
, _gstDurationSeconds = Nothing
, _gstSerialNumber = Nothing
}
-- | The value provided by the MFA device, if MFA is required. If any policy
-- requires the IAM user to submit an MFA code, specify this value. If MFA
-- authentication is required, and the user does not provide a code when
-- requesting a set of temporary security credentials, the user will
-- receive an \"access denied\" response when requesting resources that
-- require MFA authentication.
gstTokenCode :: Lens' GetSessionToken (Maybe Text)
gstTokenCode = lens _gstTokenCode (\ s a -> s{_gstTokenCode = a});
-- | The duration, in seconds, that the credentials should remain valid.
-- Acceptable durations for IAM user sessions range from 900 seconds (15
-- minutes) to 129600 seconds (36 hours), with 43200 seconds (12 hours) as
-- the default. Sessions for AWS account owners are restricted to a maximum
-- of 3600 seconds (one hour). If the duration is longer than one hour, the
-- session for AWS account owners defaults to one hour.
gstDurationSeconds :: Lens' GetSessionToken (Maybe Natural)
gstDurationSeconds = lens _gstDurationSeconds (\ s a -> s{_gstDurationSeconds = a}) . mapping _Nat;
-- | The identification number of the MFA device that is associated with the
-- IAM user who is making the 'GetSessionToken' call. Specify this value if
-- the IAM user has a policy that requires MFA authentication. The value is
-- either the serial number for a hardware device (such as 'GAHT12345678')
-- or an Amazon Resource Name (ARN) for a virtual device (such as
-- 'arn:aws:iam::123456789012:mfa\/user'). You can find the device for an
-- IAM user by going to the AWS Management Console and viewing the user\'s
-- security credentials.
gstSerialNumber :: Lens' GetSessionToken (Maybe Text)
gstSerialNumber = lens _gstSerialNumber (\ s a -> s{_gstSerialNumber = a});
instance AWSRequest GetSessionToken where
type Rs GetSessionToken = GetSessionTokenResponse
request = postQuery sTS
response
= receiveXMLWrapper "GetSessionTokenResult"
(\ s h x ->
GetSessionTokenResponse' <$>
(x .@? "Credentials") <*> (pure (fromEnum s)))
instance ToHeaders GetSessionToken where
toHeaders = const mempty
instance ToPath GetSessionToken where
toPath = const "/"
instance ToQuery GetSessionToken where
toQuery GetSessionToken'{..}
= mconcat
["Action" =: ("GetSessionToken" :: ByteString),
"Version" =: ("2011-06-15" :: ByteString),
"TokenCode" =: _gstTokenCode,
"DurationSeconds" =: _gstDurationSeconds,
"SerialNumber" =: _gstSerialNumber]
-- | Contains the response to a successful GetSessionToken request, including
-- temporary AWS credentials that can be used to make AWS requests.
--
-- /See:/ 'getSessionTokenResponse' smart constructor.
data GetSessionTokenResponse = GetSessionTokenResponse'
{ _gstrsCredentials :: !(Maybe Credentials)
, _gstrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'GetSessionTokenResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gstrsCredentials'
--
-- * 'gstrsResponseStatus'
getSessionTokenResponse
:: Int -- ^ 'gstrsResponseStatus'
-> GetSessionTokenResponse
getSessionTokenResponse pResponseStatus_ =
GetSessionTokenResponse'
{ _gstrsCredentials = Nothing
, _gstrsResponseStatus = pResponseStatus_
}
-- | The session credentials for API authentication.
gstrsCredentials :: Lens' GetSessionTokenResponse (Maybe Credentials)
gstrsCredentials = lens _gstrsCredentials (\ s a -> s{_gstrsCredentials = a});
-- | The response status code.
gstrsResponseStatus :: Lens' GetSessionTokenResponse Int
gstrsResponseStatus = lens _gstrsResponseStatus (\ s a -> s{_gstrsResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-sts/gen/Network/AWS/STS/GetSessionToken.hs | mpl-2.0 | 8,101 | 0 | 13 | 1,505 | 767 | 476 | 291 | 87 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.DirectConnect.ConfirmConnection
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Confirm the creation of a hosted connection on an interconnect.
--
-- Upon creation, the hosted connection is initially in the 'Ordering' state,
-- and will remain in this state until the owner calls ConfirmConnection to
-- confirm creation of the hosted connection.
--
-- <http://docs.aws.amazon.com/directconnect/latest/APIReference/API_ConfirmConnection.html>
module Network.AWS.DirectConnect.ConfirmConnection
(
-- * Request
ConfirmConnection
-- ** Request constructor
, confirmConnection
-- ** Request lenses
, ccConnectionId
-- * Response
, ConfirmConnectionResponse
-- ** Response constructor
, confirmConnectionResponse
-- ** Response lenses
, ccr1ConnectionState
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.DirectConnect.Types
import qualified GHC.Exts
newtype ConfirmConnection = ConfirmConnection
{ _ccConnectionId :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'ConfirmConnection' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ccConnectionId' @::@ 'Text'
--
confirmConnection :: Text -- ^ 'ccConnectionId'
-> ConfirmConnection
confirmConnection p1 = ConfirmConnection
{ _ccConnectionId = p1
}
ccConnectionId :: Lens' ConfirmConnection Text
ccConnectionId = lens _ccConnectionId (\s a -> s { _ccConnectionId = a })
newtype ConfirmConnectionResponse = ConfirmConnectionResponse
{ _ccr1ConnectionState :: Maybe ConnectionState
} deriving (Eq, Read, Show)
-- | 'ConfirmConnectionResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ccr1ConnectionState' @::@ 'Maybe' 'ConnectionState'
--
confirmConnectionResponse :: ConfirmConnectionResponse
confirmConnectionResponse = ConfirmConnectionResponse
{ _ccr1ConnectionState = Nothing
}
ccr1ConnectionState :: Lens' ConfirmConnectionResponse (Maybe ConnectionState)
ccr1ConnectionState =
lens _ccr1ConnectionState (\s a -> s { _ccr1ConnectionState = a })
instance ToPath ConfirmConnection where
toPath = const "/"
instance ToQuery ConfirmConnection where
toQuery = const mempty
instance ToHeaders ConfirmConnection
instance ToJSON ConfirmConnection where
toJSON ConfirmConnection{..} = object
[ "connectionId" .= _ccConnectionId
]
instance AWSRequest ConfirmConnection where
type Sv ConfirmConnection = DirectConnect
type Rs ConfirmConnection = ConfirmConnectionResponse
request = post "ConfirmConnection"
response = jsonResponse
instance FromJSON ConfirmConnectionResponse where
parseJSON = withObject "ConfirmConnectionResponse" $ \o -> ConfirmConnectionResponse
<$> o .:? "connectionState"
| romanb/amazonka | amazonka-directconnect/gen/Network/AWS/DirectConnect/ConfirmConnection.hs | mpl-2.0 | 3,849 | 0 | 9 | 773 | 451 | 275 | 176 | 57 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving, FlexibleContexts, OverloadedStrings #-}
module Futhark.Pipeline
( CompileError (..)
, Pipeline
, PipelineConfig (..)
, Action (..)
, FutharkM
, runFutharkM
, compileError
, compileErrorS
, compileFail
, onePass
, passes
, runPasses
, runPipeline
)
where
import Control.Applicative
import Control.Category
import Control.Monad
import Control.Monad.Writer.Strict hiding (pass)
import Control.Monad.Except
import Control.Monad.State
import Control.Monad.Reader
import qualified Data.Text as T
import qualified Data.Text.IO as T
import System.IO
import Prelude hiding (id, (.))
import Futhark.Representation.AST (Prog, pretty, PrettyLore)
import Futhark.TypeCheck
import Futhark.Pass
import Futhark.Util.Log
import Futhark.MonadFreshNames
import qualified Futhark.Util.Pretty as PP
data CompileError = CompileError {
errorDesc :: T.Text
, errorData :: T.Text
}
data FutharkEnv = FutharkEnv { futharkVerbose :: Bool
-- ^ If true, print log messages to standard error.
}
newtype FutharkM a = FutharkM (ExceptT CompileError (StateT VNameSource (ReaderT FutharkEnv IO)) a)
deriving (Applicative, Functor, Monad,
MonadError CompileError,
MonadState VNameSource,
MonadReader FutharkEnv,
MonadIO)
instance MonadFreshNames FutharkM where
getNameSource = get
putNameSource = put
instance MonadLogger FutharkM where
addLog msg = do verb <- asks futharkVerbose
when verb $ liftIO $ T.hPutStr stderr $ toText msg
runFutharkM :: FutharkM a -> Bool -> IO (Either CompileError a)
runFutharkM (FutharkM m) verbose =
runReaderT (evalStateT (runExceptT m) blankNameSource) newEnv
where newEnv = FutharkEnv verbose
compileError :: (MonadError CompileError m, PP.Pretty err) =>
T.Text -> err -> m a
compileError s e = throwError $ CompileError s $ T.pack $ pretty e
compileErrorS :: (MonadError CompileError m) =>
T.Text -> String -> m a
compileErrorS s e = throwError $ CompileError s $ T.pack e
compileFail :: String -> FutharkM a
compileFail s = compileErrorS (T.pack s) "<nothing>"
data Action lore =
Action { actionName :: String
, actionDescription :: String
, actionProcedure :: Prog lore -> FutharkM ()
}
data PipelineConfig =
PipelineConfig { pipelineVerbose :: Bool
, pipelineValidate :: Bool
}
newtype Pipeline fromlore tolore =
Pipeline { unPipeline :: PipelineConfig -> Prog fromlore -> FutharkM (Prog tolore) }
instance Category Pipeline where
id = Pipeline $ const return
p2 . p1 = Pipeline perform
where perform cfg prog =
runPasses p2 cfg =<< runPasses p1 cfg prog
runPasses :: Pipeline fromlore tolore
-> PipelineConfig
-> Prog fromlore
-> FutharkM (Prog tolore)
runPasses = unPipeline
runPipeline :: Pipeline fromlore tolore
-> PipelineConfig
-> Prog fromlore
-> Action tolore
-> FutharkM ()
runPipeline p cfg prog a = do
prog' <- runPasses p cfg prog
when (pipelineVerbose cfg) $ logMsg $
"Running action " <> T.pack (actionName a)
actionProcedure a prog'
onePass :: Checkable tolore =>
Pass fromlore tolore -> Pipeline fromlore tolore
onePass pass = Pipeline perform
where perform cfg prog = do
when (pipelineVerbose cfg) $ logMsg $
"Running pass " <> T.pack (passName pass)
prog' <- runPass pass prog
when (pipelineValidate cfg) $
case checkProg prog' of
Left err -> validationError pass prog' $ show err
Right () -> return ()
return prog'
passes :: Checkable lore =>
[Pass lore lore] -> Pipeline lore lore
passes = foldl (>>>) id . map onePass
validationError :: PrettyLore tolore =>
Pass fromlore tolore -> Prog tolore -> String -> FutharkM a
validationError pass prog err =
compileError msg prog
where msg = "Type error after pass '" <> T.pack (passName pass) <> "':\n" <> T.pack err
runPass :: Pass fromlore tolore
-> Prog fromlore
-> FutharkM (Prog tolore)
runPass pass prog = do
(res, logged) <- runPassM (passFunction pass prog)
addLog logged
case res of Left err -> compileError err ()
Right x -> return x
| CulpaBS/wbBach | src/Futhark/Pipeline.hs | bsd-3-clause | 4,604 | 0 | 14 | 1,329 | 1,306 | 673 | 633 | 117 | 2 |
{-# LANGUAGE TemplateHaskell, MultiParamTypeClasses, PatternGuards, TypeSynonymInstances #-}
-- | Lambdabot base module. Controls message send and receive
module Plugin.Base (theModule) where
import Plugin
import IRCBase (IrcMessage, timeReply, errShowMsg)
-- import Message (getTopic, nick, joinChannel, body, fullName, channels)
import Message (getTopic, nick, server, body, Nick(..), lambdabotName, showNick, readNick)
import qualified Data.Map as M (insert, delete)
import Control.Monad.State (MonadState(..), when, gets)
import Control.OldException (Exception(NoMethodError))
import qualified Data.ByteString.Char8 as P
import qualified Text.Regex as R
-- valid command prefixes
commands :: [String]
commands = commandPrefixes config
$(plugin "Base")
type BaseState = GlobalPrivate () ()
type Base a = ModuleT BaseState LB a
instance Module BaseModule BaseState where
moduleDefState _ = return $ mkGlobalPrivate 20 ()
moduleInit _ = do
ircSignalConnect "PING" doPING
bindModule1 doNOTICE >>= ircSignalConnect "NOTICE"
ircSignalConnect "PART" doPART
ircSignalConnect "JOIN" doJOIN
ircSignalConnect "NICK" doNICK
ircSignalConnect "MODE" doMODE
ircSignalConnect "TOPIC" doTOPIC
ircSignalConnect "QUIT" doQUIT
bindModule1 doPRIVMSG >>= ircSignalConnect "PRIVMSG"
ircSignalConnect "001" doRPL_WELCOME
{- ircSignalConnect "002" doRPL_YOURHOST
ircSignalConnect "003" doRPL_CREATED
ircSignalConnect "004" doRPL_MYINFO -}
ircSignalConnect "005" doRPL_BOUNCE
{- ircSignalConnect "250" doRPL_STATSCONN
ircSignalConnect "251" doRPL_LUSERCLIENT
ircSignalConnect "252" doRPL_LUSEROP
ircSignalConnect "253" doRPL_LUSERUNKNOWN
ircSignalConnect "254" doRPL_LUSERCHANNELS
ircSignalConnect "255" doRPL_LUSERME
ircSignalConnect "265" doRPL_LOCALUSERS
ircSignalConnect "266" doRPL_GLOBALUSERS -}
ircSignalConnect "332" doRPL_TOPIC
{- ircSignalConnect "353" doRPL_NAMRELY
ircSignalConnect "366" doRPL_ENDOFNAMES
ircSignalConnect "372" doRPL_MOTD
ircSignalConnect "375" doRPL_MOTDSTART
ircSignalConnect "376" doRPL_ENDOFMOTD -}
doIGNORE :: Callback
doIGNORE msg = debugStrLn $ show msg
-- = debugStrLn $ "IGNORING> <" ++ msgPrefix msg ++
-- "> [" ++ msgCommand msg ++ "] " ++ show (body msg)
doPING :: Callback
doPING msg
= debugStrLn $ errShowMsg msg
-- If this is a "TIME" then we need to pass it over to the localtime plugin
-- otherwise, dump it to stdout
doNOTICE :: IrcMessage -> Base ()
doNOTICE msg =
if isCTCPTimeReply
then do
-- bind implicit params to Localtime module. boo on implict params :/
-- withModule ircModules
-- "Localtime"
-- (error "Plugin/Base: no Localtime plugin? So I can't handle CTCP time messges")
-- (\_ -> doPRIVMSG (timeReply msg))
-- need to say which module to run the privmsg in
doPRIVMSG (timeReply msg)
else debugStrLn $ "NOTICE: " ++ show (body msg)
where
isCTCPTimeReply = ":\SOHTIME" `isPrefixOf` (last (body msg))
doJOIN :: Callback
doJOIN msg | lambdabotName msg /= nick msg = doIGNORE msg
| otherwise
= do s <- get
put (s { ircChannels = M.insert (mkCN loc) "[currently unknown]" (ircChannels s)}) -- the empty topic causes problems
send $ getTopic loc -- initialize topic
where (_, aloc) = breakOnGlue ":" (head (body msg))
loc = case aloc of
[] -> Nick "freenode" "weird#"
_ -> Nick (server msg) (tail aloc)
doPART :: Callback
doPART msg
= when (lambdabotName msg == nick msg) $ do
let loc = Nick (server msg) (head (body msg))
s <- get
put (s { ircChannels = M.delete (mkCN loc) (ircChannels s) })
doNICK :: Callback
doNICK msg
= doIGNORE msg
doMODE :: Callback
doMODE msg
= doIGNORE msg
doTOPIC :: Callback
doTOPIC msg
= do let loc = Nick (server msg) ((head (body msg)))
s <- get
put (s { ircChannels = M.insert (mkCN loc) (tail $ head $ tail $ body msg) (ircChannels s)})
doRPL_WELCOME :: Callback
doRPL_WELCOME = doIGNORE
doQUIT :: Callback
doQUIT msg = doIGNORE msg
doRPL_BOUNCE :: Callback
doRPL_BOUNCE _msg = debugStrLn "BOUNCE!"
doRPL_TOPIC :: Callback
doRPL_TOPIC msg -- nearly the same as doTOPIC but has our nick on the front of body
= do let loc = Nick (server msg) ((body msg) !! 1)
s <- get
put (s { ircChannels = M.insert (mkCN loc) (tail $ last $ body msg) (ircChannels s) })
doPRIVMSG :: IrcMessage -> Base ()
doPRIVMSG msg = do
-- now <- io getClockTime
-- io $ appendFile (File.findFile "log") $ ppr now
ignored <- lift $ checkIgnore msg
if ignored
then lift $ doIGNORE msg
else mapM_ (doPRIVMSG' (lambdabotName msg) msg) targets
where
alltargets = head (body msg)
targets = map (readNick msg) $ split "," alltargets
-- where
-- ppr now = concat [ timeStamp now, " ", "<", (nick msg), " ", (fullName msg), " #"
-- , (concat . intersperse "," $ channels msg) , "> "
-- , (tail . concat . intersperse " " . tail) (body msg), "\n"]
--
-- | What does the bot respond to?
--
doPRIVMSG' :: Nick -> IrcMessage -> Nick -> Base ()
doPRIVMSG' myname msg target
| myname == target
= let (cmd, params) = breakOnGlue " " text
in doPersonalMsg cmd (dropWhile (== ' ') params)
| flip any ":," $ \c -> (showNick msg myname ++ [c]) `isPrefixOf` text
= let Just wholeCmd = maybeCommand (showNick msg myname) text
(cmd, params) = breakOnGlue " " wholeCmd
in doPublicMsg cmd (dropWhile (==' ') params)
| (commands `arePrefixesOf` text)
&& length text > 1
&& (text !! 1 /= ' ') -- elem of prefixes
&& (not (commands `arePrefixesOf` [text !! 1]) ||
(length text > 2 && text !! 2 == ' ')) -- ignore @@ prefix, but not the @@ command itself
= let (cmd, params) = breakOnGlue " " (dropWhile (==' ') text)
in doPublicMsg cmd (dropWhile (==' ') params)
| otherwise = doContextualMsg text
where
text = tail (head (tail (body msg)))
who = nick msg
doPersonalMsg s r
| commands `arePrefixesOf` s = doMsg (tail s) r who
| s `elem` (evalPrefixes config) = doMsg "run" r who
| otherwise = (lift $ doIGNORE msg)
doPublicMsg s r
| commands `arePrefixesOf` s = doMsg (tail s) r target
| (evalPrefixes config) `arePrefixesWithSpaceOf` s = doMsg "run" r target -- TODO
| otherwise = (lift $ doIGNORE msg)
--
-- normal commands.
--
-- check privledges, do any spell correction, dispatch, handling
-- possible timeouts.
--
-- todo, refactor
--
doMsg cmd rest towhere = do
let ircmsg = ircPrivmsg towhere
allcmds <- getDictKeys ircCommands
let ms = filter (isPrefixOf cmd) allcmds
case ms of
[s] -> docmd s -- a unique prefix
_ | cmd `elem` ms -> docmd cmd -- correct command (usual case)
_ | otherwise -> case closests cmd allcmds of
(n,[s]) | n < e , ms == [] -> docmd s -- unique edit match
(n,ss) | n < e || ms /= [] -- some possibilities
-> lift . ircmsg $ "Maybe you meant: "++showClean(nub(ms++ss))
_ -> docmd cmd -- no prefix, edit distance too far
where
e = 3 -- edit distance cut off. Seems reasonable for small words
fcmd = P.pack cmd -- TODO
frest = P.pack rest
docmd cmd' = do
act <- bindModule0 . withPS towhere $ \_ _ -> do
withModule ircCommands cmd' -- Important.
(ircPrivmsg towhere "Unknown command, try @list")
(\m -> do
name' <- getName
privs <- gets ircPrivCommands
let illegal = disabledCommands config
ok <- liftM2 (||) (return $ cmd' `notElem` (privs ++ illegal))
(lift $ checkPrivs msg)
if not ok
then lift $ ircPrivmsg towhere "Not enough privileges"
else catchIrc
(do mstrs <- catchError
(Right `fmap` fprocess_ m fcmd frest)
(\ex -> case (ex :: IRCError) of -- dispatch
(IRCRaised (NoMethodError _)) -> catchError
(Left `fmap` process m msg towhere cmd' rest)
(\ey -> case (ey :: IRCError) of -- dispatch
(IRCRaised (NoMethodError _)) ->
Left `fmap` process_ m cmd' rest
_ -> throwError ey)
_ -> throwError ex)
-- send off our strings/bytestrings
case mstrs of
Right ps -> lift $ mapM_ (ircPrivmsgF towhere) ps
Left ms -> lift $ mapM_ (ircPrivmsg towhere) ms)
(lift . ircPrivmsg towhere .
(("Plugin `" ++ name' ++ "' failed with: ") ++) . show))
lift $ act
--
-- contextual messages are all input that isn't an explicit command.
-- they're passed to all modules (todo, sounds inefficient) for
-- scanning, and any that implement 'contextual' will reply.
--
-- we try to run the contextual functions from all modules, on every
-- non-command. better hope this is efficient.
--
-- Note how we catch any plugin errors here, rather than letting
-- them bubble back up to the mainloop
--
doContextualMsg r = lift $ do
withAllModules ( \m -> do
act <- bindModule0 ( do
ms <- contextual m msg target r
lift $ mapM_ (ircPrivmsg target) ms
)
name' <- getName
lift $ catchIrc act (debugStrLn . (name' ++) .
(" module failed in contextual handler: " ++) . show)
)
return ()
------------------------------------------------------------------------
maybeCommand :: String -> String -> Maybe String
maybeCommand nm text = case R.matchRegexAll re text of
Nothing -> Nothing
Just (_, _, cmd, _) -> Just cmd
where re = regex' (nm ++ "[.:,]*[[:space:]]*")
--
-- And stuff we don't care about
--
{-
doRPL_YOURHOST :: Callback
doRPL_YOURHOST _msg = return ()
doRPL_CREATED :: Callback
doRPL_CREATED _msg = return ()
doRPL_MYINFO :: Callback
doRPL_MYINFO _msg = return ()
doRPL_STATSCONN :: Callback
doRPL_STATSCONN _msg = return ()
doRPL_LUSERCLIENT :: Callback
doRPL_LUSERCLIENT _msg = return ()
doRPL_LUSEROP :: Callback
doRPL_LUSEROP _msg = return ()
doRPL_LUSERUNKNOWN :: Callback
doRPL_LUSERUNKNOWN _msg = return ()
doRPL_LUSERCHANNELS :: Callback
doRPL_LUSERCHANNELS _msg = return ()
doRPL_LUSERME :: Callback
doRPL_LUSERME _msg = return ()
doRPL_LOCALUSERS :: Callback
doRPL_LOCALUSERS _msg = return ()
doRPL_GLOBALUSERS :: Callback
doRPL_GLOBALUSERS _msg = return ()
doUNKNOWN :: Callback
doUNKNOWN msg
= debugStrLn $ "UNKNOWN> <" ++ msgPrefix msg ++
"> [" ++ msgCommand msg ++ "] " ++ show (body msg)
doRPL_NAMREPLY :: Callback
doRPL_NAMREPLY _msg = return ()
doRPL_ENDOFNAMES :: Callback
doRPL_ENDOFNAMES _msg = return ()
doRPL_MOTD :: Callback
doRPL_MOTD _msg = return ()
doRPL_MOTDSTART :: Callback
doRPL_MOTDSTART _msg = return ()
doRPL_ENDOFMOTD :: Callback
doRPL_ENDOFMOTD _msg = return ()
-}
| zeekay/lambdabot | Plugin/Base.hs | mit | 12,329 | 0 | 42 | 4,085 | 2,624 | 1,343 | 1,281 | 173 | 9 |
module Propellor.Property.Systemd.Core where
import Propellor
import qualified Propellor.Property.Apt as Apt
-- dbus is only a Recommends of systemd, but is needed for communication
-- from the systemd inside a container to the one outside, so make sure it
-- gets installed.
installed :: Property NoInfo
installed = Apt.installed ["systemd", "dbus"]
| sjfloat/propellor | src/Propellor/Property/Systemd/Core.hs | bsd-2-clause | 353 | 0 | 6 | 52 | 47 | 31 | 16 | 5 | 1 |
module Distribution.Client.Init.Licenses
( License
, bsd2
, bsd3
, gplv2
, gplv3
, lgpl21
, lgpl3
, agplv3
, apache20
, mit
, mpl20
, isc
) where
type License = String
bsd2 :: String -> String -> License
bsd2 authors year = unlines
[ "Copyright (c) " ++ year ++ ", " ++ authors
, "All rights reserved."
, ""
, "Redistribution and use in source and binary forms, with or without"
, "modification, are permitted provided that the following conditions are"
, "met:"
, ""
, "1. Redistributions of source code must retain the above copyright"
, " notice, this list of conditions and the following disclaimer."
, ""
, "2. Redistributions in binary form must reproduce the above copyright"
, " notice, this list of conditions and the following disclaimer in the"
, " documentation and/or other materials provided with the"
, " distribution."
, ""
, "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS"
, "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT"
, "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR"
, "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT"
, "OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,"
, "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT"
, "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,"
, "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY"
, "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT"
, "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE"
, "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
]
bsd3 :: String -> String -> License
bsd3 authors year = unlines
[ "Copyright (c) " ++ year ++ ", " ++ authors
, ""
, "All rights reserved."
, ""
, "Redistribution and use in source and binary forms, with or without"
, "modification, are permitted provided that the following conditions are met:"
, ""
, " * Redistributions of source code must retain the above copyright"
, " notice, this list of conditions and the following disclaimer."
, ""
, " * Redistributions in binary form must reproduce the above"
, " copyright notice, this list of conditions and the following"
, " disclaimer in the documentation and/or other materials provided"
, " with the distribution."
, ""
, " * Neither the name of " ++ authors ++ " nor the names of other"
, " contributors may be used to endorse or promote products derived"
, " from this software without specific prior written permission."
, ""
, "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS"
, "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT"
, "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR"
, "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT"
, "OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,"
, "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT"
, "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,"
, "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY"
, "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT"
, "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE"
, "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
]
gplv2 :: License
gplv2 = unlines
[ " GNU GENERAL PUBLIC LICENSE"
, " Version 2, June 1991"
, ""
, " Copyright (C) 1989, 1991 Free Software Foundation, Inc.,"
, " 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA"
, " Everyone is permitted to copy and distribute verbatim copies"
, " of this license document, but changing it is not allowed."
, ""
, " Preamble"
, ""
, " The licenses for most software are designed to take away your"
, "freedom to share and change it. By contrast, the GNU General Public"
, "License is intended to guarantee your freedom to share and change free"
, "software--to make sure the software is free for all its users. This"
, "General Public License applies to most of the Free Software"
, "Foundation's software and to any other program whose authors commit to"
, "using it. (Some other Free Software Foundation software is covered by"
, "the GNU Lesser General Public License instead.) You can apply it to"
, "your programs, too."
, ""
, " When we speak of free software, we are referring to freedom, not"
, "price. Our General Public Licenses are designed to make sure that you"
, "have the freedom to distribute copies of free software (and charge for"
, "this service if you wish), that you receive source code or can get it"
, "if you want it, that you can change the software or use pieces of it"
, "in new free programs; and that you know you can do these things."
, ""
, " To protect your rights, we need to make restrictions that forbid"
, "anyone to deny you these rights or to ask you to surrender the rights."
, "These restrictions translate to certain responsibilities for you if you"
, "distribute copies of the software, or if you modify it."
, ""
, " For example, if you distribute copies of such a program, whether"
, "gratis or for a fee, you must give the recipients all the rights that"
, "you have. You must make sure that they, too, receive or can get the"
, "source code. And you must show them these terms so they know their"
, "rights."
, ""
, " We protect your rights with two steps: (1) copyright the software, and"
, "(2) offer you this license which gives you legal permission to copy,"
, "distribute and/or modify the software."
, ""
, " Also, for each author's protection and ours, we want to make certain"
, "that everyone understands that there is no warranty for this free"
, "software. If the software is modified by someone else and passed on, we"
, "want its recipients to know that what they have is not the original, so"
, "that any problems introduced by others will not reflect on the original"
, "authors' reputations."
, ""
, " Finally, any free program is threatened constantly by software"
, "patents. We wish to avoid the danger that redistributors of a free"
, "program will individually obtain patent licenses, in effect making the"
, "program proprietary. To prevent this, we have made it clear that any"
, "patent must be licensed for everyone's free use or not licensed at all."
, ""
, " The precise terms and conditions for copying, distribution and"
, "modification follow."
, ""
, " GNU GENERAL PUBLIC LICENSE"
, " TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION"
, ""
, " 0. This License applies to any program or other work which contains"
, "a notice placed by the copyright holder saying it may be distributed"
, "under the terms of this General Public License. The \"Program\", below,"
, "refers to any such program or work, and a \"work based on the Program\""
, "means either the Program or any derivative work under copyright law:"
, "that is to say, a work containing the Program or a portion of it,"
, "either verbatim or with modifications and/or translated into another"
, "language. (Hereinafter, translation is included without limitation in"
, "the term \"modification\".) Each licensee is addressed as \"you\"."
, ""
, "Activities other than copying, distribution and modification are not"
, "covered by this License; they are outside its scope. The act of"
, "running the Program is not restricted, and the output from the Program"
, "is covered only if its contents constitute a work based on the"
, "Program (independent of having been made by running the Program)."
, "Whether that is true depends on what the Program does."
, ""
, " 1. You may copy and distribute verbatim copies of the Program's"
, "source code as you receive it, in any medium, provided that you"
, "conspicuously and appropriately publish on each copy an appropriate"
, "copyright notice and disclaimer of warranty; keep intact all the"
, "notices that refer to this License and to the absence of any warranty;"
, "and give any other recipients of the Program a copy of this License"
, "along with the Program."
, ""
, "You may charge a fee for the physical act of transferring a copy, and"
, "you may at your option offer warranty protection in exchange for a fee."
, ""
, " 2. You may modify your copy or copies of the Program or any portion"
, "of it, thus forming a work based on the Program, and copy and"
, "distribute such modifications or work under the terms of Section 1"
, "above, provided that you also meet all of these conditions:"
, ""
, " a) You must cause the modified files to carry prominent notices"
, " stating that you changed the files and the date of any change."
, ""
, " b) You must cause any work that you distribute or publish, that in"
, " whole or in part contains or is derived from the Program or any"
, " part thereof, to be licensed as a whole at no charge to all third"
, " parties under the terms of this License."
, ""
, " c) If the modified program normally reads commands interactively"
, " when run, you must cause it, when started running for such"
, " interactive use in the most ordinary way, to print or display an"
, " announcement including an appropriate copyright notice and a"
, " notice that there is no warranty (or else, saying that you provide"
, " a warranty) and that users may redistribute the program under"
, " these conditions, and telling the user how to view a copy of this"
, " License. (Exception: if the Program itself is interactive but"
, " does not normally print such an announcement, your work based on"
, " the Program is not required to print an announcement.)"
, ""
, "These requirements apply to the modified work as a whole. If"
, "identifiable sections of that work are not derived from the Program,"
, "and can be reasonably considered independent and separate works in"
, "themselves, then this License, and its terms, do not apply to those"
, "sections when you distribute them as separate works. But when you"
, "distribute the same sections as part of a whole which is a work based"
, "on the Program, the distribution of the whole must be on the terms of"
, "this License, whose permissions for other licensees extend to the"
, "entire whole, and thus to each and every part regardless of who wrote it."
, ""
, "Thus, it is not the intent of this section to claim rights or contest"
, "your rights to work written entirely by you; rather, the intent is to"
, "exercise the right to control the distribution of derivative or"
, "collective works based on the Program."
, ""
, "In addition, mere aggregation of another work not based on the Program"
, "with the Program (or with a work based on the Program) on a volume of"
, "a storage or distribution medium does not bring the other work under"
, "the scope of this License."
, ""
, " 3. You may copy and distribute the Program (or a work based on it,"
, "under Section 2) in object code or executable form under the terms of"
, "Sections 1 and 2 above provided that you also do one of the following:"
, ""
, " a) Accompany it with the complete corresponding machine-readable"
, " source code, which must be distributed under the terms of Sections"
, " 1 and 2 above on a medium customarily used for software interchange; or,"
, ""
, " b) Accompany it with a written offer, valid for at least three"
, " years, to give any third party, for a charge no more than your"
, " cost of physically performing source distribution, a complete"
, " machine-readable copy of the corresponding source code, to be"
, " distributed under the terms of Sections 1 and 2 above on a medium"
, " customarily used for software interchange; or,"
, ""
, " c) Accompany it with the information you received as to the offer"
, " to distribute corresponding source code. (This alternative is"
, " allowed only for noncommercial distribution and only if you"
, " received the program in object code or executable form with such"
, " an offer, in accord with Subsection b above.)"
, ""
, "The source code for a work means the preferred form of the work for"
, "making modifications to it. For an executable work, complete source"
, "code means all the source code for all modules it contains, plus any"
, "associated interface definition files, plus the scripts used to"
, "control compilation and installation of the executable. However, as a"
, "special exception, the source code distributed need not include"
, "anything that is normally distributed (in either source or binary"
, "form) with the major components (compiler, kernel, and so on) of the"
, "operating system on which the executable runs, unless that component"
, "itself accompanies the executable."
, ""
, "If distribution of executable or object code is made by offering"
, "access to copy from a designated place, then offering equivalent"
, "access to copy the source code from the same place counts as"
, "distribution of the source code, even though third parties are not"
, "compelled to copy the source along with the object code."
, ""
, " 4. You may not copy, modify, sublicense, or distribute the Program"
, "except as expressly provided under this License. Any attempt"
, "otherwise to copy, modify, sublicense or distribute the Program is"
, "void, and will automatically terminate your rights under this License."
, "However, parties who have received copies, or rights, from you under"
, "this License will not have their licenses terminated so long as such"
, "parties remain in full compliance."
, ""
, " 5. You are not required to accept this License, since you have not"
, "signed it. However, nothing else grants you permission to modify or"
, "distribute the Program or its derivative works. These actions are"
, "prohibited by law if you do not accept this License. Therefore, by"
, "modifying or distributing the Program (or any work based on the"
, "Program), you indicate your acceptance of this License to do so, and"
, "all its terms and conditions for copying, distributing or modifying"
, "the Program or works based on it."
, ""
, " 6. Each time you redistribute the Program (or any work based on the"
, "Program), the recipient automatically receives a license from the"
, "original licensor to copy, distribute or modify the Program subject to"
, "these terms and conditions. You may not impose any further"
, "restrictions on the recipients' exercise of the rights granted herein."
, "You are not responsible for enforcing compliance by third parties to"
, "this License."
, ""
, " 7. If, as a consequence of a court judgment or allegation of patent"
, "infringement or for any other reason (not limited to patent issues),"
, "conditions are imposed on you (whether by court order, agreement or"
, "otherwise) that contradict the conditions of this License, they do not"
, "excuse you from the conditions of this License. If you cannot"
, "distribute so as to satisfy simultaneously your obligations under this"
, "License and any other pertinent obligations, then as a consequence you"
, "may not distribute the Program at all. For example, if a patent"
, "license would not permit royalty-free redistribution of the Program by"
, "all those who receive copies directly or indirectly through you, then"
, "the only way you could satisfy both it and this License would be to"
, "refrain entirely from distribution of the Program."
, ""
, "If any portion of this section is held invalid or unenforceable under"
, "any particular circumstance, the balance of the section is intended to"
, "apply and the section as a whole is intended to apply in other"
, "circumstances."
, ""
, "It is not the purpose of this section to induce you to infringe any"
, "patents or other property right claims or to contest validity of any"
, "such claims; this section has the sole purpose of protecting the"
, "integrity of the free software distribution system, which is"
, "implemented by public license practices. Many people have made"
, "generous contributions to the wide range of software distributed"
, "through that system in reliance on consistent application of that"
, "system; it is up to the author/donor to decide if he or she is willing"
, "to distribute software through any other system and a licensee cannot"
, "impose that choice."
, ""
, "This section is intended to make thoroughly clear what is believed to"
, "be a consequence of the rest of this License."
, ""
, " 8. If the distribution and/or use of the Program is restricted in"
, "certain countries either by patents or by copyrighted interfaces, the"
, "original copyright holder who places the Program under this License"
, "may add an explicit geographical distribution limitation excluding"
, "those countries, so that distribution is permitted only in or among"
, "countries not thus excluded. In such case, this License incorporates"
, "the limitation as if written in the body of this License."
, ""
, " 9. The Free Software Foundation may publish revised and/or new versions"
, "of the General Public License from time to time. Such new versions will"
, "be similar in spirit to the present version, but may differ in detail to"
, "address new problems or concerns."
, ""
, "Each version is given a distinguishing version number. If the Program"
, "specifies a version number of this License which applies to it and \"any"
, "later version\", you have the option of following the terms and conditions"
, "either of that version or of any later version published by the Free"
, "Software Foundation. If the Program does not specify a version number of"
, "this License, you may choose any version ever published by the Free Software"
, "Foundation."
, ""
, " 10. If you wish to incorporate parts of the Program into other free"
, "programs whose distribution conditions are different, write to the author"
, "to ask for permission. For software which is copyrighted by the Free"
, "Software Foundation, write to the Free Software Foundation; we sometimes"
, "make exceptions for this. Our decision will be guided by the two goals"
, "of preserving the free status of all derivatives of our free software and"
, "of promoting the sharing and reuse of software generally."
, ""
, " NO WARRANTY"
, ""
, " 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY"
, "FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN"
, "OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES"
, "PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED"
, "OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF"
, "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS"
, "TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE"
, "PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,"
, "REPAIR OR CORRECTION."
, ""
, " 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING"
, "WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR"
, "REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,"
, "INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING"
, "OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED"
, "TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY"
, "YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER"
, "PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE"
, "POSSIBILITY OF SUCH DAMAGES."
, ""
, " END OF TERMS AND CONDITIONS"
, ""
, " How to Apply These Terms to Your New Programs"
, ""
, " If you develop a new program, and you want it to be of the greatest"
, "possible use to the public, the best way to achieve this is to make it"
, "free software which everyone can redistribute and change under these terms."
, ""
, " To do so, attach the following notices to the program. It is safest"
, "to attach them to the start of each source file to most effectively"
, "convey the exclusion of warranty; and each file should have at least"
, "the \"copyright\" line and a pointer to where the full notice is found."
, ""
, " <one line to give the program's name and a brief idea of what it does.>"
, " Copyright (C) <year> <name of author>"
, ""
, " 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."
, ""
, "Also add information on how to contact you by electronic and paper mail."
, ""
, "If the program is interactive, make it output a short notice like this"
, "when it starts in an interactive mode:"
, ""
, " Gnomovision version 69, Copyright (C) year name of author"
, " Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'."
, " This is free software, and you are welcome to redistribute it"
, " under certain conditions; type `show c' for details."
, ""
, "The hypothetical commands `show w' and `show c' should show the appropriate"
, "parts of the General Public License. Of course, the commands you use may"
, "be called something other than `show w' and `show c'; they could even be"
, "mouse-clicks or menu items--whatever suits your program."
, ""
, "You should also get your employer (if you work as a programmer) or your"
, "school, if any, to sign a \"copyright disclaimer\" for the program, if"
, "necessary. Here is a sample; alter the names:"
, ""
, " Yoyodyne, Inc., hereby disclaims all copyright interest in the program"
, " `Gnomovision' (which makes passes at compilers) written by James Hacker."
, ""
, " <signature of Ty Coon>, 1 April 1989"
, " Ty Coon, President of Vice"
, ""
, "This General Public License does not permit incorporating your program into"
, "proprietary programs. If your program is a subroutine library, you may"
, "consider it more useful to permit linking proprietary applications with the"
, "library. If this is what you want to do, use the GNU Lesser General"
, "Public License instead of this License."
]
gplv3 :: License
gplv3 = unlines
[ " GNU GENERAL PUBLIC LICENSE"
, " Version 3, 29 June 2007"
, ""
, " Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>"
, " Everyone is permitted to copy and distribute verbatim copies"
, " of this license document, but changing it is not allowed."
, ""
, " Preamble"
, ""
, " The GNU General Public License is a free, copyleft license for"
, "software and other kinds of works."
, ""
, " The licenses for most software and other practical works are designed"
, "to take away your freedom to share and change the works. By contrast,"
, "the GNU General Public License is intended to guarantee your freedom to"
, "share and change all versions of a program--to make sure it remains free"
, "software for all its users. We, the Free Software Foundation, use the"
, "GNU General Public License for most of our software; it applies also to"
, "any other work released this way by its authors. You can apply it to"
, "your programs, too."
, ""
, " When we speak of free software, we are referring to freedom, not"
, "price. Our General Public Licenses are designed to make sure that you"
, "have the freedom to distribute copies of free software (and charge for"
, "them if you wish), that you receive source code or can get it if you"
, "want it, that you can change the software or use pieces of it in new"
, "free programs, and that you know you can do these things."
, ""
, " To protect your rights, we need to prevent others from denying you"
, "these rights or asking you to surrender the rights. Therefore, you have"
, "certain responsibilities if you distribute copies of the software, or if"
, "you modify it: responsibilities to respect the freedom of others."
, ""
, " For example, if you distribute copies of such a program, whether"
, "gratis or for a fee, you must pass on to the recipients the same"
, "freedoms that you received. You must make sure that they, too, receive"
, "or can get the source code. And you must show them these terms so they"
, "know their rights."
, ""
, " Developers that use the GNU GPL protect your rights with two steps:"
, "(1) assert copyright on the software, and (2) offer you this License"
, "giving you legal permission to copy, distribute and/or modify it."
, ""
, " For the developers' and authors' protection, the GPL clearly explains"
, "that there is no warranty for this free software. For both users' and"
, "authors' sake, the GPL requires that modified versions be marked as"
, "changed, so that their problems will not be attributed erroneously to"
, "authors of previous versions."
, ""
, " Some devices are designed to deny users access to install or run"
, "modified versions of the software inside them, although the manufacturer"
, "can do so. This is fundamentally incompatible with the aim of"
, "protecting users' freedom to change the software. The systematic"
, "pattern of such abuse occurs in the area of products for individuals to"
, "use, which is precisely where it is most unacceptable. Therefore, we"
, "have designed this version of the GPL to prohibit the practice for those"
, "products. If such problems arise substantially in other domains, we"
, "stand ready to extend this provision to those domains in future versions"
, "of the GPL, as needed to protect the freedom of users."
, ""
, " Finally, every program is threatened constantly by software patents."
, "States should not allow patents to restrict development and use of"
, "software on general-purpose computers, but in those that do, we wish to"
, "avoid the special danger that patents applied to a free program could"
, "make it effectively proprietary. To prevent this, the GPL assures that"
, "patents cannot be used to render the program non-free."
, ""
, " The precise terms and conditions for copying, distribution and"
, "modification follow."
, ""
, " TERMS AND CONDITIONS"
, ""
, " 0. Definitions."
, ""
, " \"This License\" refers to version 3 of the GNU General Public License."
, ""
, " \"Copyright\" also means copyright-like laws that apply to other kinds of"
, "works, such as semiconductor masks."
, ""
, " \"The Program\" refers to any copyrightable work licensed under this"
, "License. Each licensee is addressed as \"you\". \"Licensees\" and"
, "\"recipients\" may be individuals or organizations."
, ""
, " To \"modify\" a work means to copy from or adapt all or part of the work"
, "in a fashion requiring copyright permission, other than the making of an"
, "exact copy. The resulting work is called a \"modified version\" of the"
, "earlier work or a work \"based on\" the earlier work."
, ""
, " A \"covered work\" means either the unmodified Program or a work based"
, "on the Program."
, ""
, " To \"propagate\" a work means to do anything with it that, without"
, "permission, would make you directly or secondarily liable for"
, "infringement under applicable copyright law, except executing it on a"
, "computer or modifying a private copy. Propagation includes copying,"
, "distribution (with or without modification), making available to the"
, "public, and in some countries other activities as well."
, ""
, " To \"convey\" a work means any kind of propagation that enables other"
, "parties to make or receive copies. Mere interaction with a user through"
, "a computer network, with no transfer of a copy, is not conveying."
, ""
, " An interactive user interface displays \"Appropriate Legal Notices\""
, "to the extent that it includes a convenient and prominently visible"
, "feature that (1) displays an appropriate copyright notice, and (2)"
, "tells the user that there is no warranty for the work (except to the"
, "extent that warranties are provided), that licensees may convey the"
, "work under this License, and how to view a copy of this License. If"
, "the interface presents a list of user commands or options, such as a"
, "menu, a prominent item in the list meets this criterion."
, ""
, " 1. Source Code."
, ""
, " The \"source code\" for a work means the preferred form of the work"
, "for making modifications to it. \"Object code\" means any non-source"
, "form of a work."
, ""
, " A \"Standard Interface\" means an interface that either is an official"
, "standard defined by a recognized standards body, or, in the case of"
, "interfaces specified for a particular programming language, one that"
, "is widely used among developers working in that language."
, ""
, " The \"System Libraries\" of an executable work include anything, other"
, "than the work as a whole, that (a) is included in the normal form of"
, "packaging a Major Component, but which is not part of that Major"
, "Component, and (b) serves only to enable use of the work with that"
, "Major Component, or to implement a Standard Interface for which an"
, "implementation is available to the public in source code form. A"
, "\"Major Component\", in this context, means a major essential component"
, "(kernel, window system, and so on) of the specific operating system"
, "(if any) on which the executable work runs, or a compiler used to"
, "produce the work, or an object code interpreter used to run it."
, ""
, " The \"Corresponding Source\" for a work in object code form means all"
, "the source code needed to generate, install, and (for an executable"
, "work) run the object code and to modify the work, including scripts to"
, "control those activities. However, it does not include the work's"
, "System Libraries, or general-purpose tools or generally available free"
, "programs which are used unmodified in performing those activities but"
, "which are not part of the work. For example, Corresponding Source"
, "includes interface definition files associated with source files for"
, "the work, and the source code for shared libraries and dynamically"
, "linked subprograms that the work is specifically designed to require,"
, "such as by intimate data communication or control flow between those"
, "subprograms and other parts of the work."
, ""
, " The Corresponding Source need not include anything that users"
, "can regenerate automatically from other parts of the Corresponding"
, "Source."
, ""
, " The Corresponding Source for a work in source code form is that"
, "same work."
, ""
, " 2. Basic Permissions."
, ""
, " All rights granted under this License are granted for the term of"
, "copyright on the Program, and are irrevocable provided the stated"
, "conditions are met. This License explicitly affirms your unlimited"
, "permission to run the unmodified Program. The output from running a"
, "covered work is covered by this License only if the output, given its"
, "content, constitutes a covered work. This License acknowledges your"
, "rights of fair use or other equivalent, as provided by copyright law."
, ""
, " You may make, run and propagate covered works that you do not"
, "convey, without conditions so long as your license otherwise remains"
, "in force. You may convey covered works to others for the sole purpose"
, "of having them make modifications exclusively for you, or provide you"
, "with facilities for running those works, provided that you comply with"
, "the terms of this License in conveying all material for which you do"
, "not control copyright. Those thus making or running the covered works"
, "for you must do so exclusively on your behalf, under your direction"
, "and control, on terms that prohibit them from making any copies of"
, "your copyrighted material outside their relationship with you."
, ""
, " Conveying under any other circumstances is permitted solely under"
, "the conditions stated below. Sublicensing is not allowed; section 10"
, "makes it unnecessary."
, ""
, " 3. Protecting Users' Legal Rights From Anti-Circumvention Law."
, ""
, " No covered work shall be deemed part of an effective technological"
, "measure under any applicable law fulfilling obligations under article"
, "11 of the WIPO copyright treaty adopted on 20 December 1996, or"
, "similar laws prohibiting or restricting circumvention of such"
, "measures."
, ""
, " When you convey a covered work, you waive any legal power to forbid"
, "circumvention of technological measures to the extent such circumvention"
, "is effected by exercising rights under this License with respect to"
, "the covered work, and you disclaim any intention to limit operation or"
, "modification of the work as a means of enforcing, against the work's"
, "users, your or third parties' legal rights to forbid circumvention of"
, "technological measures."
, ""
, " 4. Conveying Verbatim Copies."
, ""
, " You may convey verbatim copies of the Program's source code as you"
, "receive it, in any medium, provided that you conspicuously and"
, "appropriately publish on each copy an appropriate copyright notice;"
, "keep intact all notices stating that this License and any"
, "non-permissive terms added in accord with section 7 apply to the code;"
, "keep intact all notices of the absence of any warranty; and give all"
, "recipients a copy of this License along with the Program."
, ""
, " You may charge any price or no price for each copy that you convey,"
, "and you may offer support or warranty protection for a fee."
, ""
, " 5. Conveying Modified Source Versions."
, ""
, " You may convey a work based on the Program, or the modifications to"
, "produce it from the Program, in the form of source code under the"
, "terms of section 4, provided that you also meet all of these conditions:"
, ""
, " a) The work must carry prominent notices stating that you modified"
, " it, and giving a relevant date."
, ""
, " b) The work must carry prominent notices stating that it is"
, " released under this License and any conditions added under section"
, " 7. This requirement modifies the requirement in section 4 to"
, " \"keep intact all notices\"."
, ""
, " c) You must license the entire work, as a whole, under this"
, " License to anyone who comes into possession of a copy. This"
, " License will therefore apply, along with any applicable section 7"
, " additional terms, to the whole of the work, and all its parts,"
, " regardless of how they are packaged. This License gives no"
, " permission to license the work in any other way, but it does not"
, " invalidate such permission if you have separately received it."
, ""
, " d) If the work has interactive user interfaces, each must display"
, " Appropriate Legal Notices; however, if the Program has interactive"
, " interfaces that do not display Appropriate Legal Notices, your"
, " work need not make them do so."
, ""
, " A compilation of a covered work with other separate and independent"
, "works, which are not by their nature extensions of the covered work,"
, "and which are not combined with it such as to form a larger program,"
, "in or on a volume of a storage or distribution medium, is called an"
, "\"aggregate\" if the compilation and its resulting copyright are not"
, "used to limit the access or legal rights of the compilation's users"
, "beyond what the individual works permit. Inclusion of a covered work"
, "in an aggregate does not cause this License to apply to the other"
, "parts of the aggregate."
, ""
, " 6. Conveying Non-Source Forms."
, ""
, " You may convey a covered work in object code form under the terms"
, "of sections 4 and 5, provided that you also convey the"
, "machine-readable Corresponding Source under the terms of this License,"
, "in one of these ways:"
, ""
, " a) Convey the object code in, or embodied in, a physical product"
, " (including a physical distribution medium), accompanied by the"
, " Corresponding Source fixed on a durable physical medium"
, " customarily used for software interchange."
, ""
, " b) Convey the object code in, or embodied in, a physical product"
, " (including a physical distribution medium), accompanied by a"
, " written offer, valid for at least three years and valid for as"
, " long as you offer spare parts or customer support for that product"
, " model, to give anyone who possesses the object code either (1) a"
, " copy of the Corresponding Source for all the software in the"
, " product that is covered by this License, on a durable physical"
, " medium customarily used for software interchange, for a price no"
, " more than your reasonable cost of physically performing this"
, " conveying of source, or (2) access to copy the"
, " Corresponding Source from a network server at no charge."
, ""
, " c) Convey individual copies of the object code with a copy of the"
, " written offer to provide the Corresponding Source. This"
, " alternative is allowed only occasionally and noncommercially, and"
, " only if you received the object code with such an offer, in accord"
, " with subsection 6b."
, ""
, " d) Convey the object code by offering access from a designated"
, " place (gratis or for a charge), and offer equivalent access to the"
, " Corresponding Source in the same way through the same place at no"
, " further charge. You need not require recipients to copy the"
, " Corresponding Source along with the object code. If the place to"
, " copy the object code is a network server, the Corresponding Source"
, " may be on a different server (operated by you or a third party)"
, " that supports equivalent copying facilities, provided you maintain"
, " clear directions next to the object code saying where to find the"
, " Corresponding Source. Regardless of what server hosts the"
, " Corresponding Source, you remain obligated to ensure that it is"
, " available for as long as needed to satisfy these requirements."
, ""
, " e) Convey the object code using peer-to-peer transmission, provided"
, " you inform other peers where the object code and Corresponding"
, " Source of the work are being offered to the general public at no"
, " charge under subsection 6d."
, ""
, " A separable portion of the object code, whose source code is excluded"
, "from the Corresponding Source as a System Library, need not be"
, "included in conveying the object code work."
, ""
, " A \"User Product\" is either (1) a \"consumer product\", which means any"
, "tangible personal property which is normally used for personal, family,"
, "or household purposes, or (2) anything designed or sold for incorporation"
, "into a dwelling. In determining whether a product is a consumer product,"
, "doubtful cases shall be resolved in favor of coverage. For a particular"
, "product received by a particular user, \"normally used\" refers to a"
, "typical or common use of that class of product, regardless of the status"
, "of the particular user or of the way in which the particular user"
, "actually uses, or expects or is expected to use, the product. A product"
, "is a consumer product regardless of whether the product has substantial"
, "commercial, industrial or non-consumer uses, unless such uses represent"
, "the only significant mode of use of the product."
, ""
, " \"Installation Information\" for a User Product means any methods,"
, "procedures, authorization keys, or other information required to install"
, "and execute modified versions of a covered work in that User Product from"
, "a modified version of its Corresponding Source. The information must"
, "suffice to ensure that the continued functioning of the modified object"
, "code is in no case prevented or interfered with solely because"
, "modification has been made."
, ""
, " If you convey an object code work under this section in, or with, or"
, "specifically for use in, a User Product, and the conveying occurs as"
, "part of a transaction in which the right of possession and use of the"
, "User Product is transferred to the recipient in perpetuity or for a"
, "fixed term (regardless of how the transaction is characterized), the"
, "Corresponding Source conveyed under this section must be accompanied"
, "by the Installation Information. But this requirement does not apply"
, "if neither you nor any third party retains the ability to install"
, "modified object code on the User Product (for example, the work has"
, "been installed in ROM)."
, ""
, " The requirement to provide Installation Information does not include a"
, "requirement to continue to provide support service, warranty, or updates"
, "for a work that has been modified or installed by the recipient, or for"
, "the User Product in which it has been modified or installed. Access to a"
, "network may be denied when the modification itself materially and"
, "adversely affects the operation of the network or violates the rules and"
, "protocols for communication across the network."
, ""
, " Corresponding Source conveyed, and Installation Information provided,"
, "in accord with this section must be in a format that is publicly"
, "documented (and with an implementation available to the public in"
, "source code form), and must require no special password or key for"
, "unpacking, reading or copying."
, ""
, " 7. Additional Terms."
, ""
, " \"Additional permissions\" are terms that supplement the terms of this"
, "License by making exceptions from one or more of its conditions."
, "Additional permissions that are applicable to the entire Program shall"
, "be treated as though they were included in this License, to the extent"
, "that they are valid under applicable law. If additional permissions"
, "apply only to part of the Program, that part may be used separately"
, "under those permissions, but the entire Program remains governed by"
, "this License without regard to the additional permissions."
, ""
, " When you convey a copy of a covered work, you may at your option"
, "remove any additional permissions from that copy, or from any part of"
, "it. (Additional permissions may be written to require their own"
, "removal in certain cases when you modify the work.) You may place"
, "additional permissions on material, added by you to a covered work,"
, "for which you have or can give appropriate copyright permission."
, ""
, " Notwithstanding any other provision of this License, for material you"
, "add to a covered work, you may (if authorized by the copyright holders of"
, "that material) supplement the terms of this License with terms:"
, ""
, " a) Disclaiming warranty or limiting liability differently from the"
, " terms of sections 15 and 16 of this License; or"
, ""
, " b) Requiring preservation of specified reasonable legal notices or"
, " author attributions in that material or in the Appropriate Legal"
, " Notices displayed by works containing it; or"
, ""
, " c) Prohibiting misrepresentation of the origin of that material, or"
, " requiring that modified versions of such material be marked in"
, " reasonable ways as different from the original version; or"
, ""
, " d) Limiting the use for publicity purposes of names of licensors or"
, " authors of the material; or"
, ""
, " e) Declining to grant rights under trademark law for use of some"
, " trade names, trademarks, or service marks; or"
, ""
, " f) Requiring indemnification of licensors and authors of that"
, " material by anyone who conveys the material (or modified versions of"
, " it) with contractual assumptions of liability to the recipient, for"
, " any liability that these contractual assumptions directly impose on"
, " those licensors and authors."
, ""
, " All other non-permissive additional terms are considered \"further"
, "restrictions\" within the meaning of section 10. If the Program as you"
, "received it, or any part of it, contains a notice stating that it is"
, "governed by this License along with a term that is a further"
, "restriction, you may remove that term. If a license document contains"
, "a further restriction but permits relicensing or conveying under this"
, "License, you may add to a covered work material governed by the terms"
, "of that license document, provided that the further restriction does"
, "not survive such relicensing or conveying."
, ""
, " If you add terms to a covered work in accord with this section, you"
, "must place, in the relevant source files, a statement of the"
, "additional terms that apply to those files, or a notice indicating"
, "where to find the applicable terms."
, ""
, " Additional terms, permissive or non-permissive, may be stated in the"
, "form of a separately written license, or stated as exceptions;"
, "the above requirements apply either way."
, ""
, " 8. Termination."
, ""
, " You may not propagate or modify a covered work except as expressly"
, "provided under this License. Any attempt otherwise to propagate or"
, "modify it is void, and will automatically terminate your rights under"
, "this License (including any patent licenses granted under the third"
, "paragraph of section 11)."
, ""
, " However, if you cease all violation of this License, then your"
, "license from a particular copyright holder is reinstated (a)"
, "provisionally, unless and until the copyright holder explicitly and"
, "finally terminates your license, and (b) permanently, if the copyright"
, "holder fails to notify you of the violation by some reasonable means"
, "prior to 60 days after the cessation."
, ""
, " Moreover, your license from a particular copyright holder is"
, "reinstated permanently if the copyright holder notifies you of the"
, "violation by some reasonable means, this is the first time you have"
, "received notice of violation of this License (for any work) from that"
, "copyright holder, and you cure the violation prior to 30 days after"
, "your receipt of the notice."
, ""
, " Termination of your rights under this section does not terminate the"
, "licenses of parties who have received copies or rights from you under"
, "this License. If your rights have been terminated and not permanently"
, "reinstated, you do not qualify to receive new licenses for the same"
, "material under section 10."
, ""
, " 9. Acceptance Not Required for Having Copies."
, ""
, " You are not required to accept this License in order to receive or"
, "run a copy of the Program. Ancillary propagation of a covered work"
, "occurring solely as a consequence of using peer-to-peer transmission"
, "to receive a copy likewise does not require acceptance. However,"
, "nothing other than this License grants you permission to propagate or"
, "modify any covered work. These actions infringe copyright if you do"
, "not accept this License. Therefore, by modifying or propagating a"
, "covered work, you indicate your acceptance of this License to do so."
, ""
, " 10. Automatic Licensing of Downstream Recipients."
, ""
, " Each time you convey a covered work, the recipient automatically"
, "receives a license from the original licensors, to run, modify and"
, "propagate that work, subject to this License. You are not responsible"
, "for enforcing compliance by third parties with this License."
, ""
, " An \"entity transaction\" is a transaction transferring control of an"
, "organization, or substantially all assets of one, or subdividing an"
, "organization, or merging organizations. If propagation of a covered"
, "work results from an entity transaction, each party to that"
, "transaction who receives a copy of the work also receives whatever"
, "licenses to the work the party's predecessor in interest had or could"
, "give under the previous paragraph, plus a right to possession of the"
, "Corresponding Source of the work from the predecessor in interest, if"
, "the predecessor has it or can get it with reasonable efforts."
, ""
, " You may not impose any further restrictions on the exercise of the"
, "rights granted or affirmed under this License. For example, you may"
, "not impose a license fee, royalty, or other charge for exercise of"
, "rights granted under this License, and you may not initiate litigation"
, "(including a cross-claim or counterclaim in a lawsuit) alleging that"
, "any patent claim is infringed by making, using, selling, offering for"
, "sale, or importing the Program or any portion of it."
, ""
, " 11. Patents."
, ""
, " A \"contributor\" is a copyright holder who authorizes use under this"
, "License of the Program or a work on which the Program is based. The"
, "work thus licensed is called the contributor's \"contributor version\"."
, ""
, " A contributor's \"essential patent claims\" are all patent claims"
, "owned or controlled by the contributor, whether already acquired or"
, "hereafter acquired, that would be infringed by some manner, permitted"
, "by this License, of making, using, or selling its contributor version,"
, "but do not include claims that would be infringed only as a"
, "consequence of further modification of the contributor version. For"
, "purposes of this definition, \"control\" includes the right to grant"
, "patent sublicenses in a manner consistent with the requirements of"
, "this License."
, ""
, " Each contributor grants you a non-exclusive, worldwide, royalty-free"
, "patent license under the contributor's essential patent claims, to"
, "make, use, sell, offer for sale, import and otherwise run, modify and"
, "propagate the contents of its contributor version."
, ""
, " In the following three paragraphs, a \"patent license\" is any express"
, "agreement or commitment, however denominated, not to enforce a patent"
, "(such as an express permission to practice a patent or covenant not to"
, "sue for patent infringement). To \"grant\" such a patent license to a"
, "party means to make such an agreement or commitment not to enforce a"
, "patent against the party."
, ""
, " If you convey a covered work, knowingly relying on a patent license,"
, "and the Corresponding Source of the work is not available for anyone"
, "to copy, free of charge and under the terms of this License, through a"
, "publicly available network server or other readily accessible means,"
, "then you must either (1) cause the Corresponding Source to be so"
, "available, or (2) arrange to deprive yourself of the benefit of the"
, "patent license for this particular work, or (3) arrange, in a manner"
, "consistent with the requirements of this License, to extend the patent"
, "license to downstream recipients. \"Knowingly relying\" means you have"
, "actual knowledge that, but for the patent license, your conveying the"
, "covered work in a country, or your recipient's use of the covered work"
, "in a country, would infringe one or more identifiable patents in that"
, "country that you have reason to believe are valid."
, ""
, " If, pursuant to or in connection with a single transaction or"
, "arrangement, you convey, or propagate by procuring conveyance of, a"
, "covered work, and grant a patent license to some of the parties"
, "receiving the covered work authorizing them to use, propagate, modify"
, "or convey a specific copy of the covered work, then the patent license"
, "you grant is automatically extended to all recipients of the covered"
, "work and works based on it."
, ""
, " A patent license is \"discriminatory\" if it does not include within"
, "the scope of its coverage, prohibits the exercise of, or is"
, "conditioned on the non-exercise of one or more of the rights that are"
, "specifically granted under this License. You may not convey a covered"
, "work if you are a party to an arrangement with a third party that is"
, "in the business of distributing software, under which you make payment"
, "to the third party based on the extent of your activity of conveying"
, "the work, and under which the third party grants, to any of the"
, "parties who would receive the covered work from you, a discriminatory"
, "patent license (a) in connection with copies of the covered work"
, "conveyed by you (or copies made from those copies), or (b) primarily"
, "for and in connection with specific products or compilations that"
, "contain the covered work, unless you entered into that arrangement,"
, "or that patent license was granted, prior to 28 March 2007."
, ""
, " Nothing in this License shall be construed as excluding or limiting"
, "any implied license or other defenses to infringement that may"
, "otherwise be available to you under applicable patent law."
, ""
, " 12. No Surrender of Others' Freedom."
, ""
, " If conditions are imposed on you (whether by court order, agreement or"
, "otherwise) that contradict the conditions of this License, they do not"
, "excuse you from the conditions of this License. If you cannot convey a"
, "covered work so as to satisfy simultaneously your obligations under this"
, "License and any other pertinent obligations, then as a consequence you may"
, "not convey it at all. For example, if you agree to terms that obligate you"
, "to collect a royalty for further conveying from those to whom you convey"
, "the Program, the only way you could satisfy both those terms and this"
, "License would be to refrain entirely from conveying the Program."
, ""
, " 13. Use with the GNU Affero General Public License."
, ""
, " Notwithstanding any other provision of this License, you have"
, "permission to link or combine any covered work with a work licensed"
, "under version 3 of the GNU Affero General Public License into a single"
, "combined work, and to convey the resulting work. The terms of this"
, "License will continue to apply to the part which is the covered work,"
, "but the special requirements of the GNU Affero General Public License,"
, "section 13, concerning interaction through a network will apply to the"
, "combination as such."
, ""
, " 14. Revised Versions of this License."
, ""
, " The Free Software Foundation may publish revised and/or new versions of"
, "the GNU General Public License from time to time. Such new versions will"
, "be similar in spirit to the present version, but may differ in detail to"
, "address new problems or concerns."
, ""
, " Each version is given a distinguishing version number. If the"
, "Program specifies that a certain numbered version of the GNU General"
, "Public License \"or any later version\" applies to it, you have the"
, "option of following the terms and conditions either of that numbered"
, "version or of any later version published by the Free Software"
, "Foundation. If the Program does not specify a version number of the"
, "GNU General Public License, you may choose any version ever published"
, "by the Free Software Foundation."
, ""
, " If the Program specifies that a proxy can decide which future"
, "versions of the GNU General Public License can be used, that proxy's"
, "public statement of acceptance of a version permanently authorizes you"
, "to choose that version for the Program."
, ""
, " Later license versions may give you additional or different"
, "permissions. However, no additional obligations are imposed on any"
, "author or copyright holder as a result of your choosing to follow a"
, "later version."
, ""
, " 15. Disclaimer of Warranty."
, ""
, " THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY"
, "APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT"
, "HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY"
, "OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,"
, "THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR"
, "PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM"
, "IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF"
, "ALL NECESSARY SERVICING, REPAIR OR CORRECTION."
, ""
, " 16. Limitation of Liability."
, ""
, " IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING"
, "WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS"
, "THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY"
, "GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE"
, "USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF"
, "DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD"
, "PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),"
, "EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF"
, "SUCH DAMAGES."
, ""
, " 17. Interpretation of Sections 15 and 16."
, ""
, " If the disclaimer of warranty and limitation of liability provided"
, "above cannot be given local legal effect according to their terms,"
, "reviewing courts shall apply local law that most closely approximates"
, "an absolute waiver of all civil liability in connection with the"
, "Program, unless a warranty or assumption of liability accompanies a"
, "copy of the Program in return for a fee."
, ""
, " END OF TERMS AND CONDITIONS"
, ""
, " How to Apply These Terms to Your New Programs"
, ""
, " If you develop a new program, and you want it to be of the greatest"
, "possible use to the public, the best way to achieve this is to make it"
, "free software which everyone can redistribute and change under these terms."
, ""
, " To do so, attach the following notices to the program. It is safest"
, "to attach them to the start of each source file to most effectively"
, "state the exclusion of warranty; and each file should have at least"
, "the \"copyright\" line and a pointer to where the full notice is found."
, ""
, " <one line to give the program's name and a brief idea of what it does.>"
, " Copyright (C) <year> <name of author>"
, ""
, " 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 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 General Public License for more details."
, ""
, " You should have received a copy of the GNU General Public License"
, " along with this program. If not, see <http://www.gnu.org/licenses/>."
, ""
, "Also add information on how to contact you by electronic and paper mail."
, ""
, " If the program does terminal interaction, make it output a short"
, "notice like this when it starts in an interactive mode:"
, ""
, " <program> Copyright (C) <year> <name of author>"
, " This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'."
, " This is free software, and you are welcome to redistribute it"
, " under certain conditions; type `show c' for details."
, ""
, "The hypothetical commands `show w' and `show c' should show the appropriate"
, "parts of the General Public License. Of course, your program's commands"
, "might be different; for a GUI interface, you would use an \"about box\"."
, ""
, " You should also get your employer (if you work as a programmer) or school,"
, "if any, to sign a \"copyright disclaimer\" for the program, if necessary."
, "For more information on this, and how to apply and follow the GNU GPL, see"
, "<http://www.gnu.org/licenses/>."
, ""
, " The GNU General Public License does not permit incorporating your program"
, "into proprietary programs. If your program is a subroutine library, you"
, "may consider it more useful to permit linking proprietary applications with"
, "the library. If this is what you want to do, use the GNU Lesser General"
, "Public License instead of this License. But first, please read"
, "<http://www.gnu.org/philosophy/why-not-lgpl.html>."
]
agplv3 :: License
agplv3 = unlines
[ " GNU AFFERO GENERAL PUBLIC LICENSE"
, " Version 3, 19 November 2007"
, ""
, " Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>"
, " Everyone is permitted to copy and distribute verbatim copies"
, " of this license document, but changing it is not allowed."
, ""
, " Preamble"
, ""
, " The GNU Affero General Public License is a free, copyleft license for"
, "software and other kinds of works, specifically designed to ensure"
, "cooperation with the community in the case of network server software."
, ""
, " The licenses for most software and other practical works are designed"
, "to take away your freedom to share and change the works. By contrast,"
, "our General Public Licenses are intended to guarantee your freedom to"
, "share and change all versions of a program--to make sure it remains free"
, "software for all its users."
, ""
, " When we speak of free software, we are referring to freedom, not"
, "price. Our General Public Licenses are designed to make sure that you"
, "have the freedom to distribute copies of free software (and charge for"
, "them if you wish), that you receive source code or can get it if you"
, "want it, that you can change the software or use pieces of it in new"
, "free programs, and that you know you can do these things."
, ""
, " Developers that use our General Public Licenses protect your rights"
, "with two steps: (1) assert copyright on the software, and (2) offer"
, "you this License which gives you legal permission to copy, distribute"
, "and/or modify the software."
, ""
, " A secondary benefit of defending all users' freedom is that"
, "improvements made in alternate versions of the program, if they"
, "receive widespread use, become available for other developers to"
, "incorporate. Many developers of free software are heartened and"
, "encouraged by the resulting cooperation. However, in the case of"
, "software used on network servers, this result may fail to come about."
, "The GNU General Public License permits making a modified version and"
, "letting the public access it on a server without ever releasing its"
, "source code to the public."
, ""
, " The GNU Affero General Public License is designed specifically to"
, "ensure that, in such cases, the modified source code becomes available"
, "to the community. It requires the operator of a network server to"
, "provide the source code of the modified version running there to the"
, "users of that server. Therefore, public use of a modified version, on"
, "a publicly accessible server, gives the public access to the source"
, "code of the modified version."
, ""
, " An older license, called the Affero General Public License and"
, "published by Affero, was designed to accomplish similar goals. This is"
, "a different license, not a version of the Affero GPL, but Affero has"
, "released a new version of the Affero GPL which permits relicensing under"
, "this license."
, ""
, " The precise terms and conditions for copying, distribution and"
, "modification follow."
, ""
, " TERMS AND CONDITIONS"
, ""
, " 0. Definitions."
, ""
, " \"This License\" refers to version 3 of the GNU Affero General Public License."
, ""
, " \"Copyright\" also means copyright-like laws that apply to other kinds of"
, "works, such as semiconductor masks."
, ""
, " \"The Program\" refers to any copyrightable work licensed under this"
, "License. Each licensee is addressed as \"you\". \"Licensees\" and"
, "\"recipients\" may be individuals or organizations."
, ""
, " To \"modify\" a work means to copy from or adapt all or part of the work"
, "in a fashion requiring copyright permission, other than the making of an"
, "exact copy. The resulting work is called a \"modified version\" of the"
, "earlier work or a work \"based on\" the earlier work."
, ""
, " A \"covered work\" means either the unmodified Program or a work based"
, "on the Program."
, ""
, " To \"propagate\" a work means to do anything with it that, without"
, "permission, would make you directly or secondarily liable for"
, "infringement under applicable copyright law, except executing it on a"
, "computer or modifying a private copy. Propagation includes copying,"
, "distribution (with or without modification), making available to the"
, "public, and in some countries other activities as well."
, ""
, " To \"convey\" a work means any kind of propagation that enables other"
, "parties to make or receive copies. Mere interaction with a user through"
, "a computer network, with no transfer of a copy, is not conveying."
, ""
, " An interactive user interface displays \"Appropriate Legal Notices\""
, "to the extent that it includes a convenient and prominently visible"
, "feature that (1) displays an appropriate copyright notice, and (2)"
, "tells the user that there is no warranty for the work (except to the"
, "extent that warranties are provided), that licensees may convey the"
, "work under this License, and how to view a copy of this License. If"
, "the interface presents a list of user commands or options, such as a"
, "menu, a prominent item in the list meets this criterion."
, ""
, " 1. Source Code."
, ""
, " The \"source code\" for a work means the preferred form of the work"
, "for making modifications to it. \"Object code\" means any non-source"
, "form of a work."
, ""
, " A \"Standard Interface\" means an interface that either is an official"
, "standard defined by a recognized standards body, or, in the case of"
, "interfaces specified for a particular programming language, one that"
, "is widely used among developers working in that language."
, ""
, " The \"System Libraries\" of an executable work include anything, other"
, "than the work as a whole, that (a) is included in the normal form of"
, "packaging a Major Component, but which is not part of that Major"
, "Component, and (b) serves only to enable use of the work with that"
, "Major Component, or to implement a Standard Interface for which an"
, "implementation is available to the public in source code form. A"
, "\"Major Component\", in this context, means a major essential component"
, "(kernel, window system, and so on) of the specific operating system"
, "(if any) on which the executable work runs, or a compiler used to"
, "produce the work, or an object code interpreter used to run it."
, ""
, " The \"Corresponding Source\" for a work in object code form means all"
, "the source code needed to generate, install, and (for an executable"
, "work) run the object code and to modify the work, including scripts to"
, "control those activities. However, it does not include the work's"
, "System Libraries, or general-purpose tools or generally available free"
, "programs which are used unmodified in performing those activities but"
, "which are not part of the work. For example, Corresponding Source"
, "includes interface definition files associated with source files for"
, "the work, and the source code for shared libraries and dynamically"
, "linked subprograms that the work is specifically designed to require,"
, "such as by intimate data communication or control flow between those"
, "subprograms and other parts of the work."
, ""
, " The Corresponding Source need not include anything that users"
, "can regenerate automatically from other parts of the Corresponding"
, "Source."
, ""
, " The Corresponding Source for a work in source code form is that"
, "same work."
, ""
, " 2. Basic Permissions."
, ""
, " All rights granted under this License are granted for the term of"
, "copyright on the Program, and are irrevocable provided the stated"
, "conditions are met. This License explicitly affirms your unlimited"
, "permission to run the unmodified Program. The output from running a"
, "covered work is covered by this License only if the output, given its"
, "content, constitutes a covered work. This License acknowledges your"
, "rights of fair use or other equivalent, as provided by copyright law."
, ""
, " You may make, run and propagate covered works that you do not"
, "convey, without conditions so long as your license otherwise remains"
, "in force. You may convey covered works to others for the sole purpose"
, "of having them make modifications exclusively for you, or provide you"
, "with facilities for running those works, provided that you comply with"
, "the terms of this License in conveying all material for which you do"
, "not control copyright. Those thus making or running the covered works"
, "for you must do so exclusively on your behalf, under your direction"
, "and control, on terms that prohibit them from making any copies of"
, "your copyrighted material outside their relationship with you."
, ""
, " Conveying under any other circumstances is permitted solely under"
, "the conditions stated below. Sublicensing is not allowed; section 10"
, "makes it unnecessary."
, ""
, " 3. Protecting Users' Legal Rights From Anti-Circumvention Law."
, ""
, " No covered work shall be deemed part of an effective technological"
, "measure under any applicable law fulfilling obligations under article"
, "11 of the WIPO copyright treaty adopted on 20 December 1996, or"
, "similar laws prohibiting or restricting circumvention of such"
, "measures."
, ""
, " When you convey a covered work, you waive any legal power to forbid"
, "circumvention of technological measures to the extent such circumvention"
, "is effected by exercising rights under this License with respect to"
, "the covered work, and you disclaim any intention to limit operation or"
, "modification of the work as a means of enforcing, against the work's"
, "users, your or third parties' legal rights to forbid circumvention of"
, "technological measures."
, ""
, " 4. Conveying Verbatim Copies."
, ""
, " You may convey verbatim copies of the Program's source code as you"
, "receive it, in any medium, provided that you conspicuously and"
, "appropriately publish on each copy an appropriate copyright notice;"
, "keep intact all notices stating that this License and any"
, "non-permissive terms added in accord with section 7 apply to the code;"
, "keep intact all notices of the absence of any warranty; and give all"
, "recipients a copy of this License along with the Program."
, ""
, " You may charge any price or no price for each copy that you convey,"
, "and you may offer support or warranty protection for a fee."
, ""
, " 5. Conveying Modified Source Versions."
, ""
, " You may convey a work based on the Program, or the modifications to"
, "produce it from the Program, in the form of source code under the"
, "terms of section 4, provided that you also meet all of these conditions:"
, ""
, " a) The work must carry prominent notices stating that you modified"
, " it, and giving a relevant date."
, ""
, " b) The work must carry prominent notices stating that it is"
, " released under this License and any conditions added under section"
, " 7. This requirement modifies the requirement in section 4 to"
, " \"keep intact all notices\"."
, ""
, " c) You must license the entire work, as a whole, under this"
, " License to anyone who comes into possession of a copy. This"
, " License will therefore apply, along with any applicable section 7"
, " additional terms, to the whole of the work, and all its parts,"
, " regardless of how they are packaged. This License gives no"
, " permission to license the work in any other way, but it does not"
, " invalidate such permission if you have separately received it."
, ""
, " d) If the work has interactive user interfaces, each must display"
, " Appropriate Legal Notices; however, if the Program has interactive"
, " interfaces that do not display Appropriate Legal Notices, your"
, " work need not make them do so."
, ""
, " A compilation of a covered work with other separate and independent"
, "works, which are not by their nature extensions of the covered work,"
, "and which are not combined with it such as to form a larger program,"
, "in or on a volume of a storage or distribution medium, is called an"
, "\"aggregate\" if the compilation and its resulting copyright are not"
, "used to limit the access or legal rights of the compilation's users"
, "beyond what the individual works permit. Inclusion of a covered work"
, "in an aggregate does not cause this License to apply to the other"
, "parts of the aggregate."
, ""
, " 6. Conveying Non-Source Forms."
, ""
, " You may convey a covered work in object code form under the terms"
, "of sections 4 and 5, provided that you also convey the"
, "machine-readable Corresponding Source under the terms of this License,"
, "in one of these ways:"
, ""
, " a) Convey the object code in, or embodied in, a physical product"
, " (including a physical distribution medium), accompanied by the"
, " Corresponding Source fixed on a durable physical medium"
, " customarily used for software interchange."
, ""
, " b) Convey the object code in, or embodied in, a physical product"
, " (including a physical distribution medium), accompanied by a"
, " written offer, valid for at least three years and valid for as"
, " long as you offer spare parts or customer support for that product"
, " model, to give anyone who possesses the object code either (1) a"
, " copy of the Corresponding Source for all the software in the"
, " product that is covered by this License, on a durable physical"
, " medium customarily used for software interchange, for a price no"
, " more than your reasonable cost of physically performing this"
, " conveying of source, or (2) access to copy the"
, " Corresponding Source from a network server at no charge."
, ""
, " c) Convey individual copies of the object code with a copy of the"
, " written offer to provide the Corresponding Source. This"
, " alternative is allowed only occasionally and noncommercially, and"
, " only if you received the object code with such an offer, in accord"
, " with subsection 6b."
, ""
, " d) Convey the object code by offering access from a designated"
, " place (gratis or for a charge), and offer equivalent access to the"
, " Corresponding Source in the same way through the same place at no"
, " further charge. You need not require recipients to copy the"
, " Corresponding Source along with the object code. If the place to"
, " copy the object code is a network server, the Corresponding Source"
, " may be on a different server (operated by you or a third party)"
, " that supports equivalent copying facilities, provided you maintain"
, " clear directions next to the object code saying where to find the"
, " Corresponding Source. Regardless of what server hosts the"
, " Corresponding Source, you remain obligated to ensure that it is"
, " available for as long as needed to satisfy these requirements."
, ""
, " e) Convey the object code using peer-to-peer transmission, provided"
, " you inform other peers where the object code and Corresponding"
, " Source of the work are being offered to the general public at no"
, " charge under subsection 6d."
, ""
, " A separable portion of the object code, whose source code is excluded"
, "from the Corresponding Source as a System Library, need not be"
, "included in conveying the object code work."
, ""
, " A \"User Product\" is either (1) a \"consumer product\", which means any"
, "tangible personal property which is normally used for personal, family,"
, "or household purposes, or (2) anything designed or sold for incorporation"
, "into a dwelling. In determining whether a product is a consumer product,"
, "doubtful cases shall be resolved in favor of coverage. For a particular"
, "product received by a particular user, \"normally used\" refers to a"
, "typical or common use of that class of product, regardless of the status"
, "of the particular user or of the way in which the particular user"
, "actually uses, or expects or is expected to use, the product. A product"
, "is a consumer product regardless of whether the product has substantial"
, "commercial, industrial or non-consumer uses, unless such uses represent"
, "the only significant mode of use of the product."
, ""
, " \"Installation Information\" for a User Product means any methods,"
, "procedures, authorization keys, or other information required to install"
, "and execute modified versions of a covered work in that User Product from"
, "a modified version of its Corresponding Source. The information must"
, "suffice to ensure that the continued functioning of the modified object"
, "code is in no case prevented or interfered with solely because"
, "modification has been made."
, ""
, " If you convey an object code work under this section in, or with, or"
, "specifically for use in, a User Product, and the conveying occurs as"
, "part of a transaction in which the right of possession and use of the"
, "User Product is transferred to the recipient in perpetuity or for a"
, "fixed term (regardless of how the transaction is characterized), the"
, "Corresponding Source conveyed under this section must be accompanied"
, "by the Installation Information. But this requirement does not apply"
, "if neither you nor any third party retains the ability to install"
, "modified object code on the User Product (for example, the work has"
, "been installed in ROM)."
, ""
, " The requirement to provide Installation Information does not include a"
, "requirement to continue to provide support service, warranty, or updates"
, "for a work that has been modified or installed by the recipient, or for"
, "the User Product in which it has been modified or installed. Access to a"
, "network may be denied when the modification itself materially and"
, "adversely affects the operation of the network or violates the rules and"
, "protocols for communication across the network."
, ""
, " Corresponding Source conveyed, and Installation Information provided,"
, "in accord with this section must be in a format that is publicly"
, "documented (and with an implementation available to the public in"
, "source code form), and must require no special password or key for"
, "unpacking, reading or copying."
, ""
, " 7. Additional Terms."
, ""
, " \"Additional permissions\" are terms that supplement the terms of this"
, "License by making exceptions from one or more of its conditions."
, "Additional permissions that are applicable to the entire Program shall"
, "be treated as though they were included in this License, to the extent"
, "that they are valid under applicable law. If additional permissions"
, "apply only to part of the Program, that part may be used separately"
, "under those permissions, but the entire Program remains governed by"
, "this License without regard to the additional permissions."
, ""
, " When you convey a copy of a covered work, you may at your option"
, "remove any additional permissions from that copy, or from any part of"
, "it. (Additional permissions may be written to require their own"
, "removal in certain cases when you modify the work.) You may place"
, "additional permissions on material, added by you to a covered work,"
, "for which you have or can give appropriate copyright permission."
, ""
, " Notwithstanding any other provision of this License, for material you"
, "add to a covered work, you may (if authorized by the copyright holders of"
, "that material) supplement the terms of this License with terms:"
, ""
, " a) Disclaiming warranty or limiting liability differently from the"
, " terms of sections 15 and 16 of this License; or"
, ""
, " b) Requiring preservation of specified reasonable legal notices or"
, " author attributions in that material or in the Appropriate Legal"
, " Notices displayed by works containing it; or"
, ""
, " c) Prohibiting misrepresentation of the origin of that material, or"
, " requiring that modified versions of such material be marked in"
, " reasonable ways as different from the original version; or"
, ""
, " d) Limiting the use for publicity purposes of names of licensors or"
, " authors of the material; or"
, ""
, " e) Declining to grant rights under trademark law for use of some"
, " trade names, trademarks, or service marks; or"
, ""
, " f) Requiring indemnification of licensors and authors of that"
, " material by anyone who conveys the material (or modified versions of"
, " it) with contractual assumptions of liability to the recipient, for"
, " any liability that these contractual assumptions directly impose on"
, " those licensors and authors."
, ""
, " All other non-permissive additional terms are considered \"further"
, "restrictions\" within the meaning of section 10. If the Program as you"
, "received it, or any part of it, contains a notice stating that it is"
, "governed by this License along with a term that is a further"
, "restriction, you may remove that term. If a license document contains"
, "a further restriction but permits relicensing or conveying under this"
, "License, you may add to a covered work material governed by the terms"
, "of that license document, provided that the further restriction does"
, "not survive such relicensing or conveying."
, ""
, " If you add terms to a covered work in accord with this section, you"
, "must place, in the relevant source files, a statement of the"
, "additional terms that apply to those files, or a notice indicating"
, "where to find the applicable terms."
, ""
, " Additional terms, permissive or non-permissive, may be stated in the"
, "form of a separately written license, or stated as exceptions;"
, "the above requirements apply either way."
, ""
, " 8. Termination."
, ""
, " You may not propagate or modify a covered work except as expressly"
, "provided under this License. Any attempt otherwise to propagate or"
, "modify it is void, and will automatically terminate your rights under"
, "this License (including any patent licenses granted under the third"
, "paragraph of section 11)."
, ""
, " However, if you cease all violation of this License, then your"
, "license from a particular copyright holder is reinstated (a)"
, "provisionally, unless and until the copyright holder explicitly and"
, "finally terminates your license, and (b) permanently, if the copyright"
, "holder fails to notify you of the violation by some reasonable means"
, "prior to 60 days after the cessation."
, ""
, " Moreover, your license from a particular copyright holder is"
, "reinstated permanently if the copyright holder notifies you of the"
, "violation by some reasonable means, this is the first time you have"
, "received notice of violation of this License (for any work) from that"
, "copyright holder, and you cure the violation prior to 30 days after"
, "your receipt of the notice."
, ""
, " Termination of your rights under this section does not terminate the"
, "licenses of parties who have received copies or rights from you under"
, "this License. If your rights have been terminated and not permanently"
, "reinstated, you do not qualify to receive new licenses for the same"
, "material under section 10."
, ""
, " 9. Acceptance Not Required for Having Copies."
, ""
, " You are not required to accept this License in order to receive or"
, "run a copy of the Program. Ancillary propagation of a covered work"
, "occurring solely as a consequence of using peer-to-peer transmission"
, "to receive a copy likewise does not require acceptance. However,"
, "nothing other than this License grants you permission to propagate or"
, "modify any covered work. These actions infringe copyright if you do"
, "not accept this License. Therefore, by modifying or propagating a"
, "covered work, you indicate your acceptance of this License to do so."
, ""
, " 10. Automatic Licensing of Downstream Recipients."
, ""
, " Each time you convey a covered work, the recipient automatically"
, "receives a license from the original licensors, to run, modify and"
, "propagate that work, subject to this License. You are not responsible"
, "for enforcing compliance by third parties with this License."
, ""
, " An \"entity transaction\" is a transaction transferring control of an"
, "organization, or substantially all assets of one, or subdividing an"
, "organization, or merging organizations. If propagation of a covered"
, "work results from an entity transaction, each party to that"
, "transaction who receives a copy of the work also receives whatever"
, "licenses to the work the party's predecessor in interest had or could"
, "give under the previous paragraph, plus a right to possession of the"
, "Corresponding Source of the work from the predecessor in interest, if"
, "the predecessor has it or can get it with reasonable efforts."
, ""
, " You may not impose any further restrictions on the exercise of the"
, "rights granted or affirmed under this License. For example, you may"
, "not impose a license fee, royalty, or other charge for exercise of"
, "rights granted under this License, and you may not initiate litigation"
, "(including a cross-claim or counterclaim in a lawsuit) alleging that"
, "any patent claim is infringed by making, using, selling, offering for"
, "sale, or importing the Program or any portion of it."
, ""
, " 11. Patents."
, ""
, " A \"contributor\" is a copyright holder who authorizes use under this"
, "License of the Program or a work on which the Program is based. The"
, "work thus licensed is called the contributor's \"contributor version\"."
, ""
, " A contributor's \"essential patent claims\" are all patent claims"
, "owned or controlled by the contributor, whether already acquired or"
, "hereafter acquired, that would be infringed by some manner, permitted"
, "by this License, of making, using, or selling its contributor version,"
, "but do not include claims that would be infringed only as a"
, "consequence of further modification of the contributor version. For"
, "purposes of this definition, \"control\" includes the right to grant"
, "patent sublicenses in a manner consistent with the requirements of"
, "this License."
, ""
, " Each contributor grants you a non-exclusive, worldwide, royalty-free"
, "patent license under the contributor's essential patent claims, to"
, "make, use, sell, offer for sale, import and otherwise run, modify and"
, "propagate the contents of its contributor version."
, ""
, " In the following three paragraphs, a \"patent license\" is any express"
, "agreement or commitment, however denominated, not to enforce a patent"
, "(such as an express permission to practice a patent or covenant not to"
, "sue for patent infringement). To \"grant\" such a patent license to a"
, "party means to make such an agreement or commitment not to enforce a"
, "patent against the party."
, ""
, " If you convey a covered work, knowingly relying on a patent license,"
, "and the Corresponding Source of the work is not available for anyone"
, "to copy, free of charge and under the terms of this License, through a"
, "publicly available network server or other readily accessible means,"
, "then you must either (1) cause the Corresponding Source to be so"
, "available, or (2) arrange to deprive yourself of the benefit of the"
, "patent license for this particular work, or (3) arrange, in a manner"
, "consistent with the requirements of this License, to extend the patent"
, "license to downstream recipients. \"Knowingly relying\" means you have"
, "actual knowledge that, but for the patent license, your conveying the"
, "covered work in a country, or your recipient's use of the covered work"
, "in a country, would infringe one or more identifiable patents in that"
, "country that you have reason to believe are valid."
, ""
, " If, pursuant to or in connection with a single transaction or"
, "arrangement, you convey, or propagate by procuring conveyance of, a"
, "covered work, and grant a patent license to some of the parties"
, "receiving the covered work authorizing them to use, propagate, modify"
, "or convey a specific copy of the covered work, then the patent license"
, "you grant is automatically extended to all recipients of the covered"
, "work and works based on it."
, ""
, " A patent license is \"discriminatory\" if it does not include within"
, "the scope of its coverage, prohibits the exercise of, or is"
, "conditioned on the non-exercise of one or more of the rights that are"
, "specifically granted under this License. You may not convey a covered"
, "work if you are a party to an arrangement with a third party that is"
, "in the business of distributing software, under which you make payment"
, "to the third party based on the extent of your activity of conveying"
, "the work, and under which the third party grants, to any of the"
, "parties who would receive the covered work from you, a discriminatory"
, "patent license (a) in connection with copies of the covered work"
, "conveyed by you (or copies made from those copies), or (b) primarily"
, "for and in connection with specific products or compilations that"
, "contain the covered work, unless you entered into that arrangement,"
, "or that patent license was granted, prior to 28 March 2007."
, ""
, " Nothing in this License shall be construed as excluding or limiting"
, "any implied license or other defenses to infringement that may"
, "otherwise be available to you under applicable patent law."
, ""
, " 12. No Surrender of Others' Freedom."
, ""
, " If conditions are imposed on you (whether by court order, agreement or"
, "otherwise) that contradict the conditions of this License, they do not"
, "excuse you from the conditions of this License. If you cannot convey a"
, "covered work so as to satisfy simultaneously your obligations under this"
, "License and any other pertinent obligations, then as a consequence you may"
, "not convey it at all. For example, if you agree to terms that obligate you"
, "to collect a royalty for further conveying from those to whom you convey"
, "the Program, the only way you could satisfy both those terms and this"
, "License would be to refrain entirely from conveying the Program."
, ""
, " 13. Remote Network Interaction; Use with the GNU General Public License."
, ""
, " Notwithstanding any other provision of this License, if you modify the"
, "Program, your modified version must prominently offer all users"
, "interacting with it remotely through a computer network (if your version"
, "supports such interaction) an opportunity to receive the Corresponding"
, "Source of your version by providing access to the Corresponding Source"
, "from a network server at no charge, through some standard or customary"
, "means of facilitating copying of software. This Corresponding Source"
, "shall include the Corresponding Source for any work covered by version 3"
, "of the GNU General Public License that is incorporated pursuant to the"
, "following paragraph."
, ""
, " Notwithstanding any other provision of this License, you have"
, "permission to link or combine any covered work with a work licensed"
, "under version 3 of the GNU General Public License into a single"
, "combined work, and to convey the resulting work. The terms of this"
, "License will continue to apply to the part which is the covered work,"
, "but the work with which it is combined will remain governed by version"
, "3 of the GNU General Public License."
, ""
, " 14. Revised Versions of this License."
, ""
, " The Free Software Foundation may publish revised and/or new versions of"
, "the GNU Affero General Public License from time to time. Such new versions"
, "will be similar in spirit to the present version, but may differ in detail to"
, "address new problems or concerns."
, ""
, " Each version is given a distinguishing version number. If the"
, "Program specifies that a certain numbered version of the GNU Affero General"
, "Public License \"or any later version\" applies to it, you have the"
, "option of following the terms and conditions either of that numbered"
, "version or of any later version published by the Free Software"
, "Foundation. If the Program does not specify a version number of the"
, "GNU Affero General Public License, you may choose any version ever published"
, "by the Free Software Foundation."
, ""
, " If the Program specifies that a proxy can decide which future"
, "versions of the GNU Affero General Public License can be used, that proxy's"
, "public statement of acceptance of a version permanently authorizes you"
, "to choose that version for the Program."
, ""
, " Later license versions may give you additional or different"
, "permissions. However, no additional obligations are imposed on any"
, "author or copyright holder as a result of your choosing to follow a"
, "later version."
, ""
, " 15. Disclaimer of Warranty."
, ""
, " THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY"
, "APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT"
, "HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY"
, "OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,"
, "THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR"
, "PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM"
, "IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF"
, "ALL NECESSARY SERVICING, REPAIR OR CORRECTION."
, ""
, " 16. Limitation of Liability."
, ""
, " IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING"
, "WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS"
, "THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY"
, "GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE"
, "USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF"
, "DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD"
, "PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),"
, "EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF"
, "SUCH DAMAGES."
, ""
, " 17. Interpretation of Sections 15 and 16."
, ""
, " If the disclaimer of warranty and limitation of liability provided"
, "above cannot be given local legal effect according to their terms,"
, "reviewing courts shall apply local law that most closely approximates"
, "an absolute waiver of all civil liability in connection with the"
, "Program, unless a warranty or assumption of liability accompanies a"
, "copy of the Program in return for a fee."
, ""
, " END OF TERMS AND CONDITIONS"
, ""
, " How to Apply These Terms to Your New Programs"
, ""
, " If you develop a new program, and you want it to be of the greatest"
, "possible use to the public, the best way to achieve this is to make it"
, "free software which everyone can redistribute and change under these terms."
, ""
, " To do so, attach the following notices to the program. It is safest"
, "to attach them to the start of each source file to most effectively"
, "state the exclusion of warranty; and each file should have at least"
, "the \"copyright\" line and a pointer to where the full notice is found."
, ""
, " <one line to give the program's name and a brief idea of what it does.>"
, " Copyright (C) <year> <name of author>"
, ""
, " 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/>."
, ""
, "Also add information on how to contact you by electronic and paper mail."
, ""
, " If your software can interact with users remotely through a computer"
, "network, you should also make sure that it provides a way for users to"
, "get its source. For example, if your program is a web application, its"
, "interface could display a \"Source\" link that leads users to an archive"
, "of the code. There are many ways you could offer source, and different"
, "solutions will be better for different programs; see section 13 for the"
, "specific requirements."
, ""
, " You should also get your employer (if you work as a programmer) or school,"
, "if any, to sign a \"copyright disclaimer\" for the program, if necessary."
, "For more information on this, and how to apply and follow the GNU AGPL, see"
, "<http://www.gnu.org/licenses/>."
]
lgpl21 :: License
lgpl21 = unlines
[ " GNU LESSER GENERAL PUBLIC LICENSE"
, " Version 2.1, February 1999"
, ""
, " Copyright (C) 1991, 1999 Free Software Foundation, Inc."
, " 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA"
, " Everyone is permitted to copy and distribute verbatim copies"
, " of this license document, but changing it is not allowed."
, ""
, "[This is the first released version of the Lesser GPL. It also counts"
, " as the successor of the GNU Library Public License, version 2, hence"
, " the version number 2.1.]"
, ""
, " Preamble"
, ""
, " The licenses for most software are designed to take away your"
, "freedom to share and change it. By contrast, the GNU General Public"
, "Licenses are intended to guarantee your freedom to share and change"
, "free software--to make sure the software is free for all its users."
, ""
, " This license, the Lesser General Public License, applies to some"
, "specially designated software packages--typically libraries--of the"
, "Free Software Foundation and other authors who decide to use it. You"
, "can use it too, but we suggest you first think carefully about whether"
, "this license or the ordinary General Public License is the better"
, "strategy to use in any particular case, based on the explanations below."
, ""
, " When we speak of free software, we are referring to freedom of use,"
, "not price. Our General Public Licenses are designed to make sure that"
, "you have the freedom to distribute copies of free software (and charge"
, "for this service if you wish); that you receive source code or can get"
, "it if you want it; that you can change the software and use pieces of"
, "it in new free programs; and that you are informed that you can do"
, "these things."
, ""
, " To protect your rights, we need to make restrictions that forbid"
, "distributors to deny you these rights or to ask you to surrender these"
, "rights. These restrictions translate to certain responsibilities for"
, "you if you distribute copies of the library or if you modify it."
, ""
, " For example, if you distribute copies of the library, whether gratis"
, "or for a fee, you must give the recipients all the rights that we gave"
, "you. You must make sure that they, too, receive or can get the source"
, "code. If you link other code with the library, you must provide"
, "complete object files to the recipients, so that they can relink them"
, "with the library after making changes to the library and recompiling"
, "it. And you must show them these terms so they know their rights."
, ""
, " We protect your rights with a two-step method: (1) we copyright the"
, "library, and (2) we offer you this license, which gives you legal"
, "permission to copy, distribute and/or modify the library."
, ""
, " To protect each distributor, we want to make it very clear that"
, "there is no warranty for the free library. Also, if the library is"
, "modified by someone else and passed on, the recipients should know"
, "that what they have is not the original version, so that the original"
, "author's reputation will not be affected by problems that might be"
, "introduced by others."
, ""
, " Finally, software patents pose a constant threat to the existence of"
, "any free program. We wish to make sure that a company cannot"
, "effectively restrict the users of a free program by obtaining a"
, "restrictive license from a patent holder. Therefore, we insist that"
, "any patent license obtained for a version of the library must be"
, "consistent with the full freedom of use specified in this license."
, ""
, " Most GNU software, including some libraries, is covered by the"
, "ordinary GNU General Public License. This license, the GNU Lesser"
, "General Public License, applies to certain designated libraries, and"
, "is quite different from the ordinary General Public License. We use"
, "this license for certain libraries in order to permit linking those"
, "libraries into non-free programs."
, ""
, " When a program is linked with a library, whether statically or using"
, "a shared library, the combination of the two is legally speaking a"
, "combined work, a derivative of the original library. The ordinary"
, "General Public License therefore permits such linking only if the"
, "entire combination fits its criteria of freedom. The Lesser General"
, "Public License permits more lax criteria for linking other code with"
, "the library."
, ""
, " We call this license the \"Lesser\" General Public License because it"
, "does Less to protect the user's freedom than the ordinary General"
, "Public License. It also provides other free software developers Less"
, "of an advantage over competing non-free programs. These disadvantages"
, "are the reason we use the ordinary General Public License for many"
, "libraries. However, the Lesser license provides advantages in certain"
, "special circumstances."
, ""
, " For example, on rare occasions, there may be a special need to"
, "encourage the widest possible use of a certain library, so that it becomes"
, "a de-facto standard. To achieve this, non-free programs must be"
, "allowed to use the library. A more frequent case is that a free"
, "library does the same job as widely used non-free libraries. In this"
, "case, there is little to gain by limiting the free library to free"
, "software only, so we use the Lesser General Public License."
, ""
, " In other cases, permission to use a particular library in non-free"
, "programs enables a greater number of people to use a large body of"
, "free software. For example, permission to use the GNU C Library in"
, "non-free programs enables many more people to use the whole GNU"
, "operating system, as well as its variant, the GNU/Linux operating"
, "system."
, ""
, " Although the Lesser General Public License is Less protective of the"
, "users' freedom, it does ensure that the user of a program that is"
, "linked with the Library has the freedom and the wherewithal to run"
, "that program using a modified version of the Library."
, ""
, " The precise terms and conditions for copying, distribution and"
, "modification follow. Pay close attention to the difference between a"
, "\"work based on the library\" and a \"work that uses the library\". The"
, "former contains code derived from the library, whereas the latter must"
, "be combined with the library in order to run."
, ""
, " GNU LESSER GENERAL PUBLIC LICENSE"
, " TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION"
, ""
, " 0. This License Agreement applies to any software library or other"
, "program which contains a notice placed by the copyright holder or"
, "other authorized party saying it may be distributed under the terms of"
, "this Lesser General Public License (also called \"this License\")."
, "Each licensee is addressed as \"you\"."
, ""
, " A \"library\" means a collection of software functions and/or data"
, "prepared so as to be conveniently linked with application programs"
, "(which use some of those functions and data) to form executables."
, ""
, " The \"Library\", below, refers to any such software library or work"
, "which has been distributed under these terms. A \"work based on the"
, "Library\" means either the Library or any derivative work under"
, "copyright law: that is to say, a work containing the Library or a"
, "portion of it, either verbatim or with modifications and/or translated"
, "straightforwardly into another language. (Hereinafter, translation is"
, "included without limitation in the term \"modification\".)"
, ""
, " \"Source code\" for a work means the preferred form of the work for"
, "making modifications to it. For a library, complete source code means"
, "all the source code for all modules it contains, plus any associated"
, "interface definition files, plus the scripts used to control compilation"
, "and installation of the library."
, ""
, " Activities other than copying, distribution and modification are not"
, "covered by this License; they are outside its scope. The act of"
, "running a program using the Library is not restricted, and output from"
, "such a program is covered only if its contents constitute a work based"
, "on the Library (independent of the use of the Library in a tool for"
, "writing it). Whether that is true depends on what the Library does"
, "and what the program that uses the Library does."
, ""
, " 1. You may copy and distribute verbatim copies of the Library's"
, "complete source code as you receive it, in any medium, provided that"
, "you conspicuously and appropriately publish on each copy an"
, "appropriate copyright notice and disclaimer of warranty; keep intact"
, "all the notices that refer to this License and to the absence of any"
, "warranty; and distribute a copy of this License along with the"
, "Library."
, ""
, " You may charge a fee for the physical act of transferring a copy,"
, "and you may at your option offer warranty protection in exchange for a"
, "fee."
, ""
, " 2. You may modify your copy or copies of the Library or any portion"
, "of it, thus forming a work based on the Library, and copy and"
, "distribute such modifications or work under the terms of Section 1"
, "above, provided that you also meet all of these conditions:"
, ""
, " a) The modified work must itself be a software library."
, ""
, " b) You must cause the files modified to carry prominent notices"
, " stating that you changed the files and the date of any change."
, ""
, " c) You must cause the whole of the work to be licensed at no"
, " charge to all third parties under the terms of this License."
, ""
, " d) If a facility in the modified Library refers to a function or a"
, " table of data to be supplied by an application program that uses"
, " the facility, other than as an argument passed when the facility"
, " is invoked, then you must make a good faith effort to ensure that,"
, " in the event an application does not supply such function or"
, " table, the facility still operates, and performs whatever part of"
, " its purpose remains meaningful."
, ""
, " (For example, a function in a library to compute square roots has"
, " a purpose that is entirely well-defined independent of the"
, " application. Therefore, Subsection 2d requires that any"
, " application-supplied function or table used by this function must"
, " be optional: if the application does not supply it, the square"
, " root function must still compute square roots.)"
, ""
, "These requirements apply to the modified work as a whole. If"
, "identifiable sections of that work are not derived from the Library,"
, "and can be reasonably considered independent and separate works in"
, "themselves, then this License, and its terms, do not apply to those"
, "sections when you distribute them as separate works. But when you"
, "distribute the same sections as part of a whole which is a work based"
, "on the Library, the distribution of the whole must be on the terms of"
, "this License, whose permissions for other licensees extend to the"
, "entire whole, and thus to each and every part regardless of who wrote"
, "it."
, ""
, "Thus, it is not the intent of this section to claim rights or contest"
, "your rights to work written entirely by you; rather, the intent is to"
, "exercise the right to control the distribution of derivative or"
, "collective works based on the Library."
, ""
, "In addition, mere aggregation of another work not based on the Library"
, "with the Library (or with a work based on the Library) on a volume of"
, "a storage or distribution medium does not bring the other work under"
, "the scope of this License."
, ""
, " 3. You may opt to apply the terms of the ordinary GNU General Public"
, "License instead of this License to a given copy of the Library. To do"
, "this, you must alter all the notices that refer to this License, so"
, "that they refer to the ordinary GNU General Public License, version 2,"
, "instead of to this License. (If a newer version than version 2 of the"
, "ordinary GNU General Public License has appeared, then you can specify"
, "that version instead if you wish.) Do not make any other change in"
, "these notices."
, ""
, " Once this change is made in a given copy, it is irreversible for"
, "that copy, so the ordinary GNU General Public License applies to all"
, "subsequent copies and derivative works made from that copy."
, ""
, " This option is useful when you wish to copy part of the code of"
, "the Library into a program that is not a library."
, ""
, " 4. You may copy and distribute the Library (or a portion or"
, "derivative of it, under Section 2) in object code or executable form"
, "under the terms of Sections 1 and 2 above provided that you accompany"
, "it with the complete corresponding machine-readable source code, which"
, "must be distributed under the terms of Sections 1 and 2 above on a"
, "medium customarily used for software interchange."
, ""
, " If distribution of object code is made by offering access to copy"
, "from a designated place, then offering equivalent access to copy the"
, "source code from the same place satisfies the requirement to"
, "distribute the source code, even though third parties are not"
, "compelled to copy the source along with the object code."
, ""
, " 5. A program that contains no derivative of any portion of the"
, "Library, but is designed to work with the Library by being compiled or"
, "linked with it, is called a \"work that uses the Library\". Such a"
, "work, in isolation, is not a derivative work of the Library, and"
, "therefore falls outside the scope of this License."
, ""
, " However, linking a \"work that uses the Library\" with the Library"
, "creates an executable that is a derivative of the Library (because it"
, "contains portions of the Library), rather than a \"work that uses the"
, "library\". The executable is therefore covered by this License."
, "Section 6 states terms for distribution of such executables."
, ""
, " When a \"work that uses the Library\" uses material from a header file"
, "that is part of the Library, the object code for the work may be a"
, "derivative work of the Library even though the source code is not."
, "Whether this is true is especially significant if the work can be"
, "linked without the Library, or if the work is itself a library. The"
, "threshold for this to be true is not precisely defined by law."
, ""
, " If such an object file uses only numerical parameters, data"
, "structure layouts and accessors, and small macros and small inline"
, "functions (ten lines or less in length), then the use of the object"
, "file is unrestricted, regardless of whether it is legally a derivative"
, "work. (Executables containing this object code plus portions of the"
, "Library will still fall under Section 6.)"
, ""
, " Otherwise, if the work is a derivative of the Library, you may"
, "distribute the object code for the work under the terms of Section 6."
, "Any executables containing that work also fall under Section 6,"
, "whether or not they are linked directly with the Library itself."
, ""
, " 6. As an exception to the Sections above, you may also combine or"
, "link a \"work that uses the Library\" with the Library to produce a"
, "work containing portions of the Library, and distribute that work"
, "under terms of your choice, provided that the terms permit"
, "modification of the work for the customer's own use and reverse"
, "engineering for debugging such modifications."
, ""
, " You must give prominent notice with each copy of the work that the"
, "Library is used in it and that the Library and its use are covered by"
, "this License. You must supply a copy of this License. If the work"
, "during execution displays copyright notices, you must include the"
, "copyright notice for the Library among them, as well as a reference"
, "directing the user to the copy of this License. Also, you must do one"
, "of these things:"
, ""
, " a) Accompany the work with the complete corresponding"
, " machine-readable source code for the Library including whatever"
, " changes were used in the work (which must be distributed under"
, " Sections 1 and 2 above); and, if the work is an executable linked"
, " with the Library, with the complete machine-readable \"work that"
, " uses the Library\", as object code and/or source code, so that the"
, " user can modify the Library and then relink to produce a modified"
, " executable containing the modified Library. (It is understood"
, " that the user who changes the contents of definitions files in the"
, " Library will not necessarily be able to recompile the application"
, " to use the modified definitions.)"
, ""
, " b) Use a suitable shared library mechanism for linking with the"
, " Library. A suitable mechanism is one that (1) uses at run time a"
, " copy of the library already present on the user's computer system,"
, " rather than copying library functions into the executable, and (2)"
, " will operate properly with a modified version of the library, if"
, " the user installs one, as long as the modified version is"
, " interface-compatible with the version that the work was made with."
, ""
, " c) Accompany the work with a written offer, valid for at"
, " least three years, to give the same user the materials"
, " specified in Subsection 6a, above, for a charge no more"
, " than the cost of performing this distribution."
, ""
, " d) If distribution of the work is made by offering access to copy"
, " from a designated place, offer equivalent access to copy the above"
, " specified materials from the same place."
, ""
, " e) Verify that the user has already received a copy of these"
, " materials or that you have already sent this user a copy."
, ""
, " For an executable, the required form of the \"work that uses the"
, "Library\" must include any data and utility programs needed for"
, "reproducing the executable from it. However, as a special exception,"
, "the materials to be distributed need not include anything that is"
, "normally distributed (in either source or binary form) with the major"
, "components (compiler, kernel, and so on) of the operating system on"
, "which the executable runs, unless that component itself accompanies"
, "the executable."
, ""
, " It may happen that this requirement contradicts the license"
, "restrictions of other proprietary libraries that do not normally"
, "accompany the operating system. Such a contradiction means you cannot"
, "use both them and the Library together in an executable that you"
, "distribute."
, ""
, " 7. You may place library facilities that are a work based on the"
, "Library side-by-side in a single library together with other library"
, "facilities not covered by this License, and distribute such a combined"
, "library, provided that the separate distribution of the work based on"
, "the Library and of the other library facilities is otherwise"
, "permitted, and provided that you do these two things:"
, ""
, " a) Accompany the combined library with a copy of the same work"
, " based on the Library, uncombined with any other library"
, " facilities. This must be distributed under the terms of the"
, " Sections above."
, ""
, " b) Give prominent notice with the combined library of the fact"
, " that part of it is a work based on the Library, and explaining"
, " where to find the accompanying uncombined form of the same work."
, ""
, " 8. You may not copy, modify, sublicense, link with, or distribute"
, "the Library except as expressly provided under this License. Any"
, "attempt otherwise to copy, modify, sublicense, link with, or"
, "distribute the Library is void, and will automatically terminate your"
, "rights under this License. However, parties who have received copies,"
, "or rights, from you under this License will not have their licenses"
, "terminated so long as such parties remain in full compliance."
, ""
, " 9. You are not required to accept this License, since you have not"
, "signed it. However, nothing else grants you permission to modify or"
, "distribute the Library or its derivative works. These actions are"
, "prohibited by law if you do not accept this License. Therefore, by"
, "modifying or distributing the Library (or any work based on the"
, "Library), you indicate your acceptance of this License to do so, and"
, "all its terms and conditions for copying, distributing or modifying"
, "the Library or works based on it."
, ""
, " 10. Each time you redistribute the Library (or any work based on the"
, "Library), the recipient automatically receives a license from the"
, "original licensor to copy, distribute, link with or modify the Library"
, "subject to these terms and conditions. You may not impose any further"
, "restrictions on the recipients' exercise of the rights granted herein."
, "You are not responsible for enforcing compliance by third parties with"
, "this License."
, ""
, " 11. If, as a consequence of a court judgment or allegation of patent"
, "infringement or for any other reason (not limited to patent issues),"
, "conditions are imposed on you (whether by court order, agreement or"
, "otherwise) that contradict the conditions of this License, they do not"
, "excuse you from the conditions of this License. If you cannot"
, "distribute so as to satisfy simultaneously your obligations under this"
, "License and any other pertinent obligations, then as a consequence you"
, "may not distribute the Library at all. For example, if a patent"
, "license would not permit royalty-free redistribution of the Library by"
, "all those who receive copies directly or indirectly through you, then"
, "the only way you could satisfy both it and this License would be to"
, "refrain entirely from distribution of the Library."
, ""
, "If any portion of this section is held invalid or unenforceable under any"
, "particular circumstance, the balance of the section is intended to apply,"
, "and the section as a whole is intended to apply in other circumstances."
, ""
, "It is not the purpose of this section to induce you to infringe any"
, "patents or other property right claims or to contest validity of any"
, "such claims; this section has the sole purpose of protecting the"
, "integrity of the free software distribution system which is"
, "implemented by public license practices. Many people have made"
, "generous contributions to the wide range of software distributed"
, "through that system in reliance on consistent application of that"
, "system; it is up to the author/donor to decide if he or she is willing"
, "to distribute software through any other system and a licensee cannot"
, "impose that choice."
, ""
, "This section is intended to make thoroughly clear what is believed to"
, "be a consequence of the rest of this License."
, ""
, " 12. If the distribution and/or use of the Library is restricted in"
, "certain countries either by patents or by copyrighted interfaces, the"
, "original copyright holder who places the Library under this License may add"
, "an explicit geographical distribution limitation excluding those countries,"
, "so that distribution is permitted only in or among countries not thus"
, "excluded. In such case, this License incorporates the limitation as if"
, "written in the body of this License."
, ""
, " 13. The Free Software Foundation may publish revised and/or new"
, "versions of the Lesser General Public License from time to time."
, "Such new versions will be similar in spirit to the present version,"
, "but may differ in detail to address new problems or concerns."
, ""
, "Each version is given a distinguishing version number. If the Library"
, "specifies a version number of this License which applies to it and"
, "\"any later version\", you have the option of following the terms and"
, "conditions either of that version or of any later version published by"
, "the Free Software Foundation. If the Library does not specify a"
, "license version number, you may choose any version ever published by"
, "the Free Software Foundation."
, ""
, " 14. If you wish to incorporate parts of the Library into other free"
, "programs whose distribution conditions are incompatible with these,"
, "write to the author to ask for permission. For software which is"
, "copyrighted by the Free Software Foundation, write to the Free"
, "Software Foundation; we sometimes make exceptions for this. Our"
, "decision will be guided by the two goals of preserving the free status"
, "of all derivatives of our free software and of promoting the sharing"
, "and reuse of software generally."
, ""
, " NO WARRANTY"
, ""
, " 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO"
, "WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW."
, "EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR"
, "OTHER PARTIES PROVIDE THE LIBRARY \"AS IS\" WITHOUT WARRANTY OF ANY"
, "KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE"
, "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR"
, "PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE"
, "LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME"
, "THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION."
, ""
, " 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN"
, "WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY"
, "AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU"
, "FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR"
, "CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE"
, "LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING"
, "RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A"
, "FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF"
, "SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH"
, "DAMAGES."
, ""
, " END OF TERMS AND CONDITIONS"
, ""
, " How to Apply These Terms to Your New Libraries"
, ""
, " If you develop a new library, and you want it to be of the greatest"
, "possible use to the public, we recommend making it free software that"
, "everyone can redistribute and change. You can do so by permitting"
, "redistribution under these terms (or, alternatively, under the terms of the"
, "ordinary General Public License)."
, ""
, " To apply these terms, attach the following notices to the library. It is"
, "safest to attach them to the start of each source file to most effectively"
, "convey the exclusion of warranty; and each file should have at least the"
, "\"copyright\" line and a pointer to where the full notice is found."
, ""
, " <one line to give the library's name and a brief idea of what it does.>"
, " Copyright (C) <year> <name of author>"
, ""
, " This library is free software; you can redistribute it and/or"
, " modify it under the terms of the GNU Lesser General Public"
, " License as published by the Free Software Foundation; either"
, " version 2.1 of the License, or (at your option) any later version."
, ""
, " This library is distributed in the hope that it will be useful,"
, " but WITHOUT ANY WARRANTY; without even the implied warranty of"
, " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU"
, " Lesser General Public License for more details."
, ""
, " You should have received a copy of the GNU Lesser General Public"
, " License along with this library; if not, write to the Free Software"
, " Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA"
, ""
, "Also add information on how to contact you by electronic and paper mail."
, ""
, "You should also get your employer (if you work as a programmer) or your"
, "school, if any, to sign a \"copyright disclaimer\" for the library, if"
, "necessary. Here is a sample; alter the names:"
, ""
, " Yoyodyne, Inc., hereby disclaims all copyright interest in the"
, " library `Frob' (a library for tweaking knobs) written by James Random Hacker."
, ""
, " <signature of Ty Coon>, 1 April 1990"
, " Ty Coon, President of Vice"
, ""
, "That's all there is to it!"
]
lgpl3 :: License
lgpl3 = unlines
[ " GNU LESSER GENERAL PUBLIC LICENSE"
, " Version 3, 29 June 2007"
, ""
, " Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>"
, " Everyone is permitted to copy and distribute verbatim copies"
, " of this license document, but changing it is not allowed."
, ""
, ""
, " This version of the GNU Lesser General Public License incorporates"
, "the terms and conditions of version 3 of the GNU General Public"
, "License, supplemented by the additional permissions listed below."
, ""
, " 0. Additional Definitions."
, ""
, " As used herein, \"this License\" refers to version 3 of the GNU Lesser"
, "General Public License, and the \"GNU GPL\" refers to version 3 of the GNU"
, "General Public License."
, ""
, " \"The Library\" refers to a covered work governed by this License,"
, "other than an Application or a Combined Work as defined below."
, ""
, " An \"Application\" is any work that makes use of an interface provided"
, "by the Library, but which is not otherwise based on the Library."
, "Defining a subclass of a class defined by the Library is deemed a mode"
, "of using an interface provided by the Library."
, ""
, " A \"Combined Work\" is a work produced by combining or linking an"
, "Application with the Library. The particular version of the Library"
, "with which the Combined Work was made is also called the \"Linked"
, "Version\"."
, ""
, " The \"Minimal Corresponding Source\" for a Combined Work means the"
, "Corresponding Source for the Combined Work, excluding any source code"
, "for portions of the Combined Work that, considered in isolation, are"
, "based on the Application, and not on the Linked Version."
, ""
, " The \"Corresponding Application Code\" for a Combined Work means the"
, "object code and/or source code for the Application, including any data"
, "and utility programs needed for reproducing the Combined Work from the"
, "Application, but excluding the System Libraries of the Combined Work."
, ""
, " 1. Exception to Section 3 of the GNU GPL."
, ""
, " You may convey a covered work under sections 3 and 4 of this License"
, "without being bound by section 3 of the GNU GPL."
, ""
, " 2. Conveying Modified Versions."
, ""
, " If you modify a copy of the Library, and, in your modifications, a"
, "facility refers to a function or data to be supplied by an Application"
, "that uses the facility (other than as an argument passed when the"
, "facility is invoked), then you may convey a copy of the modified"
, "version:"
, ""
, " a) under this License, provided that you make a good faith effort to"
, " ensure that, in the event an Application does not supply the"
, " function or data, the facility still operates, and performs"
, " whatever part of its purpose remains meaningful, or"
, ""
, " b) under the GNU GPL, with none of the additional permissions of"
, " this License applicable to that copy."
, ""
, " 3. Object Code Incorporating Material from Library Header Files."
, ""
, " The object code form of an Application may incorporate material from"
, "a header file that is part of the Library. You may convey such object"
, "code under terms of your choice, provided that, if the incorporated"
, "material is not limited to numerical parameters, data structure"
, "layouts and accessors, or small macros, inline functions and templates"
, "(ten or fewer lines in length), you do both of the following:"
, ""
, " a) Give prominent notice with each copy of the object code that the"
, " Library is used in it and that the Library and its use are"
, " covered by this License."
, ""
, " b) Accompany the object code with a copy of the GNU GPL and this license"
, " document."
, ""
, " 4. Combined Works."
, ""
, " You may convey a Combined Work under terms of your choice that,"
, "taken together, effectively do not restrict modification of the"
, "portions of the Library contained in the Combined Work and reverse"
, "engineering for debugging such modifications, if you also do each of"
, "the following:"
, ""
, " a) Give prominent notice with each copy of the Combined Work that"
, " the Library is used in it and that the Library and its use are"
, " covered by this License."
, ""
, " b) Accompany the Combined Work with a copy of the GNU GPL and this license"
, " document."
, ""
, " c) For a Combined Work that displays copyright notices during"
, " execution, include the copyright notice for the Library among"
, " these notices, as well as a reference directing the user to the"
, " copies of the GNU GPL and this license document."
, ""
, " d) Do one of the following:"
, ""
, " 0) Convey the Minimal Corresponding Source under the terms of this"
, " License, and the Corresponding Application Code in a form"
, " suitable for, and under terms that permit, the user to"
, " recombine or relink the Application with a modified version of"
, " the Linked Version to produce a modified Combined Work, in the"
, " manner specified by section 6 of the GNU GPL for conveying"
, " Corresponding Source."
, ""
, " 1) Use a suitable shared library mechanism for linking with the"
, " Library. A suitable mechanism is one that (a) uses at run time"
, " a copy of the Library already present on the user's computer"
, " system, and (b) will operate properly with a modified version"
, " of the Library that is interface-compatible with the Linked"
, " Version."
, ""
, " e) Provide Installation Information, but only if you would otherwise"
, " be required to provide such information under section 6 of the"
, " GNU GPL, and only to the extent that such information is"
, " necessary to install and execute a modified version of the"
, " Combined Work produced by recombining or relinking the"
, " Application with a modified version of the Linked Version. (If"
, " you use option 4d0, the Installation Information must accompany"
, " the Minimal Corresponding Source and Corresponding Application"
, " Code. If you use option 4d1, you must provide the Installation"
, " Information in the manner specified by section 6 of the GNU GPL"
, " for conveying Corresponding Source.)"
, ""
, " 5. Combined Libraries."
, ""
, " You may place library facilities that are a work based on the"
, "Library side by side in a single library together with other library"
, "facilities that are not Applications and are not covered by this"
, "License, and convey such a combined library under terms of your"
, "choice, if you do both of the following:"
, ""
, " a) Accompany the combined library with a copy of the same work based"
, " on the Library, uncombined with any other library facilities,"
, " conveyed under the terms of this License."
, ""
, " b) Give prominent notice with the combined library that part of it"
, " is a work based on the Library, and explaining where to find the"
, " accompanying uncombined form of the same work."
, ""
, " 6. Revised Versions of the GNU Lesser General Public License."
, ""
, " The Free Software Foundation may publish revised and/or new versions"
, "of the GNU Lesser General Public License from time to time. Such new"
, "versions will be similar in spirit to the present version, but may"
, "differ in detail to address new problems or concerns."
, ""
, " Each version is given a distinguishing version number. If the"
, "Library as you received it specifies that a certain numbered version"
, "of the GNU Lesser General Public License \"or any later version\""
, "applies to it, you have the option of following the terms and"
, "conditions either of that published version or of any later version"
, "published by the Free Software Foundation. If the Library as you"
, "received it does not specify a version number of the GNU Lesser"
, "General Public License, you may choose any version of the GNU Lesser"
, "General Public License ever published by the Free Software Foundation."
, ""
, " If the Library as you received it specifies that a proxy can decide"
, "whether future versions of the GNU Lesser General Public License shall"
, "apply, that proxy's public statement of acceptance of any version is"
, "permanent authorization for you to choose that version for the"
, "Library."
]
apache20 :: License
apache20 = unlines
[ ""
, " Apache License"
, " Version 2.0, January 2004"
, " http://www.apache.org/licenses/"
, ""
, " TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION"
, ""
, " 1. Definitions."
, ""
, " \"License\" shall mean the terms and conditions for use, reproduction,"
, " and distribution as defined by Sections 1 through 9 of this document."
, ""
, " \"Licensor\" shall mean the copyright owner or entity authorized by"
, " the copyright owner that is granting the License."
, ""
, " \"Legal Entity\" shall mean the union of the acting entity and all"
, " other entities that control, are controlled by, or are under common"
, " control with that entity. For the purposes of this definition,"
, " \"control\" means (i) the power, direct or indirect, to cause the"
, " direction or management of such entity, whether by contract or"
, " otherwise, or (ii) ownership of fifty percent (50%) or more of the"
, " outstanding shares, or (iii) beneficial ownership of such entity."
, ""
, " \"You\" (or \"Your\") shall mean an individual or Legal Entity"
, " exercising permissions granted by this License."
, ""
, " \"Source\" form shall mean the preferred form for making modifications,"
, " including but not limited to software source code, documentation"
, " source, and configuration files."
, ""
, " \"Object\" form shall mean any form resulting from mechanical"
, " transformation or translation of a Source form, including but"
, " not limited to compiled object code, generated documentation,"
, " and conversions to other media types."
, ""
, " \"Work\" shall mean the work of authorship, whether in Source or"
, " Object form, made available under the License, as indicated by a"
, " copyright notice that is included in or attached to the work"
, " (an example is provided in the Appendix below)."
, ""
, " \"Derivative Works\" shall mean any work, whether in Source or Object"
, " form, that is based on (or derived from) the Work and for which the"
, " editorial revisions, annotations, elaborations, or other modifications"
, " represent, as a whole, an original work of authorship. For the purposes"
, " of this License, Derivative Works shall not include works that remain"
, " separable from, or merely link (or bind by name) to the interfaces of,"
, " the Work and Derivative Works thereof."
, ""
, " \"Contribution\" shall mean any work of authorship, including"
, " the original version of the Work and any modifications or additions"
, " to that Work or Derivative Works thereof, that is intentionally"
, " submitted to Licensor for inclusion in the Work by the copyright owner"
, " or by an individual or Legal Entity authorized to submit on behalf of"
, " the copyright owner. For the purposes of this definition, \"submitted\""
, " means any form of electronic, verbal, or written communication sent"
, " to the Licensor or its representatives, including but not limited to"
, " communication on electronic mailing lists, source code control systems,"
, " and issue tracking systems that are managed by, or on behalf of, the"
, " Licensor for the purpose of discussing and improving the Work, but"
, " excluding communication that is conspicuously marked or otherwise"
, " designated in writing by the copyright owner as \"Not a Contribution.\""
, ""
, " \"Contributor\" shall mean Licensor and any individual or Legal Entity"
, " on behalf of whom a Contribution has been received by Licensor and"
, " subsequently incorporated within the Work."
, ""
, " 2. Grant of Copyright License. Subject to the terms and conditions of"
, " this License, each Contributor hereby grants to You a perpetual,"
, " worldwide, non-exclusive, no-charge, royalty-free, irrevocable"
, " copyright license to reproduce, prepare Derivative Works of,"
, " publicly display, publicly perform, sublicense, and distribute the"
, " Work and such Derivative Works in Source or Object form."
, ""
, " 3. Grant of Patent License. Subject to the terms and conditions of"
, " this License, each Contributor hereby grants to You a perpetual,"
, " worldwide, non-exclusive, no-charge, royalty-free, irrevocable"
, " (except as stated in this section) patent license to make, have made,"
, " use, offer to sell, sell, import, and otherwise transfer the Work,"
, " where such license applies only to those patent claims licensable"
, " by such Contributor that are necessarily infringed by their"
, " Contribution(s) alone or by combination of their Contribution(s)"
, " with the Work to which such Contribution(s) was submitted. If You"
, " institute patent litigation against any entity (including a"
, " cross-claim or counterclaim in a lawsuit) alleging that the Work"
, " or a Contribution incorporated within the Work constitutes direct"
, " or contributory patent infringement, then any patent licenses"
, " granted to You under this License for that Work shall terminate"
, " as of the date such litigation is filed."
, ""
, " 4. Redistribution. You may reproduce and distribute copies of the"
, " Work or Derivative Works thereof in any medium, with or without"
, " modifications, and in Source or Object form, provided that You"
, " meet the following conditions:"
, ""
, " (a) You must give any other recipients of the Work or"
, " Derivative Works a copy of this License; and"
, ""
, " (b) You must cause any modified files to carry prominent notices"
, " stating that You changed the files; and"
, ""
, " (c) You must retain, in the Source form of any Derivative Works"
, " that You distribute, all copyright, patent, trademark, and"
, " attribution notices from the Source form of the Work,"
, " excluding those notices that do not pertain to any part of"
, " the Derivative Works; and"
, ""
, " (d) If the Work includes a \"NOTICE\" text file as part of its"
, " distribution, then any Derivative Works that You distribute must"
, " include a readable copy of the attribution notices contained"
, " within such NOTICE file, excluding those notices that do not"
, " pertain to any part of the Derivative Works, in at least one"
, " of the following places: within a NOTICE text file distributed"
, " as part of the Derivative Works; within the Source form or"
, " documentation, if provided along with the Derivative Works; or,"
, " within a display generated by the Derivative Works, if and"
, " wherever such third-party notices normally appear. The contents"
, " of the NOTICE file are for informational purposes only and"
, " do not modify the License. You may add Your own attribution"
, " notices within Derivative Works that You distribute, alongside"
, " or as an addendum to the NOTICE text from the Work, provided"
, " that such additional attribution notices cannot be construed"
, " as modifying the License."
, ""
, " You may add Your own copyright statement to Your modifications and"
, " may provide additional or different license terms and conditions"
, " for use, reproduction, or distribution of Your modifications, or"
, " for any such Derivative Works as a whole, provided Your use,"
, " reproduction, and distribution of the Work otherwise complies with"
, " the conditions stated in this License."
, ""
, " 5. Submission of Contributions. Unless You explicitly state otherwise,"
, " any Contribution intentionally submitted for inclusion in the Work"
, " by You to the Licensor shall be under the terms and conditions of"
, " this License, without any additional terms or conditions."
, " Notwithstanding the above, nothing herein shall supersede or modify"
, " the terms of any separate license agreement you may have executed"
, " with Licensor regarding such Contributions."
, ""
, " 6. Trademarks. This License does not grant permission to use the trade"
, " names, trademarks, service marks, or product names of the Licensor,"
, " except as required for reasonable and customary use in describing the"
, " origin of the Work and reproducing the content of the NOTICE file."
, ""
, " 7. Disclaimer of Warranty. Unless required by applicable law or"
, " agreed to in writing, Licensor provides the Work (and each"
, " Contributor provides its Contributions) on an \"AS IS\" BASIS,"
, " WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or"
, " implied, including, without limitation, any warranties or conditions"
, " of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A"
, " PARTICULAR PURPOSE. You are solely responsible for determining the"
, " appropriateness of using or redistributing the Work and assume any"
, " risks associated with Your exercise of permissions under this License."
, ""
, " 8. Limitation of Liability. In no event and under no legal theory,"
, " whether in tort (including negligence), contract, or otherwise,"
, " unless required by applicable law (such as deliberate and grossly"
, " negligent acts) or agreed to in writing, shall any Contributor be"
, " liable to You for damages, including any direct, indirect, special,"
, " incidental, or consequential damages of any character arising as a"
, " result of this License or out of the use or inability to use the"
, " Work (including but not limited to damages for loss of goodwill,"
, " work stoppage, computer failure or malfunction, or any and all"
, " other commercial damages or losses), even if such Contributor"
, " has been advised of the possibility of such damages."
, ""
, " 9. Accepting Warranty or Additional Liability. While redistributing"
, " the Work or Derivative Works thereof, You may choose to offer,"
, " and charge a fee for, acceptance of support, warranty, indemnity,"
, " or other liability obligations and/or rights consistent with this"
, " License. However, in accepting such obligations, You may act only"
, " on Your own behalf and on Your sole responsibility, not on behalf"
, " of any other Contributor, and only if You agree to indemnify,"
, " defend, and hold each Contributor harmless for any liability"
, " incurred by, or claims asserted against, such Contributor by reason"
, " of your accepting any such warranty or additional liability."
, ""
, " END OF TERMS AND CONDITIONS"
, ""
, " APPENDIX: How to apply the Apache License to your work."
, ""
, " To apply the Apache License to your work, attach the following"
, " boilerplate notice, with the fields enclosed by brackets \"[]\""
, " replaced with your own identifying information. (Don't include"
, " the brackets!) The text should be enclosed in the appropriate"
, " comment syntax for the file format. We also recommend that a"
, " file or class name and description of purpose be included on the"
, " same \"printed page\" as the copyright notice for easier"
, " identification within third-party archives."
, ""
, " Copyright [yyyy] [name of copyright owner]"
, ""
, " Licensed under the Apache License, Version 2.0 (the \"License\");"
, " you may not use this file except in compliance with the License."
, " You may obtain a copy of the License at"
, ""
, " http://www.apache.org/licenses/LICENSE-2.0"
, ""
, " Unless required by applicable law or agreed to in writing, software"
, " distributed under the License is distributed on an \"AS IS\" BASIS,"
, " WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied."
, " See the License for the specific language governing permissions and"
, " limitations under the License."
]
mit :: String -> String -> License
mit authors year = unlines
[ "Copyright (c) " ++ year ++ " " ++ authors
, ""
, "Permission is hereby granted, free of charge, to any person obtaining"
, "a copy of this software and associated documentation files (the"
, "\"Software\"), to deal in the Software without restriction, including"
, "without limitation the rights to use, copy, modify, merge, publish,"
, "distribute, sublicense, and/or sell copies of the Software, and to"
, "permit persons to whom the Software is furnished to do so, subject to"
, "the following conditions:"
, ""
, "The above copyright notice and this permission notice shall be included"
, "in all copies or substantial portions of the Software."
, ""
, "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,"
, "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF"
, "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT."
, "IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY"
, "CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,"
, "TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE"
, "SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."
]
mpl20 :: License
mpl20 = unlines
[ "Mozilla Public License Version 2.0"
, "=================================="
, ""
, "1. Definitions"
, "--------------"
, ""
, "1.1. \"Contributor\""
, " means each individual or legal entity that creates, contributes to"
, " the creation of, or owns Covered Software."
, ""
, "1.2. \"Contributor Version\""
, " means the combination of the Contributions of others (if any) used"
, " by a Contributor and that particular Contributor's Contribution."
, ""
, "1.3. \"Contribution\""
, " means Covered Software of a particular Contributor."
, ""
, "1.4. \"Covered Software\""
, " means Source Code Form to which the initial Contributor has attached"
, " the notice in Exhibit A, the Executable Form of such Source Code"
, " Form, and Modifications of such Source Code Form, in each case"
, " including portions thereof."
, ""
, "1.5. \"Incompatible With Secondary Licenses\""
, " means"
, ""
, " (a) that the initial Contributor has attached the notice described"
, " in Exhibit B to the Covered Software; or"
, ""
, " (b) that the Covered Software was made available under the terms of"
, " version 1.1 or earlier of the License, but not also under the"
, " terms of a Secondary License."
, ""
, "1.6. \"Executable Form\""
, " means any form of the work other than Source Code Form."
, ""
, "1.7. \"Larger Work\""
, " means a work that combines Covered Software with other material, in"
, " a separate file or files, that is not Covered Software."
, ""
, "1.8. \"License\""
, " means this document."
, ""
, "1.9. \"Licensable\""
, " means having the right to grant, to the maximum extent possible,"
, " whether at the time of the initial grant or subsequently, any and"
, " all of the rights conveyed by this License."
, ""
, "1.10. \"Modifications\""
, " means any of the following:"
, ""
, " (a) any file in Source Code Form that results from an addition to,"
, " deletion from, or modification of the contents of Covered"
, " Software; or"
, ""
, " (b) any new file in Source Code Form that contains any Covered"
, " Software."
, ""
, "1.11. \"Patent Claims\" of a Contributor"
, " means any patent claim(s), including without limitation, method,"
, " process, and apparatus claims, in any patent Licensable by such"
, " Contributor that would be infringed, but for the grant of the"
, " License, by the making, using, selling, offering for sale, having"
, " made, import, or transfer of either its Contributions or its"
, " Contributor Version."
, ""
, "1.12. \"Secondary License\""
, " means either the GNU General Public License, Version 2.0, the GNU"
, " Lesser General Public License, Version 2.1, the GNU Affero General"
, " Public License, Version 3.0, or any later versions of those"
, " licenses."
, ""
, "1.13. \"Source Code Form\""
, " means the form of the work preferred for making modifications."
, ""
, "1.14. \"You\" (or \"Your\")"
, " means an individual or a legal entity exercising rights under this"
, " License. For legal entities, \"You\" includes any entity that"
, " controls, is controlled by, or is under common control with You. For"
, " purposes of this definition, \"control\" means (a) the power, direct"
, " or indirect, to cause the direction or management of such entity,"
, " whether by contract or otherwise, or (b) ownership of more than"
, " fifty percent (50%) of the outstanding shares or beneficial"
, " ownership of such entity."
, ""
, "2. License Grants and Conditions"
, "--------------------------------"
, ""
, "2.1. Grants"
, ""
, "Each Contributor hereby grants You a world-wide, royalty-free,"
, "non-exclusive license:"
, ""
, "(a) under intellectual property rights (other than patent or trademark)"
, " Licensable by such Contributor to use, reproduce, make available,"
, " modify, display, perform, distribute, and otherwise exploit its"
, " Contributions, either on an unmodified basis, with Modifications, or"
, " as part of a Larger Work; and"
, ""
, "(b) under Patent Claims of such Contributor to make, use, sell, offer"
, " for sale, have made, import, and otherwise transfer either its"
, " Contributions or its Contributor Version."
, ""
, "2.2. Effective Date"
, ""
, "The licenses granted in Section 2.1 with respect to any Contribution"
, "become effective for each Contribution on the date the Contributor first"
, "distributes such Contribution."
, ""
, "2.3. Limitations on Grant Scope"
, ""
, "The licenses granted in this Section 2 are the only rights granted under"
, "this License. No additional rights or licenses will be implied from the"
, "distribution or licensing of Covered Software under this License."
, "Notwithstanding Section 2.1(b) above, no patent license is granted by a"
, "Contributor:"
, ""
, "(a) for any code that a Contributor has removed from Covered Software;"
, " or"
, ""
, "(b) for infringements caused by: (i) Your and any other third party's"
, " modifications of Covered Software, or (ii) the combination of its"
, " Contributions with other software (except as part of its Contributor"
, " Version); or"
, ""
, "(c) under Patent Claims infringed by Covered Software in the absence of"
, " its Contributions."
, ""
, "This License does not grant any rights in the trademarks, service marks,"
, "or logos of any Contributor (except as may be necessary to comply with"
, "the notice requirements in Section 3.4)."
, ""
, "2.4. Subsequent Licenses"
, ""
, "No Contributor makes additional grants as a result of Your choice to"
, "distribute the Covered Software under a subsequent version of this"
, "License (see Section 10.2) or under the terms of a Secondary License (if"
, "permitted under the terms of Section 3.3)."
, ""
, "2.5. Representation"
, ""
, "Each Contributor represents that the Contributor believes its"
, "Contributions are its original creation(s) or it has sufficient rights"
, "to grant the rights to its Contributions conveyed by this License."
, ""
, "2.6. Fair Use"
, ""
, "This License is not intended to limit any rights You have under"
, "applicable copyright doctrines of fair use, fair dealing, or other"
, "equivalents."
, ""
, "2.7. Conditions"
, ""
, "Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted"
, "in Section 2.1."
, ""
, "3. Responsibilities"
, "-------------------"
, ""
, "3.1. Distribution of Source Form"
, ""
, "All distribution of Covered Software in Source Code Form, including any"
, "Modifications that You create or to which You contribute, must be under"
, "the terms of this License. You must inform recipients that the Source"
, "Code Form of the Covered Software is governed by the terms of this"
, "License, and how they can obtain a copy of this License. You may not"
, "attempt to alter or restrict the recipients' rights in the Source Code"
, "Form."
, ""
, "3.2. Distribution of Executable Form"
, ""
, "If You distribute Covered Software in Executable Form then:"
, ""
, "(a) such Covered Software must also be made available in Source Code"
, " Form, as described in Section 3.1, and You must inform recipients of"
, " the Executable Form how they can obtain a copy of such Source Code"
, " Form by reasonable means in a timely manner, at a charge no more"
, " than the cost of distribution to the recipient; and"
, ""
, "(b) You may distribute such Executable Form under the terms of this"
, " License, or sublicense it under different terms, provided that the"
, " license for the Executable Form does not attempt to limit or alter"
, " the recipients' rights in the Source Code Form under this License."
, ""
, "3.3. Distribution of a Larger Work"
, ""
, "You may create and distribute a Larger Work under terms of Your choice,"
, "provided that You also comply with the requirements of this License for"
, "the Covered Software. If the Larger Work is a combination of Covered"
, "Software with a work governed by one or more Secondary Licenses, and the"
, "Covered Software is not Incompatible With Secondary Licenses, this"
, "License permits You to additionally distribute such Covered Software"
, "under the terms of such Secondary License(s), so that the recipient of"
, "the Larger Work may, at their option, further distribute the Covered"
, "Software under the terms of either this License or such Secondary"
, "License(s)."
, ""
, "3.4. Notices"
, ""
, "You may not remove or alter the substance of any license notices"
, "(including copyright notices, patent notices, disclaimers of warranty,"
, "or limitations of liability) contained within the Source Code Form of"
, "the Covered Software, except that You may alter any license notices to"
, "the extent required to remedy known factual inaccuracies."
, ""
, "3.5. Application of Additional Terms"
, ""
, "You may choose to offer, and to charge a fee for, warranty, support,"
, "indemnity or liability obligations to one or more recipients of Covered"
, "Software. However, You may do so only on Your own behalf, and not on"
, "behalf of any Contributor. You must make it absolutely clear that any"
, "such warranty, support, indemnity, or liability obligation is offered by"
, "You alone, and You hereby agree to indemnify every Contributor for any"
, "liability incurred by such Contributor as a result of warranty, support,"
, "indemnity or liability terms You offer. You may include additional"
, "disclaimers of warranty and limitations of liability specific to any"
, "jurisdiction."
, ""
, "4. Inability to Comply Due to Statute or Regulation"
, "---------------------------------------------------"
, ""
, "If it is impossible for You to comply with any of the terms of this"
, "License with respect to some or all of the Covered Software due to"
, "statute, judicial order, or regulation then You must: (a) comply with"
, "the terms of this License to the maximum extent possible; and (b)"
, "describe the limitations and the code they affect. Such description must"
, "be placed in a text file included with all distributions of the Covered"
, "Software under this License. Except to the extent prohibited by statute"
, "or regulation, such description must be sufficiently detailed for a"
, "recipient of ordinary skill to be able to understand it."
, ""
, "5. Termination"
, "--------------"
, ""
, "5.1. The rights granted under this License will terminate automatically"
, "if You fail to comply with any of its terms. However, if You become"
, "compliant, then the rights granted under this License from a particular"
, "Contributor are reinstated (a) provisionally, unless and until such"
, "Contributor explicitly and finally terminates Your grants, and (b) on an"
, "ongoing basis, if such Contributor fails to notify You of the"
, "non-compliance by some reasonable means prior to 60 days after You have"
, "come back into compliance. Moreover, Your grants from a particular"
, "Contributor are reinstated on an ongoing basis if such Contributor"
, "notifies You of the non-compliance by some reasonable means, this is the"
, "first time You have received notice of non-compliance with this License"
, "from such Contributor, and You become compliant prior to 30 days after"
, "Your receipt of the notice."
, ""
, "5.2. If You initiate litigation against any entity by asserting a patent"
, "infringement claim (excluding declaratory judgment actions,"
, "counter-claims, and cross-claims) alleging that a Contributor Version"
, "directly or indirectly infringes any patent, then the rights granted to"
, "You by any and all Contributors for the Covered Software under Section"
, "2.1 of this License shall terminate."
, ""
, "5.3. In the event of termination under Sections 5.1 or 5.2 above, all"
, "end user license agreements (excluding distributors and resellers) which"
, "have been validly granted by You or Your distributors under this License"
, "prior to termination shall survive termination."
, ""
, "************************************************************************"
, "* *"
, "* 6. Disclaimer of Warranty *"
, "* ------------------------- *"
, "* *"
, "* Covered Software is provided under this License on an \"as is\" *"
, "* basis, without warranty of any kind, either expressed, implied, or *"
, "* statutory, including, without limitation, warranties that the *"
, "* Covered Software is free of defects, merchantable, fit for a *"
, "* particular purpose or non-infringing. The entire risk as to the *"
, "* quality and performance of the Covered Software is with You. *"
, "* Should any Covered Software prove defective in any respect, You *"
, "* (not any Contributor) assume the cost of any necessary servicing, *"
, "* repair, or correction. This disclaimer of warranty constitutes an *"
, "* essential part of this License. No use of any Covered Software is *"
, "* authorized under this License except under this disclaimer. *"
, "* *"
, "************************************************************************"
, ""
, "************************************************************************"
, "* *"
, "* 7. Limitation of Liability *"
, "* -------------------------- *"
, "* *"
, "* Under no circumstances and under no legal theory, whether tort *"
, "* (including negligence), contract, or otherwise, shall any *"
, "* Contributor, or anyone who distributes Covered Software as *"
, "* permitted above, be liable to You for any direct, indirect, *"
, "* special, incidental, or consequential damages of any character *"
, "* including, without limitation, damages for lost profits, loss of *"
, "* goodwill, work stoppage, computer failure or malfunction, or any *"
, "* and all other commercial damages or losses, even if such party *"
, "* shall have been informed of the possibility of such damages. This *"
, "* limitation of liability shall not apply to liability for death or *"
, "* personal injury resulting from such party's negligence to the *"
, "* extent applicable law prohibits such limitation. Some *"
, "* jurisdictions do not allow the exclusion or limitation of *"
, "* incidental or consequential damages, so this exclusion and *"
, "* limitation may not apply to You. *"
, "* *"
, "************************************************************************"
, ""
, "8. Litigation"
, "-------------"
, ""
, "Any litigation relating to this License may be brought only in the"
, "courts of a jurisdiction where the defendant maintains its principal"
, "place of business and such litigation shall be governed by laws of that"
, "jurisdiction, without reference to its conflict-of-law provisions."
, "Nothing in this Section shall prevent a party's ability to bring"
, "cross-claims or counter-claims."
, ""
, "9. Miscellaneous"
, "----------------"
, ""
, "This License represents the complete agreement concerning the subject"
, "matter hereof. If any provision of this License is held to be"
, "unenforceable, such provision shall be reformed only to the extent"
, "necessary to make it enforceable. Any law or regulation which provides"
, "that the language of a contract shall be construed against the drafter"
, "shall not be used to construe this License against a Contributor."
, ""
, "10. Versions of the License"
, "---------------------------"
, ""
, "10.1. New Versions"
, ""
, "Mozilla Foundation is the license steward. Except as provided in Section"
, "10.3, no one other than the license steward has the right to modify or"
, "publish new versions of this License. Each version will be given a"
, "distinguishing version number."
, ""
, "10.2. Effect of New Versions"
, ""
, "You may distribute the Covered Software under the terms of the version"
, "of the License under which You originally received the Covered Software,"
, "or under the terms of any subsequent version published by the license"
, "steward."
, ""
, "10.3. Modified Versions"
, ""
, "If you create software not governed by this License, and you want to"
, "create a new license for such software, you may create and use a"
, "modified version of this License if you rename the license and remove"
, "any references to the name of the license steward (except to note that"
, "such modified license differs from this License)."
, ""
, "10.4. Distributing Source Code Form that is Incompatible With Secondary"
, "Licenses"
, ""
, "If You choose to distribute Source Code Form that is Incompatible With"
, "Secondary Licenses under the terms of this version of the License, the"
, "notice described in Exhibit B of this License must be attached."
, ""
, "Exhibit A - Source Code Form License Notice"
, "-------------------------------------------"
, ""
, " This Source Code Form is subject to the terms of the Mozilla Public"
, " License, v. 2.0. If a copy of the MPL was not distributed with this"
, " file, You can obtain one at http://mozilla.org/MPL/2.0/."
, ""
, "If it is not possible or desirable to put the notice in a particular"
, "file, then You may include the notice in a location (such as a LICENSE"
, "file in a relevant directory) where a recipient would be likely to look"
, "for such a notice."
, ""
, "You may add additional accurate notices of copyright ownership."
, ""
, "Exhibit B - \"Incompatible With Secondary Licenses\" Notice"
, "---------------------------------------------------------"
, ""
, " This Source Code Form is \"Incompatible With Secondary Licenses\", as"
, " defined by the Mozilla Public License, v. 2.0."
]
isc :: String -> String -> License
isc authors year = unlines
[ "Copyright (c) " ++ year ++ " " ++ authors
, ""
, "Permission to use, copy, modify, and/or distribute this software for any purpose"
, "with or without fee is hereby granted, provided that the above copyright notice"
, "and this permission notice appear in all copies."
, ""
, "THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH"
, "REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND"
, "FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,"
, "INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS"
, "OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER"
, "TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF"
, "THIS SOFTWARE."
]
| tolysz/prepare-ghcjs | spec-lts8/cabal/cabal-install/Distribution/Client/Init/Licenses.hs | bsd-3-clause | 179,709 | 0 | 9 | 45,222 | 9,318 | 6,174 | 3,144 | 3,041 | 1 |
import Messente
smsSend = send "api-username" "api-password"
main = do
-- If from is Nothing then messente default 'From' is used
-- (configured from API setup at messente.com)
result <- smsSend Nothing "+00000000000" "my first sms"
putStrLn $ case result of
Right id -> "sms sent, id: " ++ id
Left (errNo, errStr) -> "not sent: " ++ show errNo ++ ", " ++ errStr
-- star http server to get delivery feedback (must configure at messente.com)
-- this function doesn't return (runs forever)
listen 9000 delivery
delivery :: Delivery -> IO ()
delivery del = putStrLn $
case del of
Delivered id -> "delivered " ++ id
DeliveryError id errNo errStr -> "not delivered " ++ id ++ ": " ++ errStr
DeliveryProgress id status -> "progress " ++ id ++ ": " ++ status
| kaiko/messente-haskell | test.hs | mit | 801 | 0 | 14 | 185 | 190 | 93 | 97 | 14 | 3 |
largeNonMersennePrime :: Integer
largeNonMersennePrime = let a = 28433 * 2^7830457 + 1
b = 10000000000
in a `mod` b
-- *Main> largeNonMersennePrime
-- 8739992577
-- (0.08 secs, 5,885,008 bytes)
| samidarko/euler | problem097.hs | mit | 250 | 0 | 11 | 86 | 48 | 27 | 21 | 4 | 1 |
-- | A minimal Haskbot server can be run via:
--
-- > {-# LANGUAGE OverloadedStrings #-}
-- >
-- > import Network.Haskbot
-- > import Network.Haskbot.Config
-- > import Network.Haskbot.Plugin
-- > import qualified Network.Haskbot.Plugin.Help as Help
-- >
-- > main :: IO ()
-- > main = haskbot config registry
-- >
-- > config :: Config
-- > config = Config { listenOn = 3000
-- > , incEndpoint = "https://my-company.slack.com/services/hooks/incoming-webhook"
-- > , incToken = "my-incoming-token"
-- > }
-- >
-- > registry :: [Plugin]
-- > registry = [ Help.register registry "my-slash-token" ]
--
-- This will run Haskbot on port 3000 with the included
-- "Network.Haskbot.Plugin.Help" plugin installed, where @\"my-slash-token\"@
-- is the secret token of a Slack slash command integration corresponding to
-- the @/haskbot@ command and pointing to the Haskbot server.
--
-- Be sure to create a Slack incoming integration (usually named /Haskbot/)
-- and set the 'incEndpoint' and 'incToken' to their corresponding values, so
-- that Slack can receive replies from Haskbot.
module Network.Haskbot
(
-- * Run a Haskbot server
haskbot
) where
import Network.Haskbot.Internal.Server (webServer)
import Network.Haskbot.Config (Config)
import Network.Haskbot.Plugin (Plugin)
-- | Run the listed plugins on a Haskbot server with the given config
haskbot :: Config -- ^ Your custom-created config
-> [Plugin] -- ^ List of all Haskbot plugins to include
-> IO ()
haskbot = webServer
| bendyworks/haskbot-plugins | haskbot-core-0.2/src/Network/Haskbot.hs | mit | 1,568 | 0 | 8 | 324 | 104 | 76 | 28 | 10 | 1 |
{-# Language OverloadedStrings #-}
module Unison.Config where
import qualified Data.Configurator as Config
import Data.Configurator.Types (Config)
import qualified Unison.Util.Logger as L
import System.IO (Handle, stderr, stdout)
-- | Load the config
load :: IO Config
load = Config.load [Config.Required "config", Config.Optional "$(HOME)/.unisonconfig"]
-- | Obtain a Logger decorator that sets the default logging level
logger :: IO (L.Logger -> L.Logger)
logger = do
config <- load
level <- Config.require config "logging"
pure $ L.at level
loggerTo :: Handle -> IO L.Logger
loggerTo h = do
t <- logger
t <$> L.atomic (L.toHandle h)
loggerStandardOut, loggerStandardError :: IO L.Logger
(loggerStandardOut, loggerStandardError) = (loggerTo stdout, loggerTo stderr)
| nightscape/platform | node/src/Unison/Config.hs | mit | 785 | 0 | 11 | 120 | 229 | 124 | 105 | 19 | 1 |
-----------------------------------------------------------------------------
--
-- Module : Graphics.GPipe.PrimitiveStream
-- Copyright : Tobias Bexelius
-- License : MIT
--
-- Maintainer : Tobias Bexelius
-- Stability : Experimental
-- Portability : Portable
--
-- |
-- A 'Graphics.GPipe.PrimitiveArray.PrimitiveArray' can be turned into a 'PrimitiveStream' in a 'Graphics.GPipe.Shader.Shader', in order to operate on the vertices of it and ultimately rasterize it into
-- a 'Graphics.GPipe.FragmentStream.FragmentStream'.
-----------------------------------------------------------------------------
module Graphics.GPipe.PrimitiveStream (
-- * The data type
PrimitiveStream(),
VertexInput(..),
ToVertex(),
-- * Creating PrimitiveStreams
toPrimitiveStream,
-- * Various PrimitiveStream operations
withInputIndices,
InputIndices(..),
withPointSize,
PointSize
)
where
import Graphics.GPipe.Internal.PrimitiveStream | Teaspot-Studio/GPipe-Core | src/Graphics/GPipe/PrimitiveStream.hs | mit | 994 | 0 | 5 | 169 | 71 | 54 | 17 | 14 | 0 |
{-# LANGUAGE DeriveGeneric #-}
module NginxInterface where
import GHC.Generics
import Data.Time.Clock.POSIX
import Data.Aeson
import Data.Maybe
import qualified Data.ByteString.Lazy.Char8 as B
import MonitorCommon
--parser-printer imports
import NginxPrettyPrinter
import NginxSourceCreator
import TreeConfigNginxFiller
----server imports
import TypeFiles.NginxTypes
import NginxDefaultValues
import TypeFiles.Common
----io
import Control.Concurrent
import Data.Time.Clock.POSIX
import Data.Time.Clock
import Data.Time.Format
import System.Process
----misc
import Data.Either
import Debug.Trace
import TransfoNginx
-- Nginix Log Type
-- A JSON format is assumed:
-- LogFormat "{\"responseTime\" : $request_time, \"stamp\" : $msec}" monitorJSON
data NginxLogReq = ApacheLogReq{ responseTime :: Float, stamp :: Float } deriving (Show, Generic)
instance ToJSON NginxLogReq where
toEncoding = genericToEncoding defaultOptions
instance FromJSON NginxLogReq
nginxMonitor :: IO Environment
nginxMonitor = do
log <- readFile "/var/log/nginx/monitor.log"
let requests = catMaybes $ map (decode . B.pack) (lines log) :: [NginxLogReq]
-- F**k Data.Time.Clock
currentTime <- (fmap floor getPOSIXTime :: IO Int)
let reqLastMinute = filter (\req -> (currentTime - round (stamp req)) <= 60) requests
return $ Environment{
requestsLastMinute = length reqLastMinute
, avgResponseTimeLastMinute = round (1000 * 1000 * (sum . map responseTime $ reqLastMinute) / fromIntegral (length reqLastMinute + 1))
}
nginxReader :: String -> IO NginxWebserver
nginxReader filename = do
res <- parseTreeNginx filename
if isLeft res
then fail "Parser failed"
else do
let (Right tree) = res
return (createSourceNginx tree)
nginxWriterReal :: String -> NginxWebserver -> IO ()
nginxWriterReal filename src = do
let text = printNginx src
writeFile filename (show text)
system "sudo nginx -s reload"
return ()
nginxWriter :: String -> NginxWebserver -> IO ()
nginxWriter filename src = do
let text = printNginx src
putStrLn "write configuration:"
print text
writeFile filename (show text)
| prl-tokyo/bigul-configuration-adaptation | Transformations/NginxInterface.hs | mit | 2,199 | 0 | 18 | 411 | 570 | 297 | 273 | 55 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module KirstieHooksArchivePageSpec where
import Test.Hspec
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import System.Directory
import System.FilePath
import System.Posix.Files
import Web.Kirstie.Model
import Web.Kirstie.DB
import Web.Kirstie.Hooks.ArchivePage
import Util
spec :: Spec
spec = do
describe "Web.Kirstie.Hooks.ArchivePage" $ do
it "all values" $ onTestSpace $ \conf pipe path -> do
let template = BL.concat [ "{{config_data.blogUrl}}"
, "{{#articles}}"
, "{{aid}}", "{{title}}"
, "{{pubdate.date}}", "{{pubdate.year}}"
, "{{pubdate.month}}", "{{pubdate.day}}"
, "{{#tags}}"
, "{{tag}}", "{{encoded_tag}}"
, "{{/tags}}"
, "{{/articles}}" ]
articles = [ minimal { articleTitle = "hoge"
, articleTags = ["foo", "bar"] } ]
expect = BS.concat [ "http://www.example.com/"
, "0", "hoge"
, "1858-11-17", "1858", "Nov", "17"
, "foo", "foo", "bar", "bar" ]
tempFile = templateDirectory conf </> "archive-page.html"
htmlFile = htmlDirectory conf </> "archive.html"
saveArticlesToDB conf articles
createDirectories conf
BL.writeFile tempFile template
archivePage conf articles
BS.readFile htmlFile `shouldReturn` expect
it "empty database" $ onTestSpace $ \conf pipe path -> do
let expect = "http://www.example.com/"
template = BL.concat [ "{{config_data.blogUrl}}"
, "{{#articles}}", "foo", "{{/articles}}" ]
tempFile = templateDirectory conf </> "archive-page.html"
htmlFile = htmlDirectory conf </> "archive.html"
createDirectories conf
BL.writeFile tempFile template
archivePage conf []
BS.readFile htmlFile `shouldReturn` expect
it "all articles" $ onTestSpace $ \conf pipe path -> do
let template = BL.concat ["{{#articles}}", "0", "{{/articles}}"]
articles = map (\i -> minimal {articleIdNum = i}) [1..20]
expect = BS.concat $ replicate (length articles) "0"
tempFile = templateDirectory conf </> "archive-page.html"
htmlFile = htmlDirectory conf </> "archive.html"
saveArticlesToDB conf articles
createDirectories conf
BL.writeFile tempFile template
archivePage conf articles
BS.readFile htmlFile `shouldReturn` expect
createDirectories :: Configure -> IO ()
createDirectories conf = do
createDirectoryIfMissing False $ templateDirectory conf
createDirectoryIfMissing False $ htmlDirectory conf
| hekt/blog-system | test/KirstieHooksArchivePageSpec.hs | mit | 2,969 | 0 | 21 | 965 | 637 | 335 | 302 | 63 | 1 |
{-# OPTIONS_GHC -fno-warn-missing-fields #-}
module KNXd.Client.Internal.TH where
import Language.Haskell.TH
import Language.Haskell.TH.Quote
import Data.Char
import Data.List
defineTypes :: QuasiQuoter
defineTypes = QuasiQuoter { quoteDec = parseHeader }
splitOn' :: Eq a => a -> [a] -> [[a]]
splitOn' = go []
where
go res _ [] = reverse res
go res s ls = let (pre, suf) = break (==s) ls
in case suf of
[] -> go (pre:res) s []
[_] -> go ([]:pre:res) s []
-- invariant: x == s
_:xs -> go (pre:res) s xs
parseHeader :: String -> Q [Dec]
parseHeader hdr = return $ [mkToFunSig, mkFromFunSig] ++ map ($ fixedValues) [mkDataDecl, mkToFunDecl, mkFromFunDecl]
where
defines = filter ("#define" `isPrefixOf`) $ lines hdr
values = map (\[_,k,v] -> (k,v)) $ filter (\x -> length x == 3) $ map words defines
camelCase [] = []
camelCase (x:xs) = toUpper x : map toLower xs
fixNames name = concatMap camelCase . tail $ splitOn' '_' name
fixedValues = map (\(k,v) -> (fixNames k, read v :: Integer)) values
dataName = mkName "PacketType"
toName = mkName "toPacketType"
fromName = mkName "fromPacketType"
word16Con = ConT . mkName $ "Word16"
mkDataDecl vals = let cons = map (\(k,_) -> NormalC (mkName k) []) vals
in DataD [] dataName [] cons [mkName "Show", mkName "Eq", mkName "Typeable"]
mkToFunSig = SigD toName $ AppT (AppT ArrowT (ConT dataName)) word16Con
mkFromFunSig = SigD fromName $ AppT (AppT ArrowT word16Con) (ConT dataName)
mkToFunDecl vals = let cl (k,v) = Clause [RecP (mkName k) []] (NormalB . LitE . IntegerL $ v) []
in FunD toName $ map cl vals
mkFromFunDecl vals = let cl (k,v) = Clause [LitP . IntegerL $ v] (NormalB . ConE $ mkName k) []
in FunD fromName $ map cl vals ++ [Clause [WildP] (NormalB $ AppE (VarE $ mkName "error") (LitE $ StringL "unknown packet type")) []]
| KaneTW/knxd-native-client | src-old/GenFromDefine.hs | mit | 2,043 | 0 | 17 | 570 | 861 | 448 | 413 | 36 | 4 |
{-# LANGUAGE OverloadedStrings #-}
module Config where
import Control.Applicative
import Data.Maybe
import System.Directory
import System.FilePath
import qualified Data.Yaml.Config as Yaml
type Config = (String, [String], [String])
load :: FilePath -> IO Config
load path = do
yaml <- Yaml.load path
dir <- listToMaybe . reverse . splitDirectories <$> getCurrentDirectory
let name = fromMaybe "dependencies" $ Yaml.lookup "name" yaml <|> dir
deps sec = fromMaybe [] (Yaml.lookup sec yaml)
mainDeps = deps "main"
testDeps = deps "test"
return (name, mainDeps, testDeps)
| sol/depends | src/Config.hs | mit | 638 | 0 | 13 | 149 | 189 | 101 | 88 | 17 | 1 |
{-|
Module : Data.Dson.Octal
Copyright : (c) Ezequiel Alvarez 2014
License : MIT
Maintainer : [email protected]
Stability : provisional
Portability : portable
Parser for octal numbers.
-}
module Data.Dson.Octal (octal) where
import Data.Dson.Lexer
import Control.Applicative
import Data.Char (digitToInt, isOctDigit)
import Data.Maybe (fromMaybe)
import Text.Parsec (satisfy, char)
import Text.Parsec.String (Parser)
octalToDouble :: (String, Maybe String, Maybe (Double, String)) -> Double
octalToDouble (int, m_dec, m_exp) = (parseOctStrs int dec) * (8 ** (sign * (parseOctStrs exp "")))
where (sign, exp) = fromMaybe (1, "0") m_exp
dec = fromMaybe "" m_dec
-- Conversion according to http://en.wikipedia.org/wiki/Octal#Octal_to_decimal_conversion
-- Decimal part has negative exponent.
parseOctStrs :: String -> String -> Double
parseOctStrs intPart decPart =
snd $ foldl expAndAdd (initlLen, 0) (intPart ++ decPart)
where initlLen = fromIntegral . pred . length $ intPart
expAndAdd (exp, acc) b = (pred exp, acc + (fromIntegral . digitToInt $ b) * (8 ** exp))
factor :: Parser Double
factor = (char '-' *> pure (-1)) <|> (char '+' *> pure 1) <|> pure 1
octalParts :: Parser (String, Maybe String, Maybe (Double, String))
octalParts = (,,) <$> some octDigit <*> optional octalDecimals <*> optional octalExponent
where octDigit = satisfy isOctDigit
octalDecimals = symbol "." *> some octDigit
octalExponent = (,) <$> (veryVERY *> factor) <*> some octDigit
veryVERY = symbol "very" <|> symbol "VERY"
{-|
This parser can read a number in the following formats:
* 5
* -3.14
* 2very-6
* 1VERY4
etc
-}
octal :: Parser Double
octal = (*) <$> factor <*> (octalToDouble <$> octalParts)
| alvare/dson-parsec | Data/Dson/Octal.hs | mit | 1,798 | 0 | 12 | 358 | 517 | 283 | 234 | 26 | 1 |
{-|
A DSL for declaration of result decoders.
-}
module Hasql.Private.Decoders
where
import Hasql.Private.Prelude hiding (maybe, bool)
import qualified Data.Vector as Vector
import qualified PostgreSQL.Binary.Decoding as A
import qualified PostgreSQL.Binary.Data as B
import qualified Hasql.Private.Decoders.Results as Results
import qualified Hasql.Private.Decoders.Result as Result
import qualified Hasql.Private.Decoders.Row as Row
import qualified Hasql.Private.Decoders.Value as Value
import qualified Hasql.Private.Decoders.Array as Array
import qualified Hasql.Private.Decoders.Composite as Composite
import qualified Hasql.Private.Prelude as Prelude
import qualified Data.Vector.Generic as GenericVector
-- * Result
-------------------------
{-|
Decoder of a query result.
-}
newtype Result a = Result (Results.Results a) deriving (Functor)
{-|
Decode no value from the result.
Useful for statements like @INSERT@ or @CREATE@.
-}
{-# INLINABLE noResult #-}
noResult :: Result ()
noResult = Result (Results.single Result.noResult)
{-|
Get the amount of rows affected by such statements as
@UPDATE@ or @DELETE@.
-}
{-# INLINABLE rowsAffected #-}
rowsAffected :: Result Int64
rowsAffected = Result (Results.single Result.rowsAffected)
{-|
Exactly one row.
Will raise the 'Hasql.Errors.UnexpectedAmountOfRows' error if it's any other.
-}
{-# INLINABLE singleRow #-}
singleRow :: Row a -> Result a
singleRow (Row row) = Result (Results.single (Result.single row))
refineResult :: (a -> Either Text b) -> Result a -> Result b
refineResult refiner (Result results) = Result (Results.refine refiner results)
-- ** Multi-row traversers
-------------------------
{-|
Foldl multiple rows.
-}
{-# INLINABLE foldlRows #-}
foldlRows :: (a -> b -> a) -> a -> Row b -> Result a
foldlRows step init (Row row) = Result (Results.single (Result.foldl step init row))
{-|
Foldr multiple rows.
-}
{-# INLINABLE foldrRows #-}
foldrRows :: (b -> a -> a) -> a -> Row b -> Result a
foldrRows step init (Row row) = Result (Results.single (Result.foldr step init row))
-- ** Specialized multi-row results
-------------------------
{-|
Maybe one row or none.
-}
{-# INLINABLE rowMaybe #-}
rowMaybe :: Row a -> Result (Maybe a)
rowMaybe (Row row) = Result (Results.single (Result.maybe row))
{-|
Zero or more rows packed into the vector.
It's recommended to prefer this function to 'rowList',
since it performs notably better.
-}
{-# INLINABLE rowVector #-}
rowVector :: Row a -> Result (Vector a)
rowVector (Row row) = Result (Results.single (Result.vector row))
{-|
Zero or more rows packed into the list.
-}
{-# INLINABLE rowList #-}
rowList :: Row a -> Result [a]
rowList = foldrRows strictCons []
-- * Row
-------------------------
{-|
Decoder of an individual row,
which gets composed of column value decoders.
E.g.:
@
x :: 'Row' (Maybe Int64, Text, TimeOfDay)
x = (,,) '<$>' ('column' . 'nullable') 'int8' '<*>' ('column' . 'nonNullable') 'text' '<*>' ('column' . 'nonNullable') 'time'
@
-}
newtype Row a = Row (Row.Row a)
deriving (Functor, Applicative, Monad, MonadFail)
{-|
Lift an individual value decoder to a composable row decoder.
-}
{-# INLINABLE column #-}
column :: NullableOrNot Value a -> Row a
column = \ case
NonNullable (Value imp) -> Row (Row.nonNullValue imp)
Nullable (Value imp) -> Row (Row.value imp)
-- * Nullability
-------------------------
{-|
Extensional specification of nullability over a generic decoder.
-}
data NullableOrNot decoder a where
NonNullable :: decoder a -> NullableOrNot decoder a
Nullable :: decoder a -> NullableOrNot decoder (Maybe a)
{-|
Specify that a decoder produces a non-nullable value.
-}
nonNullable :: decoder a -> NullableOrNot decoder a
nonNullable = NonNullable
{-|
Specify that a decoder produces a nullable value.
-}
nullable :: decoder a -> NullableOrNot decoder (Maybe a)
nullable = Nullable
-- * Value
-------------------------
{-|
Decoder of a value.
-}
newtype Value a = Value (Value.Value a)
deriving (Functor)
type role Value representational
{-|
Decoder of the @BOOL@ values.
-}
{-# INLINABLE bool #-}
bool :: Value Bool
bool = Value (Value.decoder (const A.bool))
{-|
Decoder of the @INT2@ values.
-}
{-# INLINABLE int2 #-}
int2 :: Value Int16
int2 = Value (Value.decoder (const A.int))
{-|
Decoder of the @INT4@ values.
-}
{-# INLINABLE int4 #-}
int4 :: Value Int32
int4 = Value (Value.decoder (const A.int))
{-|
Decoder of the @INT8@ values.
-}
{-# INLINABLE int8 #-}
int8 :: Value Int64
int8 = {-# SCC "int8" #-}
Value (Value.decoder (const ({-# SCC "int8.int" #-} A.int)))
{-|
Decoder of the @FLOAT4@ values.
-}
{-# INLINABLE float4 #-}
float4 :: Value Float
float4 = Value (Value.decoder (const A.float4))
{-|
Decoder of the @FLOAT8@ values.
-}
{-# INLINABLE float8 #-}
float8 :: Value Double
float8 = Value (Value.decoder (const A.float8))
{-|
Decoder of the @NUMERIC@ values.
-}
{-# INLINABLE numeric #-}
numeric :: Value B.Scientific
numeric = Value (Value.decoder (const A.numeric))
{-|
Decoder of the @CHAR@ values.
Note that it supports Unicode values.
-}
{-# INLINABLE char #-}
char :: Value Char
char = Value (Value.decoder (const A.char))
{-|
Decoder of the @TEXT@ values.
-}
{-# INLINABLE text #-}
text :: Value Text
text = Value (Value.decoder (const A.text_strict))
{-|
Decoder of the @BYTEA@ values.
-}
{-# INLINABLE bytea #-}
bytea :: Value ByteString
bytea = Value (Value.decoder (const A.bytea_strict))
{-|
Decoder of the @DATE@ values.
-}
{-# INLINABLE date #-}
date :: Value B.Day
date = Value (Value.decoder (const A.date))
{-|
Decoder of the @TIMESTAMP@ values.
-}
{-# INLINABLE timestamp #-}
timestamp :: Value B.LocalTime
timestamp = Value (Value.decoder (Prelude.bool A.timestamp_float A.timestamp_int))
{-|
Decoder of the @TIMESTAMPTZ@ values.
/NOTICE/
Postgres does not store the timezone information of @TIMESTAMPTZ@.
Instead it stores a UTC value and performs silent conversions
to the currently set timezone, when dealt with in the text format.
However this library bypasses the silent conversions
and communicates with Postgres using the UTC values directly.
-}
{-# INLINABLE timestamptz #-}
timestamptz :: Value B.UTCTime
timestamptz = Value (Value.decoder (Prelude.bool A.timestamptz_float A.timestamptz_int))
{-|
Decoder of the @TIME@ values.
-}
{-# INLINABLE time #-}
time :: Value B.TimeOfDay
time = Value (Value.decoder (Prelude.bool A.time_float A.time_int))
{-|
Decoder of the @TIMETZ@ values.
Unlike in case of @TIMESTAMPTZ@,
Postgres does store the timezone information for @TIMETZ@.
However the Haskell's \"time\" library does not contain any composite type,
that fits the task, so we use a pair of 'TimeOfDay' and 'TimeZone'
to represent a value on the Haskell's side.
-}
{-# INLINABLE timetz #-}
timetz :: Value (B.TimeOfDay, B.TimeZone)
timetz = Value (Value.decoder (Prelude.bool A.timetz_float A.timetz_int))
{-|
Decoder of the @INTERVAL@ values.
-}
{-# INLINABLE interval #-}
interval :: Value B.DiffTime
interval = Value (Value.decoder (Prelude.bool A.interval_float A.interval_int))
{-|
Decoder of the @UUID@ values.
-}
{-# INLINABLE uuid #-}
uuid :: Value B.UUID
uuid = Value (Value.decoder (const A.uuid))
{-|
Decoder of the @INET@ values.
-}
{-# INLINABLE inet #-}
inet :: Value (B.NetAddr B.IP)
inet = Value (Value.decoder (const A.inet))
{-|
Decoder of the @JSON@ values into a JSON AST.
-}
{-# INLINABLE json #-}
json :: Value B.Value
json = Value (Value.decoder (const A.json_ast))
{-|
Decoder of the @JSON@ values into a raw JSON 'ByteString'.
-}
{-# INLINABLE jsonBytes #-}
jsonBytes :: (ByteString -> Either Text a) -> Value a
jsonBytes fn = Value (Value.decoder (const (A.json_bytes fn)))
{-|
Decoder of the @JSONB@ values into a JSON AST.
-}
{-# INLINABLE jsonb #-}
jsonb :: Value B.Value
jsonb = Value (Value.decoder (const A.jsonb_ast))
{-|
Decoder of the @JSONB@ values into a raw JSON 'ByteString'.
-}
{-# INLINABLE jsonbBytes #-}
jsonbBytes :: (ByteString -> Either Text a) -> Value a
jsonbBytes fn = Value (Value.decoder (const (A.jsonb_bytes fn)))
{-|
Lift a custom value decoder function to a 'Value' decoder.
-}
{-# INLINABLE custom #-}
custom :: (Bool -> ByteString -> Either Text a) -> Value a
custom fn = Value (Value.decoderFn fn)
{-|
Refine a value decoder, lifting the possible error to the session level.
-}
{-# INLINABLE refine #-}
refine :: (a -> Either Text b) -> Value a -> Value b
refine fn (Value v) = Value (Value.Value (\b -> A.refine fn (Value.run v b)))
{-|
A generic decoder of @HSTORE@ values.
Here's how you can use it to construct a specific value:
@
x :: Value [(Text, Maybe Text)]
x = hstore 'replicateM'
@
-}
{-# INLINABLE hstore #-}
hstore :: (forall m. Monad m => Int -> m (Text, Maybe Text) -> m a) -> Value a
hstore replicateM = Value (Value.decoder (const (A.hstore replicateM A.text_strict A.text_strict)))
{-|
Given a partial mapping from text to value,
produces a decoder of that value.
-}
enum :: (Text -> Maybe a) -> Value a
enum mapping = Value (Value.decoder (const (A.enum mapping)))
{-|
Lift an 'Array' decoder to a 'Value' decoder.
-}
{-# INLINABLE array #-}
array :: Array a -> Value a
array (Array imp) = Value (Value.decoder (Array.run imp))
{-|
Lift a value decoder of element into a unidimensional array decoder producing a list.
This function is merely a shortcut to the following expression:
@
('array' . 'dimension' Control.Monad.'replicateM' . 'element')
@
Please notice that in case of multidimensional arrays nesting 'listArray' decoder
won't work. You have to explicitly construct the array decoder using 'array'.
-}
{-# INLINE listArray #-}
listArray :: NullableOrNot Value element -> Value [element]
listArray = array . dimension replicateM . element
{-|
Lift a value decoder of element into a unidimensional array decoder producing a generic vector.
This function is merely a shortcut to the following expression:
@
('array' . 'dimension' Data.Vector.Generic.'GenericVector.replicateM' . 'element')
@
Please notice that in case of multidimensional arrays nesting 'vectorArray' decoder
won't work. You have to explicitly construct the array decoder using 'array'.
-}
{-# INLINE vectorArray #-}
vectorArray :: GenericVector.Vector vector element => NullableOrNot Value element -> Value (vector element)
vectorArray = array . dimension GenericVector.replicateM . element
{-|
Lift a 'Composite' decoder to a 'Value' decoder.
-}
{-# INLINABLE composite #-}
composite :: Composite a -> Value a
composite (Composite imp) = Value (Value.decoder (Composite.run imp))
-- * Array decoders
-------------------------
{-|
A generic array decoder.
Here's how you can use it to produce a specific array value decoder:
@
x :: 'Value' [[Text]]
x = 'array' ('dimension' 'replicateM' ('dimension' 'replicateM' ('element' ('nonNullable' 'text'))))
@
-}
newtype Array a = Array (Array.Array a)
deriving (Functor)
{-|
A function for parsing a dimension of an array.
Provides support for multi-dimensional arrays.
Accepts:
* An implementation of the @replicateM@ function
(@Control.Monad.'Control.Monad.replicateM'@, @Data.Vector.'Data.Vector.replicateM'@),
which determines the output value.
* A decoder of its components, which can be either another 'dimension' or 'element'.
-}
{-# INLINABLE dimension #-}
dimension :: (forall m. Monad m => Int -> m a -> m b) -> Array a -> Array b
dimension replicateM (Array imp) = Array (Array.dimension replicateM imp)
{-|
Lift a 'Value' decoder into an 'Array' decoder for parsing of leaf values.
-}
{-# INLINABLE element #-}
element :: NullableOrNot Value a -> Array a
element = \ case
NonNullable (Value imp) -> Array (Array.nonNullValue (Value.run imp))
Nullable (Value imp) -> Array (Array.value (Value.run imp))
-- * Composite decoders
-------------------------
{-|
Composable decoder of composite values (rows, records).
-}
newtype Composite a = Composite (Composite.Composite a)
deriving (Functor, Applicative, Monad, MonadFail)
{-|
Lift a 'Value' decoder into a 'Composite' decoder for parsing of component values.
-}
field :: NullableOrNot Value a -> Composite a
field = \ case
NonNullable (Value imp) -> Composite (Composite.nonNullValue (Value.run imp))
Nullable (Value imp) -> Composite (Composite.value (Value.run imp))
| nikita-volkov/hasql | library/Hasql/Private/Decoders.hs | mit | 12,244 | 0 | 13 | 1,943 | 2,553 | 1,360 | 1,193 | -1 | -1 |
{-# LANGUAGE TypeFamilies #-}
module Hadrian.Oracles.ArgsHash (
TrackArgument, trackAllArguments, trackArgsHash, argsHashOracle
) where
import Control.Monad
import Development.Shake
import Development.Shake.Classes
import Hadrian.Expression hiding (inputs, outputs)
import Hadrian.Target
import Hadrian.Utilities
-- | 'TrackArgument' is used to specify the arguments that should be tracked by
-- the @ArgsHash@ oracle. The safest option is to track all arguments, but some
-- arguments, such as @-jN@, do not change the build results, hence there is no
-- need to initiate unnecessary rebuild if they are added to or removed from a
-- command line. If all arguments should be tracked, use 'trackAllArguments'.
type TrackArgument c b = Target c b -> String -> Bool
-- | Returns 'True' for all targets and arguments, hence can be used a safe
-- default for 'argsHashOracle'.
trackAllArguments :: TrackArgument c b
trackAllArguments _ _ = True
-- | Given a 'Target' this 'Action' determines the corresponding argument list
-- and computes its hash. The resulting value is tracked in a Shake oracle,
-- hence initiating rebuilds when the hash changes (a hash change indicates
-- changes in the build command for the given target).
-- Note: for efficiency we replace the list of input files with its hash to
-- avoid storing long lists of source files passed to some builders (e.g. ar)
-- in the Shake database. This optimisation is normally harmless, because
-- argument list constructors are assumed not to examine target sources, but
-- only append them to argument lists where appropriate.
trackArgsHash :: (ShakeValue c, ShakeValue b) => Target c b -> Action ()
trackArgsHash t = do
let hashedInputs = [ show $ hash (inputs t) ]
hashedTarget = target (context t) (builder t) hashedInputs (outputs t)
void (askOracle $ ArgsHash hashedTarget :: Action Int)
newtype ArgsHash c b = ArgsHash (Target c b)
deriving (Binary, Eq, Hashable, NFData, Show, Typeable)
type instance RuleResult (ArgsHash c b) = Int
-- | This oracle stores per-target argument list hashes in the Shake database,
-- allowing the user to track them between builds using 'trackArgsHash' queries.
argsHashOracle :: (ShakeValue c, ShakeValue b) => TrackArgument c b -> Args c b -> Rules ()
argsHashOracle trackArgument args = void $
addOracle $ \(ArgsHash target) -> do
argList <- interpret target args
let trackedArgList = filter (trackArgument target) argList
return $ hash trackedArgList
| izgzhen/hadrian | src/Hadrian/Oracles/ArgsHash.hs | mit | 2,519 | 0 | 14 | 450 | 419 | 228 | 191 | 26 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DuplicateRecordFields #-}
module Language.LSP.Types.ServerCapabilities where
import Data.Aeson
import Data.Aeson.TH
import Data.Text (Text)
import Language.LSP.Types.CodeAction
import Language.LSP.Types.CodeLens
import Language.LSP.Types.Command
import Language.LSP.Types.Common
import Language.LSP.Types.Completion
import Language.LSP.Types.Declaration
import Language.LSP.Types.Definition
import Language.LSP.Types.DocumentColor
import Language.LSP.Types.DocumentHighlight
import Language.LSP.Types.DocumentLink
import Language.LSP.Types.DocumentSymbol
import Language.LSP.Types.FoldingRange
import Language.LSP.Types.Formatting
import Language.LSP.Types.Hover
import Language.LSP.Types.Implementation
import Language.LSP.Types.References
import Language.LSP.Types.Rename
import Language.LSP.Types.SelectionRange
import Language.LSP.Types.SignatureHelp
import Language.LSP.Types.TextDocument
import Language.LSP.Types.TypeDefinition
import Language.LSP.Types.Utils
-- ---------------------------------------------------------------------
data WorkspaceFoldersServerCapabilities =
WorkspaceFoldersServerCapabilities
{ -- | The server has support for workspace folders
_supported :: Maybe Bool
-- | Whether the server wants to receive workspace folder
-- change notifications.
-- If a strings is provided the string is treated as a ID
-- under which the notification is registered on the client
-- side. The ID can be used to unregister for these events
-- using the `client/unregisterCapability` request.
, _changeNotifications :: Maybe (Text |? Bool)
}
deriving (Show, Read, Eq)
deriveJSON lspOptions ''WorkspaceFoldersServerCapabilities
data WorkspaceServerCapabilities =
WorkspaceServerCapabilities
{ -- | The server supports workspace folder. Since LSP 3.6
--
-- @since 0.7.0.0
_workspaceFolders :: Maybe WorkspaceFoldersServerCapabilities
}
deriving (Show, Read, Eq)
deriveJSON lspOptions ''WorkspaceServerCapabilities
data ServerCapabilities =
ServerCapabilities
{ -- | Defines how text documents are synced. Is either a detailed structure
-- defining each notification or for backwards compatibility the
-- 'TextDocumentSyncKind' number.
-- If omitted it defaults to 'TdSyncNone'.
_textDocumentSync :: Maybe (TextDocumentSyncOptions |? TextDocumentSyncKind)
-- | The server provides hover support.
, _hoverProvider :: Maybe (Bool |? HoverOptions)
-- | The server provides completion support.
, _completionProvider :: Maybe CompletionOptions
-- | The server provides signature help support.
, _signatureHelpProvider :: Maybe SignatureHelpOptions
-- | The server provides go to declaration support.
--
-- Since LSP 3.14.0
, _declarationProvider :: Maybe (Bool |? DeclarationOptions |? DeclarationRegistrationOptions)
-- | The server provides goto definition support.
, _definitionProvider :: Maybe (Bool |? DefinitionOptions)
-- | The server provides Goto Type Definition support. Since LSP 3.6
--
-- @since 0.7.0.0
, _typeDefinitionProvider :: Maybe (Bool |? TypeDefinitionOptions |? TypeDefinitionRegistrationOptions)
-- | The server provides Goto Implementation support. Since LSP 3.6
--
-- @since 0.7.0.0
, _implementationProvider :: Maybe (Bool |? ImplementationOptions |? ImplementationRegistrationOptions)
-- | The server provides find references support.
, _referencesProvider :: Maybe (Bool |? ReferenceOptions)
-- | The server provides document highlight support.
, _documentHighlightProvider :: Maybe (Bool |? DocumentHighlightOptions)
-- | The server provides document symbol support.
, _documentSymbolProvider :: Maybe (Bool |? DocumentSymbolOptions)
-- | The server provides code actions.
, _codeActionProvider :: Maybe (Bool |? CodeActionOptions)
-- | The server provides code lens.
, _codeLensProvider :: Maybe CodeLensOptions
-- | The server provides document link support.
, _documentLinkProvider :: Maybe DocumentLinkOptions
-- | The server provides color provider support. Since LSP 3.6
--
-- @since 0.7.0.0
, _colorProvider :: Maybe (Bool |? DocumentColorOptions |? DocumentColorRegistrationOptions)
-- | The server provides document formatting.
, _documentFormattingProvider :: Maybe (Bool |? DocumentFormattingOptions)
-- | The server provides document range formatting.
, _documentRangeFormattingProvider :: Maybe (Bool |? DocumentRangeFormattingOptions)
-- | The server provides document formatting on typing.
, _documentOnTypeFormattingProvider :: Maybe DocumentOnTypeFormattingOptions
-- | The server provides rename support.
, _renameProvider :: Maybe (Bool |? RenameOptions)
-- | The server provides folding provider support. Since LSP 3.10
--
-- @since 0.7.0.0
, _foldingRangeProvider :: Maybe (Bool |? FoldingRangeOptions |? FoldingRangeRegistrationOptions)
-- | The server provides execute command support.
, _executeCommandProvider :: Maybe ExecuteCommandOptions
-- | The server provides selection range support. Since LSP 3.15
, _selectionRangeProvider :: Maybe (Bool |? SelectionRangeOptions |? SelectionRangeRegistrationOptions)
-- | The server provides workspace symbol support.
, _workspaceSymbolProvider :: Maybe Bool
-- | Workspace specific server capabilities
, _workspace :: Maybe WorkspaceServerCapabilities
-- | Experimental server capabilities.
, _experimental :: Maybe Value
} deriving (Show, Read, Eq)
deriveJSON lspOptions ''ServerCapabilities
| alanz/haskell-lsp | lsp-types/src/Language/LSP/Types/ServerCapabilities.hs | mit | 6,128 | 0 | 12 | 1,371 | 732 | 452 | 280 | 69 | 0 |
module Y2017.M04.D07.Solution where
-- below module available via 1HaskellADay git repository
import Control.Logic.Frege ((<<-))
{--
From the Mensa Genius Quiz-a-Day Book by Dr. Abbie F. Salny
Problem for April 7th:
"You are decorating for Spring," the problem begins, and I'm like: I am?
Dr. Salny responds: "CHUT UP, FOO'! AND READ THE PROBLEM!"
Okay, then!
You are decorating for Spring, and you've found a bargain: a huge box of
beautiful decorated tiles, ...
... [see what she did with that? 'decorating for Spring' and 'decorated tiles'?]
... enough to provide a border in two rooms. You really can't figure out how to
arrange them, however. If you set a border of two tiles all around, there's one
left over; if you set three tiles all around, or four, or five, or six, there's
still one tile left over.* Finally, you try a block of seven tiles for each
corner, and you come out even.
What is the smallest number of tiles you could have to get this result?
* OCD much? Is it me, or would I just throw away the one extra tile, seeing that
I had bought it at a bargain, anyway, and what's one tile between friends,
seeing that I have a huge box of them, anyway?**
** two 'seeing's and two 'anyway's. OCD much, geophf?
Why, yes. Why do you ask?
ANYWAY!
MODULAR FORMS! Did you know that education in basic mathematics in Japan besides
addition, subtraction, multiplication and division includes the modulus as a
basic operator? So this problem should be a breeze for our Japanese Haskellers.
So, solve this problem.
First we need to know what the equations are.
--}
twoTiles, threeTiles, fourTiles, fiveTiles, sixTiles, sevenTiles :: Int -> Int
twoTiles = ntiles 2
threeTiles = ntiles 3
fourTiles = ntiles 4
fiveTiles = ntiles 5
sixTiles = ntiles 6
sevenTiles = ntiles 7
-- where twoTiles, etc, give the total number of tiles used if each corner has
-- a block of tiles two, or three, or ... tiles deep.
-- You ... COULD generalize the above equations if you want...
ntiles :: Int -> Int -> Int
ntiles = (8 *) <<- (*) -- there are 4 corners in each of the two rooms.
-- I mean, I am assuming that there are, but that
-- makes every possible solution even, even the seven
-- tiles per corner solution, so this could get ugly!
-- Now we need the guards, or test functions
oneTileRemainingFor, comesOutEvenFor :: Int -> Int -> Bool
oneTileRemainingFor = moduloIs 1
comesOutEvenFor = moduloIs 0
-- Of course, we want to test that it comes out even for a depth of seven,
-- but GENERALIZATION IS GOOD! Just in case you need a comesOutEvenFor function
-- for your everyday Haskelling tasks.
-- You're welcome.
-- You ... COULD even generalize those 'generalized' guards, but I didn't want
-- to get carried away by generality. By the Admiralty, sure, but not by
-- generality.
-- You'll get that driving home today, I'm sure.
-- and, yes, I do want to generalize the guards:
moduloIs :: Int -> Int -> Int -> Bool
moduloIs m = (== m) <<- mod
-- Now we need to tie these functions together.
-- What is the total number of tiles, t, that equals twoTiles n2, threeTiles n3,
-- ... etc all of which are modulo 1 to their respective widths n2, n3, etc,
-- and are modulo 0 to depth of seven, n7?
{--
But let's think about this problem for a second!
1. we need modulo7 == 0 in all cases
2. we have 8 corners??? really???
Eh, let's just say we're decorating n corners, instead with 2,3,...7 tiles
and go from there.
That means we have 7,14,21, etc tiles.
Let's do this. Let's work from a total number of tiles and work backwards.
.. Also we know even numbers are out (mod 2 == 0) so we can just skip those:
--}
totalTiles :: [Int]
totalTiles = filter mod1ForEverything (map (*7) [1,3 ..])
mod1ForEverything :: Int -> Bool
mod1ForEverything n = and (map ((== 1) . mod n) [3..6])
-- not a 'fast-fail' function, but I can live with it.
-- totalTiles gives us the total number of tiles that satisfies the above
-- constraints. So you've just written a constraint solver to help you decorate
-- your house for Spring. lolneat.
{--
>>> head totalTiles
301
--}
| geophf/1HaskellADay | exercises/HAD/Y2017/M04/D07/Solution.hs | mit | 4,190 | 0 | 10 | 884 | 293 | 182 | 111 | 20 | 1 |
#!/usr/bin/env runhaskell
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE UnicodeSyntax #-}
import Control.Applicative ((<$>))
import Data.Maybe (catMaybes)
import Data.Monoid ((<>))
import Control.Lens
import qualified Data.Aeson.Lens as L
import Network.StackExchange
main ∷ IO ()
main = reputation <$> askSE req >>= mapM_ (print . truncate) . catMaybes
where
req = usersByIds [972985] <> site "stackoverflow" <> key "Lhg6xe5d5BvNK*C0S8jijA(("
reputation xs = xs ^.. traverse . from se . L.key "reputation" . L.asDouble
| supki/libstackexchange | examples/rep-watcher.hs | mit | 599 | 7 | 9 | 98 | 167 | 89 | 78 | -1 | -1 |
module Helpers where
import qualified Data.Vector as V
import Data.Geometry.Geos.Geometry
makePoint (c1, c2) = point $ coordinate2 c1 c2
makePointGeo c = PointGeometry (makePoint c) Nothing
makeLinearRing :: [(Double, Double)] -> Either GeometryConstructionError LinearRing
makeLinearRing = linearRing . V.map (uncurry coordinate2) . V.fromList
makeLinearRingGeo = fmap (\lr -> LinearRingGeometry lr Nothing) . makeLinearRing
makeLineString :: [(Double, Double)] -> Either GeometryConstructionError LineString
makeLineString = lineString . V.map (uncurry coordinate2) . V.fromList
makeLineStringGeo cs = fmap (\ls -> LineStringGeometry ls Nothing) $ makeLineString cs
makePolygon :: [[(Double, Double)]] -> Either GeometryConstructionError Polygon
makePolygon ls = do
lRings <- traverse makeLinearRing ls
polygon $ V.fromList lRings
makePolygonGeo cs = fmap (\pg -> PolygonGeometry pg Nothing) $ (makePolygon cs)
makeMultiLineString :: [[(Double, Double)]] -> Either GeometryConstructionError MultiLineString
makeMultiLineString ls = fmap (multiLineString . V.fromList) (traverse makeLineString ls)
makeMultiLineStringGeo lss = fmap (\ls -> MultiLineStringGeometry ls Nothing) $ makeMultiLineString lss
fromRight :: Either a b -> b
fromRight (Right v) = v
fromRight _ = error "Shouldn't happen."
| ewestern/geos | tests/Helpers.hs | mit | 1,326 | 0 | 9 | 193 | 433 | 225 | 208 | 22 | 1 |
module Language.Jass.Parser.AST.FunctionDecl(
FunctionDecl(..),
getFuncDeclName,
getFuncDeclParameters,
getFuncDeclReturnType
) where
import Language.Jass.Parser.SourcePos
import Language.Jass.ShowIndent
import Language.Jass.JassType
import Language.Jass.Parser.AST.Parameter
type Name = String
data FunctionDecl = FunctionDecl SrcPos Name [Parameter] (Maybe JassType)
instance Show FunctionDecl where
show = showIndent 0
instance ShowIndent FunctionDecl where
showIndent i (FunctionDecl _ name pars rtype) = makeIndent i ++ name ++ " takes " ++ params ++ " returns " ++ maybe "nothing" show rtype
where params = if null pars then "nothing" else commaSep (map show pars)
instance Eq FunctionDecl where
(FunctionDecl _ name1 pars1 ret1) == (FunctionDecl _ name2 pars2 ret2) =
name1 == name2 && pars1 == pars2 && ret1 == ret2
-- | Returns function declaration name, helper
getFuncDeclName :: FunctionDecl -> String
getFuncDeclName (FunctionDecl _ name _ _) = name
-- | Returns parameters of function declaration
getFuncDeclParameters :: FunctionDecl -> [Parameter]
getFuncDeclParameters (FunctionDecl _ _ pars _) = pars
-- | Return function declaration return type
getFuncDeclReturnType :: FunctionDecl -> Maybe JassType
getFuncDeclReturnType (FunctionDecl _ _ _ retType) = retType | NCrashed/hjass | src/library/Language/Jass/Parser/AST/FunctionDecl.hs | mit | 1,323 | 0 | 11 | 212 | 348 | 189 | 159 | 25 | 1 |
module WallFollower where
import Frob
import RobotSim
--import MyRobotModel
emptyWorld = maybeReadWorldFromPath "as31"
maybeReadWorldFromPath p = do
w <- readWorldFromPath p
case w of
Right w' -> return w'
Left s -> return []
wheelSpeedsT :: WheelControl o => Behavior i Speed -> Behavior i Speed -> RobotTask s i o e
wheelSpeedsT vl vr = liftT $ setWheelSpeeds (pairZ vl vr)
{-
vAndTurningAccT :: (RobotProperties i, WheelControl o) =>
Behavior i Speed -> Behavior i AngSpeed -> RobotTask s i o e
vAndTurningAccT v acc = liftT $
setWheelSpeeds (pairZ (v-dv) (v+dv)) where
omega = integralB acc
dv = omega * robotDiameter / 2
-}
vAndTurningRateT :: (RobotProperties i, WheelControl o) =>
Behavior i Speed -> Behavior i AngSpeed -> RobotTask s i o e
vAndTurningRateT v omega = liftT $
setWheelSpeeds (pairZ (v-dv) (v+dv)) where
dv = robotDiameter * omega / 2
turnToT :: (Odometry i, WheelControl o) =>
Angle -> RobotTask s i o ()
turnToT ang =
wheelSpeedsT (-vDiff) vDiff `tillT_`
isTrueE (abs (lift1 normalizeHeading diffHeading) <=* 0.1)
where diffHeading = lift0 ang - heading
vDiff = 0.1
turnRelT :: (Odometry i, WheelControl o) =>
Angle -> RobotTask s i o ()
turnRelT relativeAng =
do initHeading <- snapshotNowT heading
turnToT (initHeading + relativeAng)
-- keep on going to the specified point
gotoPointT :: (RobotProperties i, Odometry i, WheelControl o) =>
Behavior i Point2 -> RobotTask s i o e
gotoPointT goal =
vAndTurningRateT 0.3 (lift1 normalizeHeading $ goalDir - heading) where
goalDir = (sndZ . vector2PolarCoords) $ normalize (goal .-. position)
-- go to the specified point and stop
gotoPointAndStopT :: (RobotProperties i, Odometry i, WheelControl o) =>
Behavior i Point2 -> RobotTask s i o ()
gotoPointAndStopT goal =
gotoPointT goal `tillT_`
(isTrueE $ magnitude (goal .-. position) <* 0.2)
followWallT :: (RobotProperties i, RangeDetection i, WheelControl o) =>
Length -> RobotTask s i o e
followWallT d = vAndTurningRateT v (0.1 * (signum diffD))
where
v = 0.30
leftD = lift1 (!! 1) rangeReadings
diffD = (leftD - lift0 d)
main = do w <- emptyWorld
runSimRunT w () $ do turnToT(pi/2)
followWallT 1
| jatinshah/autonomous_systems | as3/first.hs | mit | 2,299 | 19 | 11 | 527 | 749 | 377 | 372 | 47 | 2 |
-- | Data.Graph is sorely lacking in several ways, This just tries to fill in
-- some holes and provide a more convinient interface
{-# LANGUAGE RecursiveDo #-}
module Util.Graph(
Graph(),
fromGraph,
newGraph,
newGraph',
newGraphReachable,
reachableFrom,
Util.Graph.reachable,
fromScc,
findLoopBreakers,
sccGroups,
Util.Graph.scc,
sccForest,
Util.Graph.dff,
Util.Graph.components,
Util.Graph.topSort,
cyclicNodes,
toDag,
restitchGraph,
mapGraph,
transitiveClosure,
transitiveReduction
) where
import Control.Monad
import Control.Monad.ST
import Data.Array.IArray
import Data.Array.ST
import Data.Graph hiding(Graph)
import Data.Maybe
import GenUtil
import List(sort,sortBy,group,delete)
import qualified Data.Graph as G
import qualified Data.Map as Map
data Graph n = Graph G.Graph (Table n)
instance Show n => Show (Graph n) where
showsPrec n g = showsPrec n (Util.Graph.scc g)
fromGraph :: Graph n -> [(n,[n])]
fromGraph (Graph g lv) = [ (lv!v,map (lv!) vs) | (v,vs) <- assocs g ]
newGraph :: Ord k => [n] -> (n -> k) -> (n -> [k]) -> (Graph n)
newGraph ns a b = snd $ newGraph' ns a b
newGraphReachable :: Ord k => [n] -> (n -> k) -> (n -> [k]) -> ([k] -> [n],Graph n)
newGraphReachable ns fn fd = (rable,ng) where
(vmap,ng) = newGraph' ns fn fd
rable ks = Util.Graph.reachable ng [ v | Just v <- map (flip Map.lookup vmap) ks ]
reachableFrom :: Ord k => (n -> k) -> (n -> [k]) -> [n] -> [k] -> [n]
reachableFrom fn fd ns = fst $ newGraphReachable ns fn fd
-- | Build a graph from a list of nodes uniquely identified by keys,
-- with a list of keys of nodes this node should have edges to.
-- The out-list may contain keys that don't correspond to
-- nodes of the graph; they are ignored.
newGraph' :: Ord k => [n] -> (n -> k) -> (n -> [k]) -> (Map.Map k Vertex,Graph n)
newGraph' ns fn fd = (kmap,Graph graph nr) where
nr = listArray bounds0 ns
max_v = length ns - 1
bounds0 = (0,max_v) :: (Vertex, Vertex)
kmap = Map.fromList [ (fn n,i) | (i,n) <- zip [0 ..] ns ]
graph = listArray bounds0 [mapMaybe (flip Map.lookup kmap) (snub $ fd n) | n <- ns]
fromScc (Left n) = [n]
fromScc (Right n) = n
-- | determine a set of loopbreakers subject to a fitness function
-- loopbreakers have a minimum of their incoming edges ignored.
findLoopBreakers
:: (n -> Int) -- ^ fitness function, greater numbers mean more likely to be a loopbreaker
-> (n -> Bool) -- ^ whether a node is suitable at all for a choice as loopbreaker
-> Graph n -- ^ the graph
-> ([n],[n]) -- ^ (loop breakers,dependency ordered nodes after loopbreaking)
findLoopBreakers func ex (Graph g ln) = ans where
scc = G.scc g
ans = f g scc [] [] where
f g (Node v []:sccs) fs lb
| v `elem` g ! v = let ng = (fmap (List.delete v) g) in f ng (G.scc ng) [] (v:lb)
| otherwise = f g sccs (v:fs) lb
f g (n:_) fs lb = f ng (G.scc ng) [] (mv:lb) where
mv = case sortBy (\ a b -> compare (snd b) (snd a)) [ (v,func (ln!v)) | v <- ns, ex (ln!v) ] of
((mv,_):_) -> mv
[] -> error "findLoopBreakers: no valid loopbreakers"
ns = dec n []
ng = fmap (List.delete mv) g
f _ [] xs lb = (map ((ln!) . head) (group $ sort lb),reverse $ map (ln!) xs)
dec (Node v ts) vs = v:foldr dec vs ts
reachable :: Graph n -> [Vertex] -> [n]
reachable (Graph g ln) vs = map (ln!) $ snub $ concatMap (G.reachable g) vs
sccGroups :: Graph n -> [[n]]
sccGroups g = map fromScc (Util.Graph.scc g)
scc :: Graph n -> [Either n [n]]
scc (Graph g ln) = map decode forest where
forest = G.scc g
decode (Node v [])
| v `elem` g ! v = Right [ln!v]
| otherwise = Left (ln!v)
decode other = Right (dec other [])
dec (Node v ts) vs = ln!v:foldr dec vs ts
sccForest :: Graph n -> Forest n
sccForest (Graph g ln) = map (fmap (ln!)) forest where
forest = G.scc g
dff :: Graph n -> Forest n
dff (Graph g ln) = map (fmap (ln!)) forest where
forest = G.dff g
components :: Graph n -> [[n]]
components (Graph g ln) = map decode forest where
forest = G.components g
decode n = dec n []
dec (Node v ts) vs = ln!v:foldr dec vs ts
topSort :: Graph n -> [n]
topSort (Graph g ln) = map (ln!) $ G.topSort g
cyclicNodes :: Graph n -> [n]
cyclicNodes g = concat [ xs | Right xs <- Util.Graph.scc g]
toDag :: Graph n -> Graph [n]
toDag (Graph g lv) = Graph g' ns' where
ns' = listArray (0,max_v) [ map (lv!) ns | ns <- nss ]
g' = listArray (0,max_v) [ snub [ v | n <- ns, v <- g!n ] | ns <- nss ]
max_v = length nss - 1
nss = map (flip f []) (G.scc g) where
f (Node v ts) rs = v:foldr f rs ts
type AdjacencyMatrix s = STArray s (Vertex,Vertex) Bool
type IAdjacencyMatrix = Array (Vertex,Vertex) Bool
transitiveClosureAM :: AdjacencyMatrix s -> ST s ()
transitiveClosureAM arr = do
bnds@(_,(max_v,_)) <- getBounds arr
forM_ [0 .. max_v] $ \k -> do
forM_ (range bnds) $ \ (i,j) -> do
dij <- readArray arr (i,j)
dik <- readArray arr (i,k)
dkj <- readArray arr (k,j)
writeArray arr (i,j) (dij || (dik && dkj))
transitiveReductionAM :: AdjacencyMatrix s -> ST s ()
transitiveReductionAM arr = do
bnds@(_,(max_v,_)) <- getBounds arr
transitiveClosureAM arr
(farr :: IAdjacencyMatrix) <- freeze arr
forM_ [0 .. max_v] $ \k -> do
forM_ (range bnds) $ \ (i,j) -> do
if farr!(k,i) && farr!(i,j) then
writeArray arr (k,j) False
else return ()
toAdjacencyMatrix :: G.Graph -> ST s (AdjacencyMatrix s)
toAdjacencyMatrix g = do
let (0,max_v) = bounds g
arr <- newArray ((0,0),(max_v,max_v)) False :: ST s (STArray s (Vertex,Vertex) Bool)
sequence_ [ writeArray arr (v,u) True | (v,vs) <- assocs g, u <- vs ]
return arr
fromAdjacencyMatrix :: AdjacencyMatrix s -> ST s G.Graph
fromAdjacencyMatrix arr = do
bnds@(_,(max_v,_)) <- getBounds arr
rs <- getAssocs arr
let rs' = [ x | (x,True) <- rs ]
return (listArray (0,max_v) [ [ v | (n',v) <- rs', n == n' ] | n <- [ 0 .. max_v] ])
transitiveClosure :: Graph n -> Graph n
transitiveClosure (Graph g ns) = let g' = runST (tc g) in (Graph g' ns) where
tc g = do
a <- toAdjacencyMatrix g
transitiveClosureAM a
fromAdjacencyMatrix a
transitiveReduction :: Graph n -> Graph n
transitiveReduction (Graph g ns) = let g' = runST (tc g) in (Graph g' ns) where
tc g = do
a <- toAdjacencyMatrix g
transitiveReductionAM a
fromAdjacencyMatrix a
instance Functor Graph where
fmap f (Graph g n) = Graph g (fmap f n)
--mapT :: (Vertex -> a -> b) -> Table a -> Table b
--mapT f t = listArray (bounds t) [ (f v (t!v)) | v <- indices t ]
restitchGraph :: Ord k => (n -> k) -> (n -> [k]) -> Graph n -> Graph n
restitchGraph fn fd (Graph g nr) = Graph g' nr where
kmap = Map.fromList [ (fn n,i) | (i,n) <- assocs nr ]
g' = listArray (bounds g) [mapMaybe (flip Map.lookup kmap) (snub $ fd n) | n <- elems nr]
mapGraph :: forall a b . (a -> [b] -> b) -> Graph a -> Graph b
mapGraph f (Graph gr nr) = runST $ do
mnr <- thaw nr :: ST s (STArray s Vertex a)
mnr <- mapArray Left mnr
let g i = readArray mnr i >>= \v -> case v of
Right m -> return m
Left l -> mdo
writeArray mnr i (Right r)
rs <- mapM g (gr!i)
let r = f l rs
return r
mapM_ g (range $ bounds nr)
mnr <- mapArray fromRight mnr
mnr <- unsafeFreeze mnr
return (Graph gr mnr)
| dec9ue/jhc_copygc | src/Util/Graph.hs | gpl-2.0 | 7,728 | 6 | 21 | 2,137 | 3,519 | 1,823 | 1,696 | -1 | -1 |
module TestLexer where
import Test.HUnit
import Test.Framework.Providers.HUnit
import Definitions
import Lexer
commentTest :: Assertion
commentTest = assertEqual "Comments should not become tokens" expected actual
where actual = lexer "; a comment\nmov rax, 60; another\n; one more"
expected = [Line {sourceCode = "; a comment",
lineNumber = 1,
tokens = []},
Line {sourceCode = "mov rax, 60; another",
lineNumber = 2,
tokens = [TCommand MOV,
TRegister RAX,
TSymbol Comma,
TNumber 60]},
Line {sourceCode = "; one more",
lineNumber = 3,
tokens = []}]
quoteTest :: Assertion
quoteTest = assertEqual "Quotes should handle escaping" expected $ lexer source
where source = "msg: db \"a \\\"quote\"\" here\\\"\"\"\", 10"
expected = [Line {sourceCode = source,
lineNumber = 1,
tokens = [TLabel "msg",
TCommand DB,
TQuote "a \"quote\" here\"\"",
TSymbol Comma,
TNumber 10]}]
directiveTest :: Assertion
directiveTest = assertEqual "Parse directives" expected $ lexer source
where source = "global _start\n" ++
"global somefunc:function\n" ++
"extern printf"
expected = [Line {sourceCode = "global _start",
lineNumber = 1,
tokens = [TWord "global",
TWord "_start"]},
Line {sourceCode = "global somefunc:function",
lineNumber = 2,
tokens = [TWord "global",
TLabel "somefunc",
TWord "function"]},
Line {sourceCode = "extern printf",
lineNumber = 3,
tokens = [TWord "extern",
TWord "printf"]}]
tests = [
testCase "comment" commentTest,
testCase "quote" quoteTest,
testCase "directive" directiveTest
]
| briansteffens/basm | testsuite/TestLexer.hs | gpl-2.0 | 2,590 | 0 | 11 | 1,313 | 420 | 242 | 178 | 52 | 1 |
{-# LANGUAGE FlexibleContexts #-}
module Exp.Roll where
-- $Id$
import Autolib.Exp
import Autolib.NFA
import Autolib.Exp.Some
import Exp.Property
roll :: NFAC c Int
=> [ Property c ]
-> IO ( RX c, NFA c Int )
roll props = do
let [ alpha ] = do Alphabet alpha <- props ; return alpha
let [ s ] = do Max_Size s <- props ; return s
nontrivial alpha ( s `div` 2 )
| Erdwolf/autotool-bonn | src/Exp/Roll.hs | gpl-2.0 | 399 | 0 | 13 | 112 | 155 | 78 | 77 | 13 | 1 |
{-# language DeriveDataTypeable #-}
{-# language TemplateHaskell #-}
module NFA.Epsilon.Data where
import Autolib.NFA ( NFAC )
import qualified Autolib.Relation
import Autolib.Set
import Autolib.FiniteMap
import Autolib.ToDoc
import Autolib.Reader
import Data.Typeable
data NFAC c s => ENFA c s =
ENFA { nfa_info :: Doc
, alphabet :: Set c
, states :: Set s
, starts :: Set s
, finals :: Set s
, trans :: FiniteMap (s, c) (Set s)
, epsilon_trans :: Autolib.Relation.Type s s
}
deriving Typeable
$(derives [makeToDoc, makeReader] [''ENFA])
| marcellussiegburg/autotool | collection/src/NFA/Epsilon/Data.hs | gpl-2.0 | 624 | 0 | 11 | 169 | 175 | 102 | 73 | 20 | 0 |
{-# OPTIONS -O2 -Wall #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Data.Store.Rev.View
(View, curVersion, branch, setBranch, move, new, store)
where
import Control.Monad (liftM, (<=<))
import Data.Store.Rev.Branch (Branch)
import Data.Store.Rev.Change(Change(..))
import Data.Store.Rev.Version (Version)
import Data.Store.Rev.ViewBranchInternal (ViewData(..), View(..), Branch(..), moveView, makeViewKey, applyChangesToView, brViews, vdBranch, atViewData, atBrViews)
import Data.Store.Transaction (Transaction, Store(..))
import Prelude hiding (lookup)
import qualified Data.List as List
import qualified Data.Store.Property as Property
import qualified Data.Store.Rev.Branch as Branch
import qualified Data.Store.Rev.Change as Change
import qualified Data.Store.Rev.Version as Version
import qualified Data.Store.Transaction as Transaction
-- | A Version Map is a large mapping of ObjectKeys to their
-- | "current-version" values. This serves as a "cache" which is
-- | redundant to the lists of changes stored in the version graph.
lookupBS :: Monad m => View -> Change.Key -> Transaction t m (Maybe Change.Value)
lookupBS view = Transaction.lookupBS . makeViewKey view
setBranch :: Monad m => View -> Branch -> Transaction t m ()
setBranch view@(View viewDataIRef) newBranch@(Branch newBranchDataIRef) = do
let
branchRef =
Property.composeLabel vdBranch atViewData $
Transaction.fromIRef viewDataIRef
oldBranch@(Branch oldBranchDataIRef) <- Property.get branchRef
oldVersion <- Branch.curVersion oldBranch
newVersion <- Branch.curVersion newBranch
moveView view oldVersion newVersion
Property.set branchRef newBranch
Property.pureModify (Property.composeLabel brViews atBrViews $ Transaction.fromIRef oldBranchDataIRef) (List.delete view)
Property.pureModify (Property.composeLabel brViews atBrViews $ Transaction.fromIRef newBranchDataIRef) (view:)
new :: Monad m => Branch -> Transaction t m View
new br@(Branch branchDataIRef) = do
view <- View `liftM` Transaction.newIRef (ViewData br)
version <- Branch.curVersion br
applyHistory view =<< Version.versionData version
Property.pureModify (Property.composeLabel brViews atBrViews $ Transaction.fromIRef branchDataIRef) (view:)
return view
where
applyHistory view versionData = do
maybe (return ()) (applyHistory view <=< Version.versionData) . Version.parent $ versionData
applyChangesToView view Change.newValue $ Version.changes versionData
curVersion :: Monad m => View -> Transaction t m Version
curVersion = Branch.curVersion <=< branch
move :: Monad m => View -> Version -> Transaction t m ()
move view version = (`Branch.move` version) =<< branch view
branch :: Monad m => View -> Transaction t m Branch
branch (View iref) = liftM vdBranch . Transaction.readIRef $ iref
transaction :: Monad m => View -> [(Change.Key, Maybe Change.Value)] -> Transaction t m ()
transaction _ [] = return ()
transaction view changes = do
b <- branch view
Branch.newVersion b =<< mapM makeChange changes
where
makeChange (key, value) =
flip (Change key) value `liftM` lookupBS view key
-- You get a store tagged however you like...
store :: Monad m => View -> Store t' (Transaction t m)
store view = Store {
storeNewKey = Transaction.newKey,
storeLookup = lookupBS view,
storeAtomicWrite = transaction view
}
| alonho/bottle | src/Data/Store/Rev/View.hs | gpl-3.0 | 3,365 | 0 | 14 | 517 | 1,036 | 551 | 485 | 60 | 1 |
{-
Copyright (C) 2015 Michael Dunsmuir
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 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
{-# LANGUAGE TemplateHaskell #-}
module RoutequeryService.GTFSRealtime.TH where
import Control.Monad
import Language.Haskell.TH
import Data.Aeson.TH
import Data.SafeCopy
typeNames = map mkName $ [
"Alert", "Cause", "Effect",
"EntitySelector",
"FeedEntity",
"FeedHeader",
"Incrementality",
"FeedMessage",
"Position",
"TimeRange",
"TranslatedString", "Translation",
"TripDescriptor", "TDSR.ScheduleRelationship",
"TripUpdate", "StopTimeEvent", "StopTimeUpdate", "STUSR.ScheduleRelationship",
"VehicleDescriptor",
"VehiclePosition", "CongestionLevel", "OccupancyStatus", "VehicleStopStatus"]
multiDec :: (Name -> Q [Dec]) -> Q [Dec]
multiDec = liftM concat . forM typeNames
aesonDec = multiDec $ deriveToJSON defaultOptions
safeCopyDec = multiDec $ deriveSafeCopy 0 'base
| mdunsmuir/routequery-service | src/RoutequeryService/GTFSRealtime/TH.hs | gpl-3.0 | 1,503 | 0 | 9 | 263 | 182 | 109 | 73 | 24 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module System.DevUtils.Base.Cloud.Amazon.EC2.Reserved (
EC2Root (..),
EC2Config (..),
EC2Region (..),
EC2InstanceType (..),
EC2Size (..),
EC2ValueColumns (..)
) where
import System.DevUtils.Base.Cloud.Amazon.Misc
import System.DevUtils.Base.Currency
import Data.Aeson
import Control.Applicative
import Control.Monad
data EC2Root = EC2Root {
vers :: Version,
config :: EC2Config
} deriving (Show, Read, Eq)
instance FromJSON EC2Root where
parseJSON (Object v) = EC2Root <$>
v .: "vers" <*>
v .: "config"
parseJSON _ = mzero
data EC2Config = EC2Config {
regions :: [EC2Region]
} deriving (Show, Read, Eq)
instance FromJSON EC2Config where
parseJSON (Object v) = EC2Config <$>
v .: "regions"
parseJSON _ = mzero
data EC2Region = EC2Region {
region :: String,
instanceType :: [EC2InstanceType]
} deriving (Show, Read, Eq)
instance FromJSON EC2Region where
parseJSON (Object v) = EC2Region <$>
v .: "region" <*>
v .: "instanceTypes"
parseJSON _ = mzero
data EC2InstanceType = EC2InstanceType {
sizes :: [EC2Size]
} deriving (Show, Read, Eq)
instance FromJSON EC2InstanceType where
parseJSON (Object v) = EC2InstanceType <$>
v .: "sizes"
parseJSON _ = mzero
data EC2Size = EC2Size {
size :: String,
valueColumns :: [EC2ValueColumns]
} deriving (Show, Read, Eq)
instance FromJSON EC2Size where
parseJSON (Object v) = EC2Size <$>
v .: "size" <*>
v .: "valueColumns"
parseJSON _ = mzero
data EC2ValueColumns = EC2ValueColumns {
name :: String,
rate :: Maybe String,
prices :: CurrencyObject
} deriving (Show, Read, Eq)
instance FromJSON EC2ValueColumns where
parseJSON (Object v) = EC2ValueColumns <$>
v .: "name" <*>
v .:? "rate" <*>
v .: "prices"
parseJSON _ = mzero
| adarqui/DevUtils-Base | src/System/DevUtils/Base/Cloud/Amazon/EC2/Reserved.hs | gpl-3.0 | 1,765 | 0 | 11 | 317 | 580 | 327 | 253 | 65 | 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.Calendar.ACL.Insert
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates an access control rule.
--
-- /See:/ <https://developers.google.com/google-apps/calendar/firstapp Calendar API Reference> for @calendar.acl.insert@.
module Network.Google.Resource.Calendar.ACL.Insert
(
-- * REST Resource
ACLInsertResource
-- * Creating a Request
, aclInsert
, ACLInsert
-- * Request Lenses
, aiCalendarId
, aiPayload
) where
import Network.Google.AppsCalendar.Types
import Network.Google.Prelude
-- | A resource alias for @calendar.acl.insert@ method which the
-- 'ACLInsert' request conforms to.
type ACLInsertResource =
"calendar" :>
"v3" :>
"calendars" :>
Capture "calendarId" Text :>
"acl" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] ACLRule :> Post '[JSON] ACLRule
-- | Creates an access control rule.
--
-- /See:/ 'aclInsert' smart constructor.
data ACLInsert = ACLInsert'
{ _aiCalendarId :: !Text
, _aiPayload :: !ACLRule
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ACLInsert' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aiCalendarId'
--
-- * 'aiPayload'
aclInsert
:: Text -- ^ 'aiCalendarId'
-> ACLRule -- ^ 'aiPayload'
-> ACLInsert
aclInsert pAiCalendarId_ pAiPayload_ =
ACLInsert'
{ _aiCalendarId = pAiCalendarId_
, _aiPayload = pAiPayload_
}
-- | Calendar identifier. To retrieve calendar IDs call the calendarList.list
-- method. If you want to access the primary calendar of the currently
-- logged in user, use the \"primary\" keyword.
aiCalendarId :: Lens' ACLInsert Text
aiCalendarId
= lens _aiCalendarId (\ s a -> s{_aiCalendarId = a})
-- | Multipart request metadata.
aiPayload :: Lens' ACLInsert ACLRule
aiPayload
= lens _aiPayload (\ s a -> s{_aiPayload = a})
instance GoogleRequest ACLInsert where
type Rs ACLInsert = ACLRule
type Scopes ACLInsert =
'["https://www.googleapis.com/auth/calendar"]
requestClient ACLInsert'{..}
= go _aiCalendarId (Just AltJSON) _aiPayload
appsCalendarService
where go
= buildClient (Proxy :: Proxy ACLInsertResource)
mempty
| rueshyna/gogol | gogol-apps-calendar/gen/Network/Google/Resource/Calendar/ACL/Insert.hs | mpl-2.0 | 3,092 | 0 | 14 | 728 | 388 | 234 | 154 | 61 | 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.Healthcare.Projects.Locations.DataSets.DicomStores.Create
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates a new DICOM store within the parent dataset.
--
-- /See:/ <https://cloud.google.com/healthcare Cloud Healthcare API Reference> for @healthcare.projects.locations.datasets.dicomStores.create@.
module Network.Google.Resource.Healthcare.Projects.Locations.DataSets.DicomStores.Create
(
-- * REST Resource
ProjectsLocationsDataSetsDicomStoresCreateResource
-- * Creating a Request
, projectsLocationsDataSetsDicomStoresCreate
, ProjectsLocationsDataSetsDicomStoresCreate
-- * Request Lenses
, pldsdscParent
, pldsdscXgafv
, pldsdscUploadProtocol
, pldsdscAccessToken
, pldsdscUploadType
, pldsdscPayload
, pldsdscDicomStoreId
, pldsdscCallback
) where
import Network.Google.Healthcare.Types
import Network.Google.Prelude
-- | A resource alias for @healthcare.projects.locations.datasets.dicomStores.create@ method which the
-- 'ProjectsLocationsDataSetsDicomStoresCreate' request conforms to.
type ProjectsLocationsDataSetsDicomStoresCreateResource
=
"v1" :>
Capture "parent" Text :>
"dicomStores" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "dicomStoreId" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] DicomStore :> Post '[JSON] DicomStore
-- | Creates a new DICOM store within the parent dataset.
--
-- /See:/ 'projectsLocationsDataSetsDicomStoresCreate' smart constructor.
data ProjectsLocationsDataSetsDicomStoresCreate =
ProjectsLocationsDataSetsDicomStoresCreate'
{ _pldsdscParent :: !Text
, _pldsdscXgafv :: !(Maybe Xgafv)
, _pldsdscUploadProtocol :: !(Maybe Text)
, _pldsdscAccessToken :: !(Maybe Text)
, _pldsdscUploadType :: !(Maybe Text)
, _pldsdscPayload :: !DicomStore
, _pldsdscDicomStoreId :: !(Maybe Text)
, _pldsdscCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsDataSetsDicomStoresCreate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pldsdscParent'
--
-- * 'pldsdscXgafv'
--
-- * 'pldsdscUploadProtocol'
--
-- * 'pldsdscAccessToken'
--
-- * 'pldsdscUploadType'
--
-- * 'pldsdscPayload'
--
-- * 'pldsdscDicomStoreId'
--
-- * 'pldsdscCallback'
projectsLocationsDataSetsDicomStoresCreate
:: Text -- ^ 'pldsdscParent'
-> DicomStore -- ^ 'pldsdscPayload'
-> ProjectsLocationsDataSetsDicomStoresCreate
projectsLocationsDataSetsDicomStoresCreate pPldsdscParent_ pPldsdscPayload_ =
ProjectsLocationsDataSetsDicomStoresCreate'
{ _pldsdscParent = pPldsdscParent_
, _pldsdscXgafv = Nothing
, _pldsdscUploadProtocol = Nothing
, _pldsdscAccessToken = Nothing
, _pldsdscUploadType = Nothing
, _pldsdscPayload = pPldsdscPayload_
, _pldsdscDicomStoreId = Nothing
, _pldsdscCallback = Nothing
}
-- | The name of the dataset this DICOM store belongs to.
pldsdscParent :: Lens' ProjectsLocationsDataSetsDicomStoresCreate Text
pldsdscParent
= lens _pldsdscParent
(\ s a -> s{_pldsdscParent = a})
-- | V1 error format.
pldsdscXgafv :: Lens' ProjectsLocationsDataSetsDicomStoresCreate (Maybe Xgafv)
pldsdscXgafv
= lens _pldsdscXgafv (\ s a -> s{_pldsdscXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pldsdscUploadProtocol :: Lens' ProjectsLocationsDataSetsDicomStoresCreate (Maybe Text)
pldsdscUploadProtocol
= lens _pldsdscUploadProtocol
(\ s a -> s{_pldsdscUploadProtocol = a})
-- | OAuth access token.
pldsdscAccessToken :: Lens' ProjectsLocationsDataSetsDicomStoresCreate (Maybe Text)
pldsdscAccessToken
= lens _pldsdscAccessToken
(\ s a -> s{_pldsdscAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pldsdscUploadType :: Lens' ProjectsLocationsDataSetsDicomStoresCreate (Maybe Text)
pldsdscUploadType
= lens _pldsdscUploadType
(\ s a -> s{_pldsdscUploadType = a})
-- | Multipart request metadata.
pldsdscPayload :: Lens' ProjectsLocationsDataSetsDicomStoresCreate DicomStore
pldsdscPayload
= lens _pldsdscPayload
(\ s a -> s{_pldsdscPayload = a})
-- | The ID of the DICOM store that is being created. Any string value up to
-- 256 characters in length.
pldsdscDicomStoreId :: Lens' ProjectsLocationsDataSetsDicomStoresCreate (Maybe Text)
pldsdscDicomStoreId
= lens _pldsdscDicomStoreId
(\ s a -> s{_pldsdscDicomStoreId = a})
-- | JSONP
pldsdscCallback :: Lens' ProjectsLocationsDataSetsDicomStoresCreate (Maybe Text)
pldsdscCallback
= lens _pldsdscCallback
(\ s a -> s{_pldsdscCallback = a})
instance GoogleRequest
ProjectsLocationsDataSetsDicomStoresCreate
where
type Rs ProjectsLocationsDataSetsDicomStoresCreate =
DicomStore
type Scopes
ProjectsLocationsDataSetsDicomStoresCreate
= '["https://www.googleapis.com/auth/cloud-platform"]
requestClient
ProjectsLocationsDataSetsDicomStoresCreate'{..}
= go _pldsdscParent _pldsdscXgafv
_pldsdscUploadProtocol
_pldsdscAccessToken
_pldsdscUploadType
_pldsdscDicomStoreId
_pldsdscCallback
(Just AltJSON)
_pldsdscPayload
healthcareService
where go
= buildClient
(Proxy ::
Proxy
ProjectsLocationsDataSetsDicomStoresCreateResource)
mempty
| brendanhay/gogol | gogol-healthcare/gen/Network/Google/Resource/Healthcare/Projects/Locations/DataSets/DicomStores/Create.hs | mpl-2.0 | 6,594 | 0 | 18 | 1,429 | 862 | 502 | 360 | 135 | 1 |
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.StorageGateway
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- AWS Storage Gateway Service
--
-- AWS Storage Gateway is the service that connects an on-premises software
-- appliance with cloud-based storage to provide seamless and secure
-- integration between an organization\'s on-premises IT environment and
-- AWS\'s storage infrastructure. The service enables you to securely
-- upload data to the AWS cloud for cost effective backup and rapid
-- disaster recovery.
--
-- Use the following links to get started using the /AWS Storage Gateway
-- Service API Reference/:
--
-- - <http://docs.aws.amazon.com/storagegateway/latest/userguide/AWSStorageGatewayHTTPRequestsHeaders.html AWS Storage Gateway Required Request Headers>:
-- Describes the required headers that you must send with every POST
-- request to AWS Storage Gateway.
-- - <http://docs.aws.amazon.com/storagegateway/latest/userguide/AWSStorageGatewaySigningRequests.html Signing Requests>:
-- AWS Storage Gateway requires that you authenticate every request you
-- send; this topic describes how sign such a request.
-- - <http://docs.aws.amazon.com/storagegateway/latest/userguide/APIErrorResponses.html Error Responses>:
-- Provides reference information about AWS Storage Gateway errors.
-- - <http://docs.aws.amazon.com/storagegateway/latest/userguide/AWSStorageGatewayAPIOperations.html Operations in AWS Storage Gateway>:
-- Contains detailed descriptions of all AWS Storage Gateway
-- operations, their request parameters, response elements, possible
-- errors, and examples of requests and responses.
-- - <http://docs.aws.amazon.com/general/latest/gr/index.html?rande.html AWS Storage Gateway Regions and Endpoints>:
-- Provides a list of each of the regions and endpoints available for
-- use with AWS Storage Gateway.
--
-- /See:/ <http://docs.aws.amazon.com/storagegateway/latest/APIReference/Welcome.html AWS API Reference>
module Network.AWS.StorageGateway
(
-- * Service Configuration
storageGateway
-- * Errors
-- $errors
-- ** InvalidGatewayRequestException
, _InvalidGatewayRequestException
-- ** InternalServerError
, _InternalServerError
-- * Waiters
-- $waiters
-- * Operations
-- $operations
-- ** CancelArchival
, module Network.AWS.StorageGateway.CancelArchival
-- ** CreateStorediSCSIVolume
, module Network.AWS.StorageGateway.CreateStorediSCSIVolume
-- ** DescribeChapCredentials
, module Network.AWS.StorageGateway.DescribeChapCredentials
-- ** CreateTapes
, module Network.AWS.StorageGateway.CreateTapes
-- ** UpdateVTLDeviceType
, module Network.AWS.StorageGateway.UpdateVTLDeviceType
-- ** CreateCachediSCSIVolume
, module Network.AWS.StorageGateway.CreateCachediSCSIVolume
-- ** ListVolumeInitiators
, module Network.AWS.StorageGateway.ListVolumeInitiators
-- ** AddUploadBuffer
, module Network.AWS.StorageGateway.AddUploadBuffer
-- ** UpdateGatewayInformation
, module Network.AWS.StorageGateway.UpdateGatewayInformation
-- ** DescribeMaintenanceStartTime
, module Network.AWS.StorageGateway.DescribeMaintenanceStartTime
-- ** DescribeWorkingStorage
, module Network.AWS.StorageGateway.DescribeWorkingStorage
-- ** DescribeCachediSCSIVolumes
, module Network.AWS.StorageGateway.DescribeCachediSCSIVolumes
-- ** AddCache
, module Network.AWS.StorageGateway.AddCache
-- ** StartGateway
, module Network.AWS.StorageGateway.StartGateway
-- ** ShutdownGateway
, module Network.AWS.StorageGateway.ShutdownGateway
-- ** UpdateGatewaySoftwareNow
, module Network.AWS.StorageGateway.UpdateGatewaySoftwareNow
-- ** DeleteChapCredentials
, module Network.AWS.StorageGateway.DeleteChapCredentials
-- ** UpdateChapCredentials
, module Network.AWS.StorageGateway.UpdateChapCredentials
-- ** DescribeUploadBuffer
, module Network.AWS.StorageGateway.DescribeUploadBuffer
-- ** DescribeTapes (Paginated)
, module Network.AWS.StorageGateway.DescribeTapes
-- ** DescribeStorediSCSIVolumes
, module Network.AWS.StorageGateway.DescribeStorediSCSIVolumes
-- ** CreateSnapshotFromVolumeRecoveryPoint
, module Network.AWS.StorageGateway.CreateSnapshotFromVolumeRecoveryPoint
-- ** RetrieveTapeRecoveryPoint
, module Network.AWS.StorageGateway.RetrieveTapeRecoveryPoint
-- ** DeleteGateway
, module Network.AWS.StorageGateway.DeleteGateway
-- ** UpdateMaintenanceStartTime
, module Network.AWS.StorageGateway.UpdateMaintenanceStartTime
-- ** DescribeGatewayInformation
, module Network.AWS.StorageGateway.DescribeGatewayInformation
-- ** RetrieveTapeArchive
, module Network.AWS.StorageGateway.RetrieveTapeArchive
-- ** DescribeTapeArchives (Paginated)
, module Network.AWS.StorageGateway.DescribeTapeArchives
-- ** DisableGateway
, module Network.AWS.StorageGateway.DisableGateway
-- ** DescribeSnapshotSchedule
, module Network.AWS.StorageGateway.DescribeSnapshotSchedule
-- ** DescribeBandwidthRateLimit
, module Network.AWS.StorageGateway.DescribeBandwidthRateLimit
-- ** DeleteSnapshotSchedule
, module Network.AWS.StorageGateway.DeleteSnapshotSchedule
-- ** UpdateSnapshotSchedule
, module Network.AWS.StorageGateway.UpdateSnapshotSchedule
-- ** CreateSnapshot
, module Network.AWS.StorageGateway.CreateSnapshot
-- ** CancelRetrieval
, module Network.AWS.StorageGateway.CancelRetrieval
-- ** DescribeVTLDevices (Paginated)
, module Network.AWS.StorageGateway.DescribeVTLDevices
-- ** DeleteTapeArchive
, module Network.AWS.StorageGateway.DeleteTapeArchive
-- ** ListVolumeRecoveryPoints
, module Network.AWS.StorageGateway.ListVolumeRecoveryPoints
-- ** ResetCache
, module Network.AWS.StorageGateway.ResetCache
-- ** ListGateways (Paginated)
, module Network.AWS.StorageGateway.ListGateways
-- ** DeleteTape
, module Network.AWS.StorageGateway.DeleteTape
-- ** ListLocalDisks
, module Network.AWS.StorageGateway.ListLocalDisks
-- ** ListVolumes (Paginated)
, module Network.AWS.StorageGateway.ListVolumes
-- ** UpdateBandwidthRateLimit
, module Network.AWS.StorageGateway.UpdateBandwidthRateLimit
-- ** AddWorkingStorage
, module Network.AWS.StorageGateway.AddWorkingStorage
-- ** DescribeTapeRecoveryPoints (Paginated)
, module Network.AWS.StorageGateway.DescribeTapeRecoveryPoints
-- ** DeleteBandwidthRateLimit
, module Network.AWS.StorageGateway.DeleteBandwidthRateLimit
-- ** ActivateGateway
, module Network.AWS.StorageGateway.ActivateGateway
-- ** DescribeCache
, module Network.AWS.StorageGateway.DescribeCache
-- ** DeleteVolume
, module Network.AWS.StorageGateway.DeleteVolume
-- * Types
-- ** CachediSCSIVolume
, CachediSCSIVolume
, cachediSCSIVolume
, cscsivVolumeiSCSIAttributes
, cscsivVolumeStatus
, cscsivSourceSnapshotId
, cscsivVolumeARN
, cscsivVolumeProgress
, cscsivVolumeSizeInBytes
, cscsivVolumeId
, cscsivVolumeType
-- ** ChapInfo
, ChapInfo
, chapInfo
, ciTargetARN
, ciSecretToAuthenticateInitiator
, ciInitiatorName
, ciSecretToAuthenticateTarget
-- ** DeviceiSCSIAttributes
, DeviceiSCSIAttributes
, deviceiSCSIAttributes
, dscsiaTargetARN
, dscsiaChapEnabled
, dscsiaNetworkInterfaceId
, dscsiaNetworkInterfacePort
-- ** Disk
, Disk
, disk
, dDiskAllocationResource
, dDiskAllocationType
, dDiskNode
, dDiskPath
, dDiskSizeInBytes
, dDiskStatus
, dDiskId
-- ** GatewayInfo
, GatewayInfo
, gatewayInfo
, giGatewayARN
, giGatewayOperationalState
, giGatewayType
-- ** NetworkInterface
, NetworkInterface
, networkInterface
, niIPv6Address
, niMACAddress
, niIPv4Address
-- ** StorediSCSIVolume
, StorediSCSIVolume
, storediSCSIVolume
, sscsivVolumeiSCSIAttributes
, sscsivVolumeStatus
, sscsivSourceSnapshotId
, sscsivPreservedExistingData
, sscsivVolumeARN
, sscsivVolumeProgress
, sscsivVolumeSizeInBytes
, sscsivVolumeId
, sscsivVolumeDiskId
, sscsivVolumeType
-- ** Tape
, Tape
, tape
, tTapeBarcode
, tTapeStatus
, tTapeARN
, tProgress
, tTapeSizeInBytes
, tVTLDevice
-- ** TapeArchive
, TapeArchive
, tapeArchive
, taTapeBarcode
, taTapeStatus
, taTapeARN
, taTapeSizeInBytes
, taCompletionTime
, taRetrievedTo
-- ** TapeRecoveryPointInfo
, TapeRecoveryPointInfo
, tapeRecoveryPointInfo
, trpiTapeStatus
, trpiTapeRecoveryPointTime
, trpiTapeARN
, trpiTapeSizeInBytes
-- ** VTLDevice
, VTLDevice
, vTLDevice
, vtldDeviceiSCSIAttributes
, vtldVTLDeviceVendor
, vtldVTLDeviceARN
, vtldVTLDeviceType
, vtldVTLDeviceProductIdentifier
-- ** VolumeInfo
, VolumeInfo
, volumeInfo
, viVolumeARN
, viVolumeType
-- ** VolumeRecoveryPointInfo
, VolumeRecoveryPointInfo
, volumeRecoveryPointInfo
, vrpiVolumeRecoveryPointTime
, vrpiVolumeARN
, vrpiVolumeSizeInBytes
, vrpiVolumeUsageInBytes
-- ** VolumeiSCSIAttributes
, VolumeiSCSIAttributes
, volumeiSCSIAttributes
, vscsiaLunNumber
, vscsiaTargetARN
, vscsiaChapEnabled
, vscsiaNetworkInterfaceId
, vscsiaNetworkInterfacePort
) where
import Network.AWS.StorageGateway.ActivateGateway
import Network.AWS.StorageGateway.AddCache
import Network.AWS.StorageGateway.AddUploadBuffer
import Network.AWS.StorageGateway.AddWorkingStorage
import Network.AWS.StorageGateway.CancelArchival
import Network.AWS.StorageGateway.CancelRetrieval
import Network.AWS.StorageGateway.CreateCachediSCSIVolume
import Network.AWS.StorageGateway.CreateSnapshot
import Network.AWS.StorageGateway.CreateSnapshotFromVolumeRecoveryPoint
import Network.AWS.StorageGateway.CreateStorediSCSIVolume
import Network.AWS.StorageGateway.CreateTapes
import Network.AWS.StorageGateway.DeleteBandwidthRateLimit
import Network.AWS.StorageGateway.DeleteChapCredentials
import Network.AWS.StorageGateway.DeleteGateway
import Network.AWS.StorageGateway.DeleteSnapshotSchedule
import Network.AWS.StorageGateway.DeleteTape
import Network.AWS.StorageGateway.DeleteTapeArchive
import Network.AWS.StorageGateway.DeleteVolume
import Network.AWS.StorageGateway.DescribeBandwidthRateLimit
import Network.AWS.StorageGateway.DescribeCache
import Network.AWS.StorageGateway.DescribeCachediSCSIVolumes
import Network.AWS.StorageGateway.DescribeChapCredentials
import Network.AWS.StorageGateway.DescribeGatewayInformation
import Network.AWS.StorageGateway.DescribeMaintenanceStartTime
import Network.AWS.StorageGateway.DescribeSnapshotSchedule
import Network.AWS.StorageGateway.DescribeStorediSCSIVolumes
import Network.AWS.StorageGateway.DescribeTapeArchives
import Network.AWS.StorageGateway.DescribeTapeRecoveryPoints
import Network.AWS.StorageGateway.DescribeTapes
import Network.AWS.StorageGateway.DescribeUploadBuffer
import Network.AWS.StorageGateway.DescribeVTLDevices
import Network.AWS.StorageGateway.DescribeWorkingStorage
import Network.AWS.StorageGateway.DisableGateway
import Network.AWS.StorageGateway.ListGateways
import Network.AWS.StorageGateway.ListLocalDisks
import Network.AWS.StorageGateway.ListVolumeInitiators
import Network.AWS.StorageGateway.ListVolumeRecoveryPoints
import Network.AWS.StorageGateway.ListVolumes
import Network.AWS.StorageGateway.ResetCache
import Network.AWS.StorageGateway.RetrieveTapeArchive
import Network.AWS.StorageGateway.RetrieveTapeRecoveryPoint
import Network.AWS.StorageGateway.ShutdownGateway
import Network.AWS.StorageGateway.StartGateway
import Network.AWS.StorageGateway.Types
import Network.AWS.StorageGateway.UpdateBandwidthRateLimit
import Network.AWS.StorageGateway.UpdateChapCredentials
import Network.AWS.StorageGateway.UpdateGatewayInformation
import Network.AWS.StorageGateway.UpdateGatewaySoftwareNow
import Network.AWS.StorageGateway.UpdateMaintenanceStartTime
import Network.AWS.StorageGateway.UpdateSnapshotSchedule
import Network.AWS.StorageGateway.UpdateVTLDeviceType
import Network.AWS.StorageGateway.Waiters
{- $errors
Error matchers are designed for use with the functions provided by
<http://hackage.haskell.org/package/lens/docs/Control-Exception-Lens.html Control.Exception.Lens>.
This allows catching (and rethrowing) service specific errors returned
by 'StorageGateway'.
-}
{- $operations
Some AWS operations return results that are incomplete and require subsequent
requests in order to obtain the entire result set. The process of sending
subsequent requests to continue where a previous request left off is called
pagination. For example, the 'ListObjects' operation of Amazon S3 returns up to
1000 objects at a time, and you must send subsequent requests with the
appropriate Marker in order to retrieve the next page of results.
Operations that have an 'AWSPager' instance can transparently perform subsequent
requests, correctly setting Markers and other request facets to iterate through
the entire result set of a truncated API operation. Operations which support
this have an additional note in the documentation.
Many operations have the ability to filter results on the server side. See the
individual operation parameters for details.
-}
{- $waiters
Waiters poll by repeatedly sending a request until some remote success condition
configured by the 'Wait' specification is fulfilled. The 'Wait' specification
determines how many attempts should be made, in addition to delay and retry strategies.
-}
| fmapfmapfmap/amazonka | amazonka-storagegateway/gen/Network/AWS/StorageGateway.hs | mpl-2.0 | 14,737 | 0 | 5 | 2,741 | 1,196 | 887 | 309 | 208 | 0 |
-- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft }
func = do
x <- stmt
stmt x
| lspitzner/brittany | data/Test442.hs | agpl-3.0 | 145 | 1 | 7 | 23 | 23 | 9 | 14 | 3 | 1 |
{- arch-tag: FTP protocol parser
Copyright (C) 2004 John Goerzen <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
-}
{- |
Module : Network.FTP.Client.Parser
Copyright : Copyright (C) 2004 John Goerzen
License : GNU LGPL, version 2.1 or above
Maintainer : John Goerzen <[email protected]>
Stability : provisional
Portability: systems with networking
This module provides a parser that is used internally by
"Network.FTP.Client". You almost certainly do not want to use
this module directly. Use "Network.FTP.Client" instead.
Written by John Goerzen, jgoerzen\@complete.org
-}
module Network.FTP.Client.Parser(parseReply, parseGoodReply,
toPortString, fromPortString,
debugParseGoodReply,
respToSockAddr,
FTPResult,
-- * Utilities
unexpectedresp, isxresp,
forcexresp,
forceioresp,
parseDirName)
where
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Utils
import Data.List.Utils
import Data.Bits.Utils
import Data.String.Utils
import System.Log.Logger
import Network.Socket(SockAddr(..), PortNumber(..), inet_addr, inet_ntoa)
import System.IO(Handle, hGetContents)
import System.IO.Unsafe
import Text.Regex
import Data.Word
type FTPResult = (Int, [String])
-- import Control.Exception(Exception(PatternMatchFail), throw)
logit :: String -> IO ()
logit m = debugM "Network.FTP.Client.Parser" ("FTP received: " ++ m)
----------------------------------------------------------------------
-- Utilities
----------------------------------------------------------------------
unexpectedresp m r = "FTP: Expected " ++ m ++ ", got " ++ (show r)
isxresp desired (r, _) = r >= desired && r < (desired + 100)
forcexresp desired r = if isxresp desired r
then r
else error ((unexpectedresp (show desired)) r)
forceioresp :: Int -> FTPResult -> IO ()
forceioresp desired r = if isxresp desired r
then return ()
else fail (unexpectedresp (show desired) r)
crlf :: Parser String
crlf = string "\r\n" <?> "CRLF"
sp :: Parser Char
sp = char ' '
code :: Parser Int
code = do
s <- codeString
return (read s)
codeString :: Parser String
codeString = do
first <- oneOf "123456789" <?> "3-digit reply code"
remaining <- count 2 digit <?> "3-digit reply code"
return (first : remaining)
specificCode :: Int -> Parser Int
specificCode exp = do
s <- string (show exp) <?> ("Code " ++ (show exp))
return (read s)
line :: Parser String
line = do
x <- many (noneOf "\r\n")
crlf
-- return $ unsafePerformIO $ putStrLn ("line: " ++ x)
return x
----------------------------------------------------------------------
-- The parsers
----------------------------------------------------------------------
singleReplyLine :: Parser (Int, String)
singleReplyLine = do
x <- code
sp
text <- line
return (x, text)
expectedReplyLine :: Int -> Parser (Int, String)
expectedReplyLine expectedcode = do
x <- specificCode expectedcode
sp
text <- line
return (x, text)
startOfMultiReply :: Parser (Int, String)
startOfMultiReply = do
x <- code
char '-'
text <- line
return (x, text)
multiReplyComponent :: Parser [String]
multiReplyComponent = (try (do
notMatching (do
codeString
sp
) "found unexpected code"
thisLine <- line
-- return $ unsafePerformIO (putStrLn ("MRC: got " ++ thisLine))
remainder <- multiReplyComponent
return (thisLine : remainder)
)
) <|> return []
multiReply :: Parser FTPResult
multiReply = try (do
x <- singleReplyLine
return (fst x, [snd x])
)
<|> (do
start <- startOfMultiReply
component <- multiReplyComponent
end <- expectedReplyLine (fst start)
return (fst start, snd start : (component ++ [snd end]))
)
----------------------------------------------------------------------
-- The real code
----------------------------------------------------------------------
-- | Parse a FTP reply. Returns a (result code, text) pair.
parseReply :: String -> FTPResult
parseReply input =
case parse multiReply "(unknown)" input of
Left err -> error ("FTP: " ++ (show err))
Right reply -> reply
-- | Parse a FTP reply. Returns a (result code, text) pair.
-- If the result code indicates an error, raise an exception instead
-- of just passing it back.
parseGoodReply :: String -> IO FTPResult
parseGoodReply input =
let reply = parseReply input
in
if (fst reply) >= 400
then fail ("FTP:" ++ (show (fst reply)) ++ ": " ++ (join "\n" (snd reply)))
else return reply
-- | Parse a FTP reply. Logs debug messages.
debugParseGoodReply :: String -> IO FTPResult
debugParseGoodReply contents =
let logPlugin :: String -> String -> IO String
logPlugin [] [] = return []
logPlugin [] accum = do
logit accum
return []
logPlugin (x:xs) accum =
case x of
'\n' -> do logit (strip (accum))
next <- unsafeInterleaveIO $ logPlugin xs []
return (x : next)
y -> do
next <- unsafeInterleaveIO $ logPlugin xs (accum ++ [x])
return (x : next)
in
do
loggedStr <- logPlugin contents []
parseGoodReply loggedStr
{- | Converts a socket address to a string suitable for a PORT command.
Example:
> toPortString (SockAddrInet (PortNum 0x1234) (0xaabbccdd)) ->
> "170,187,204,221,18,52"
-}
toPortString :: SockAddr -> IO String
toPortString (SockAddrInet port hostaddr) =
let wport = (fromIntegral (port))::Word16
in do
hn <- inet_ntoa hostaddr
return ((replace "." "," hn) ++ "," ++
(genericJoin "," . getBytes $ wport))
toPortString _ =
error "toPortString only works on AF_INET addresses"
-- | Converts a port string to a socket address. This is the inverse calculation of 'toPortString'.
fromPortString :: String -> IO SockAddr
fromPortString instr =
let inbytes = split "," instr
hostname = join "." (take 4 inbytes)
portbytes = map read (drop 4 inbytes)
in
do
addr <- inet_addr hostname
return $ SockAddrInet (fromInteger $ fromBytes portbytes) addr
respToSockAddrRe = mkRegex("([0-9]+,){5}[0-9]+")
-- | Converts a response code to a socket address
respToSockAddr :: FTPResult -> IO SockAddr
respToSockAddr f =
do
forceioresp 200 f
if (fst f) /= 227 then
fail ("Not a 227 response: " ++ show f)
else case matchRegexAll respToSockAddrRe (head (snd f)) of
Nothing -> fail ("Could not find remote endpoint in " ++ (show f))
Just (_, x, _, _) -> fromPortString x
parseDirName :: FTPResult -> Maybe String
parseDirName (257, name:_) =
let procq [] = []
procq ('"':_) = []
procq ('"' : '"' : xs) = '"' : procq xs
procq (x:xs) = x : procq xs
in
if head name /= '"'
then Nothing
else Just (procq (tail name))
| icetortoise/ftphs | src/Network/FTP/Client/Parser.hs | lgpl-2.1 | 8,975 | 0 | 19 | 3,073 | 1,848 | 936 | 912 | 156 | 5 |
module Main where
import Criterion.Config
import Criterion.Main
import Data.Queue.RealtimeBench
import Data.Queue.SeqBench
import Data.Queue.SimpleBench
main = defaultMainWith myConfig (return ()) [
simpleBench
, realtimeBench
, seqBench
]
myConfig = defaultConfig {
-- Always GC between runs.
cfgPerformGC = ljust True
}
| isturdy/q | bench/Benchmarks.hs | unlicense | 427 | 0 | 8 | 145 | 78 | 47 | 31 | 12 | 1 |
-- Copyright 2016 TensorFlow authors.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
import Data.Int (Int32, Int64)
import Data.List (sort)
import qualified Data.List as List
import Data.ProtoLens.TextFormat (showMessage)
import Test.Framework (defaultMain, Test)
import Lens.Family2 ((^..), (.~))
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit ((@=?), assertEqual, assertFailure)
import qualified Data.Vector as V
import System.Random (randomIO, randomRIO)
import Control.Monad(forM_, replicateM, zipWithM)
import Control.Monad.IO.Class (liftIO)
import qualified TensorFlow.Core as TF
import qualified TensorFlow.GenOps.Core as TF (max, maximum, resizeBilinear', tile, pad, batchToSpaceND, spaceToBatchND, squeeze, sqrt, slice, shape, diag, batchMatMul, batchMatMul', conjugateTranspose)
import qualified TensorFlow.Convolution as TF
import qualified TensorFlow.Gradient as TF
import qualified TensorFlow.Ops as TF hiding (zeroInitializedVariable, shape)
import qualified TensorFlow.Output as TF
import qualified TensorFlow.Types as TF
import qualified TensorFlow.Variable as TF
import Proto.Tensorflow.Core.Framework.Graph_Fields (node)
import Proto.Tensorflow.Core.Framework.NodeDef_Fields (op)
import TensorFlow.Session (SessionT)
testGradientSimple :: Test
testGradientSimple = testCase "testGradientSimple" $ do
let grads = do
x <- TF.render $ TF.scalar (3 :: Float)
b <- TF.render $ TF.scalar (4 :: Float)
let y = x `TF.mul` x `TF.add` b
TF.gradients y [x, b]
-- Assert that the gradients are right.
[dx, db] <- TF.runSession $ grads >>= TF.run
6 @=? TF.unScalar dx
1 @=? TF.unScalar db
-- Assert that the graph has the expected ops.
let graphDef = TF.asGraphDef grads
putStrLn $ showMessage graphDef
let ops = graphDef ^.. node . traverse . op
expected = [ "Const"
, "Mul"
, "Const"
, "Add"
-- Default output gradient of y.
, "Shape"
, "Const"
, "Fill"
-- Add gradient.
, "Shape"
, "Shape"
, "BroadcastGradientArgs"
, "Sum"
, "Sum"
, "Reshape"
, "Reshape"
-- Mul gradient.
, "Shape"
-- This Op gets dedup'd because the inputs are the same.
-- TODO(fmayle): The same would happen to the Mul and Sum ops
-- below if the gradient function didn't multiply one as
-- 'dz * y' and the other as 'x * dz'. We could change the
-- order, but I'm going to keep it the same as the python
-- version for now.
--
-- , "Shape"
, "BroadcastGradientArgs"
, "Mul"
, "Mul"
, "Sum"
, "Sum"
, "Reshape"
, "Reshape"
-- AddN to combine x's output gradients.
, "AddN"
]
sort expected @=? sort ops
testGradientDisconnected :: Test
testGradientDisconnected = testCase "testGradientDisconnected" $ do
let grads = do
x <- TF.render $ TF.scalar (3 :: Float)
b <- TF.render $ TF.scalar (4 :: Float)
TF.gradients x [x, b]
-- Assert that the gradients are right.
[dx, db] <- TF.runSession $ grads >>= TF.run
1 @=? TF.unScalar dx
0 @=? TF.unScalar db
-- Assert that the graph has the expected ops.
let graphDef = TF.asGraphDef grads
putStrLn $ showMessage graphDef
let ops = graphDef ^.. node . traverse . op
expected = [ "Const"
, "Const"
-- Default output gradient of x.
, "Shape"
, "Const"
, "Fill"
-- Default output gradient of b.
, "ZerosLike"
]
sort expected @=? sort ops
testGradientIncidental :: Test
testGradientIncidental = testCase "testGradientIncidental" $ do
let grads = do
x <- TF.render $ TF.scalar (3 :: Float)
b <- TF.render $ TF.scalar (4 :: Float)
w <- TF.render $ TF.diag $ TF.vector [ 1.0 :: Float ]
let incidental = b `TF.mul` w
let y = (x `TF.mul` b) `TF.add` incidental
TF.gradients y [x]
-- Assert that the gradients are right.
[dx] <- TF.runSession $ grads >>= TF.run
4 @=? TF.unScalar dx
-- Assert that the graph has the expected ops.
let graphDef = TF.asGraphDef grads
putStrLn $ showMessage graphDef
let ops = graphDef ^.. node . traverse . op
expected = [ "Add"
, "BroadcastGradientArgs"
, "BroadcastGradientArgs"
, "Const"
, "Const"
, "Const"
, "Const"
, "Diag"
, "Fill"
, "Mul"
, "Mul"
, "Mul"
, "Mul"
, "Reshape"
, "Reshape"
, "Reshape"
, "Reshape"
, "Shape"
, "Shape"
, "Shape"
, "Shape"
, "Shape"
, "Sum"
, "Sum"
, "Sum"
, "Sum"
]
sort expected @=? sort ops
testGradientPruning :: Test
testGradientPruning = testCase "testGradientPruning" $ do
let grads = do
x <- TF.render $ TF.scalar (3 :: Float)
b <- TF.render $ TF.scalar (4 :: Float)
bx <- TF.render $ b `TF.mul` x
let y = bx `TF.add` b
TF.gradients y [x, bx]
-- Assert that the gradients are right.
[dx, dxb] <- TF.runSession $ grads >>= TF.run
4 @=? TF.unScalar dx
1 @=? TF.unScalar dxb
-- Test that identical "stateful" ops work with createGraph.
testCreateGraphStateful :: Test
testCreateGraphStateful = testCase "testCreateGraphStateful" $ do
[dx, dy] <- TF.runSession $ do
let shape = TF.constant (TF.Shape [1]) [1]
x :: TF.Tensor TF.Value Float <- TF.truncatedNormal shape
y :: TF.Tensor TF.Value Float <- TF.truncatedNormal shape
TF.gradients (TF.expr x + TF.expr y * 3) [x, y] >>= TF.run
-- If this test fails, it will likely be caused by an exception within
-- `TF.gradients`. These asserts are extra.
1 @=? TF.unScalar dx
3 @=? TF.unScalar dy
-- Test that name scopes work with createGraph.
testCreateGraphNameScopes :: Test
testCreateGraphNameScopes = testCase "testCreateGraphNameScopes" $ do
[dx] <- TF.runSession $ do
let shape = TF.constant (TF.Shape [1]) [1]
x :: TF.Tensor TF.Value Float <-
TF.withNameScope "foo" (TF.truncatedNormal shape)
TF.gradients x [x] >>= TF.run
-- If this test fails, it will likely be caused by an exception within
-- `TF.gradients`. This assert is extra.
1 @=? TF.unScalar dx
-- Test that createGraph can handle graphs with diamond shapes.
testDiamond :: Test
testDiamond = testCase "testDiamond" $ do
[dx] <- TF.runSession $ do
x <- TF.render $ TF.vector [1]
let y = x `TF.mul` x
z = y*y
TF.gradients z [x] >>= TF.run
(4 :: Float) @=? TF.unScalar dx
testAddNGradient :: Test
testAddNGradient = testCase "testAddNGradient" $ do
[dx] <- TF.runSession $ do
x <- TF.render $ TF.vector [1, 2, 0 :: Float]
let y = TF.addN [x, x]
TF.gradients y [x] >>= TF.run
V.fromList [2, 2, 2 :: Float] @=? dx
testMeanGradient :: Test
testMeanGradient = testCase "testMeanGradient" $ do
[dx] <- TF.runSession $ do
x <- TF.render $ TF.vector [1, 2, 0 :: Float]
let y = TF.mean x (TF.vector [0 :: Int32])
TF.gradients y [x] >>= TF.run
V.fromList [1, 1, 1 :: Float] @=? dx
testMeanGradGrad :: Test
testMeanGradGrad = testCase "testMeanGradGrad" $ do
[ddx] <- TF.runSession $ do
x <- TF.render $ TF.vector [1, 2, 0 :: Float]
let y = TF.mean x (TF.vector [0 :: Int32])
[dx] <- TF.gradients y [x]
TF.gradients dx [x] >>= TF.run
V.fromList [0, 0, 0 :: Float] @=? ddx
testMaxGradient :: Test
testMaxGradient = testCase "testMaxGradient" $ do
[dx] <- TF.runSession $ do
x <- TF.render $ TF.vector [1, 2, 3, 0, 1 :: Float]
let y = TF.max x (0 :: TF.Tensor TF.Build Int32)
TF.gradients y [x] >>= TF.run
V.fromList [0, 0, 1, 0, 0 :: Float] @=? dx
testConcatGradient :: Test
testConcatGradient = testCase "testConcatGradient" $ do
[dv,dv'] <- TF.runSession $ do
v <- TF.render $ TF.vector [1 :: Float]
v' <- TF.render $ TF.vector [2 :: Float]
let y = TF.concat (TF.scalar 0) [ v, v' ]
TF.gradients y [v,v'] >>= TF.run
V.fromList [1 :: Float] @=? dv
V.fromList [1 :: Float] @=? dv'
[dw,dw'] <- TF.runSession $ do
w <- TF.render $ TF.vector [1,2,3,4 :: Float]
w' <- TF.render $ TF.vector [5,6,7,8 :: Float]
let y = TF.concat (TF.scalar 0) [ w, w', w ]
TF.gradients y [w,w'] >>= TF.run
V.fromList [2,2,2,2 :: Float] @=? dw
V.fromList [1,1,1,1 :: Float] @=? dw'
verifyConcatGradients :: [[Int64]] -> Int32 -> IO ()
verifyConcatGradients shapes concatDim = do
let floatsFromShape :: [Int64] -> IO [Float]
floatsFromShape shape = replicateM (fromIntegral $ List.product shape) randomIO
constantZip = zipWithM $ \x shape -> TF.render $ TF.constant (TF.Shape shape) x
inputGrads <- mapM floatsFromShape shapes
inputs <- mapM floatsFromShape shapes
dinputs <- TF.runSession $ do
inputTensors <- inputs `constantZip` shapes
inputGradTensors <- inputGrads `constantZip` shapes
inputTensor <- TF.render $ TF.concat (TF.scalar concatDim) inputTensors
inputGradTensor <- TF.render $ TF.concat (TF.scalar concatDim) inputGradTensors
output <- TF.render $ inputTensor `TF.mul` inputGradTensor
TF.gradients output inputTensors >>= TF.run
(V.fromList <$> inputGrads) @=? dinputs
-- This test checks that the gradient of a concat op
-- is correct along the first, second, and third dimension.
testConcatGradientSimple :: Test
testConcatGradientSimple = testCase "testConcatGradientSimple" $ do
-- The following check is equivalent to ConcatTest._testGradientsSimple from
-- tensorflow/tensorflow/compiler/tests/concat_ops_test.py
verifyConcatGradients [[10,x,2] | x <- [1,2,6]] 1
-- The following check is equivalent to ConcatTest._testGradientsFirstDim from
-- tensorflow/tensorflow/compiler/tests/concat_ops_test.py
verifyConcatGradients [[x,10,2] | x <- [1,2,6]] 0
-- The following check is equivalent to ConcatTest._testGradientsLastDim from
-- tensorflow/tensorflow/compiler/tests/concat_ops_test.py
verifyConcatGradients [[10,2,x] | x <- [1,2,6]] 2
-- This test checks that the gradient of a concat op
-- along a random dimension across random shapes is as expected.
-- This test is inspired by ConcatTest._RunAndVerifyGradientsRandom from
-- tensorflow/tensorflow/compiler/tests/concat_ops_test.py, but also
-- verifies the gradient along negative concat dimensions.
testConcatRunAndVerifyGradientsRandom :: Test
testConcatRunAndVerifyGradientsRandom = testCase "testConcatRunAndVerifyGradientsRandom" $
forM_ [1..5 :: Int] $ \_ -> do
(shapes' :: [Int64]) <- replicateM 5 $ randomRIO (1, 5)
(numTensors :: Int) <- randomRIO (2, 10)
(concatDim :: Int) <- randomRIO (-4, 4)
(concatDimSizes :: [Int64]) <- replicateM numTensors $ randomRIO (1, 5)
let update i xs x = take i xs ++ x: drop (i+1) xs
concatDim' = concatDim `mod` length shapes'
shapes = map (update concatDim' shapes') concatDimSizes
verifyConcatGradients shapes $ fromIntegral concatDim
-- run single test like this:
-- stack --docker --docker-image=$IMAGE_NAME test tensorflow-ops:GradientTest --test-arguments -t"*MaximumGrad*"
testMaximumGrad :: Test
testMaximumGrad = testCase "testMaximumGrad" $ do
[gx, gy] <- TF.runSession $ do
x <- TF.render $ TF.vector [0 :: Float]
y <- TF.render $ TF.vector [0 :: Float]
let z = TF.maximum x y
TF.gradients z [x, y] >>= TF.run
V.fromList [1] @=? gx
V.fromList [1] @=? gy
testMaximumGradGrad :: Test
testMaximumGradGrad = testCase "testMaximumGradGrad" $ do
[ggx] <- TF.runSession $ do
x <- TF.render $ TF.vector [2 :: Float]
y <- TF.render $ TF.vector [1 :: Float]
let z = TF.maximum x y
[gx, _gy] <- TF.gradients z [x, y]
TF.gradients gx [x] >>= TF.run
V.fromList [0] @=? ggx
testReluGrad :: Test
testReluGrad = testCase "testReluGrad" $ do
[dx] <- TF.runSession $ do
x <- TF.render $ TF.vector [2 :: Float]
let y = TF.relu x
TF.gradients y [x] >>= TF.run
V.fromList [1] @=? dx
testReluGradGrad :: Test
testReluGradGrad = testCase "testReluGradGrad" $ do
[dx] <- TF.runSession $ do
x <- TF.render $ TF.vector [2 :: Float]
let y = TF.relu x
[y'] <- TF.gradients y [x]
TF.gradients y' [x] >>= TF.run
V.fromList [0] @=? dx
testTanhGrad :: Test
testTanhGrad = testCase "testTanhGrad" $ do
[dx] <- TF.runSession $ do
x <- TF.render $ TF.vector [0 :: Float]
let y = TF.tanh x
TF.gradients y [x] >>= TF.run
V.fromList [1] @=? dx
testSigmoidGrad :: Test
testSigmoidGrad = testCase "testSigmoidGrad" $ do
[dx] <- TF.runSession $ do
x <- TF.render $ TF.vector [0 :: Float]
let y = TF.sigmoid x
TF.gradients y [x] >>= TF.run
V.fromList [0.25] @=? dx
testExpandDims :: Test
testExpandDims =
testCase "testExpandDims" $ do
([dx], [s]) <-
TF.runSession $ do
(x :: TF.Tensor TF.Value Float) <- TF.render $ TF.zeros $ TF.Shape [1, 2, 3 :: Int64]
let y = TF.expandDims x $ TF.constant (TF.Shape [1]) [0 :: Int32]
calculateGradWithShape y x
V.fromList [1, 1, 1, 1, 1, 1] @=? dx
V.fromList [1, 2, 3] @=? s
testReshape :: Test
testReshape =
testCase "testReshape" $ do
([dx], [s]) <-
TF.runSession $ do
(x :: TF.Tensor TF.Value Float) <- TF.render $ TF.zeros $ TF.Shape [2, 2 :: Int64]
let y = TF.reshape x $ TF.constant (TF.Shape [2]) [1, 4 :: Int32]
calculateGradWithShape y x
V.fromList [1, 1, 1, 1] @=? dx
V.fromList [2, 2] @=? s
testPad :: Test
testPad =
testCase "testPad" $ do
([dx], [s]) <-
TF.runSession $ do
(x :: TF.Tensor TF.Value Float) <- TF.render $ TF.zeros $ TF.Shape [2, 2, 3 :: Int64]
let y = TF.pad x $ TF.constant (TF.Shape [3, 2]) [1, 4, 1, 1, 2, 3 :: Int32]
calculateGradWithShape y x
V.fromList [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] @=? dx
V.fromList [2, 2, 3] @=? s
testSqrt :: Test
testSqrt = testCase "testSqrt" $ do
[dx] <- TF.runSession $ do
x <- TF.render $ TF.vector [0.0625 :: Float]
let y = TF.sqrt x
TF.gradients y [x] >>= TF.run
V.fromList [2] @=? dx
testSlice :: Test
testSlice =
testCase "testSlice" $ do
([dx], [s]) <-
TF.runSession $ do
(x :: TF.Tensor TF.Value Float) <- TF.render $ TF.zeros $ TF.Shape [2, 3, 4 :: Int64]
(z :: TF.Tensor TF.Value Float) <- TF.render $ TF.zeros $ TF.Shape [1, 2, 2 :: Int64]
let y = TF.slice x (TF.constant (TF.Shape [3]) [1, 1, 1 :: Int32]) (TF.shape z)
calculateGradWithShape y x
let expected =
[0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 1, 1, 0,
0, 1, 1, 0]
V.fromList expected @=? dx
V.fromList [2, 3, 4] @=? s
testBatchToSpaceND :: Test
testBatchToSpaceND =
testCase "testBatchToSpaceND" $ do
([dx], [s]) <-
TF.runSession $ do
(x :: TF.Tensor TF.Value Float) <- TF.render $ TF.constant (TF.Shape [4, 1, 1, 1 :: Int64]) [1, 2, 3, 4]
shape <- TF.render $ TF.vector [2, 2 :: Int32]
crops <- TF.render $ TF.constant (TF.Shape [2, 2]) [0, 0, 0, 0 :: Int32]
let y = TF.batchToSpaceND x shape crops
calculateGradWithShape y x
V.fromList [1, 1, 1, 1] @=? dx
V.fromList [4, 1, 1, 1] @=? s
testSpaceToBatchND :: Test
testSpaceToBatchND =
testCase "testSpaceToBatchND" $ do
([dx], [s]) <-
TF.runSession $ do
(x :: TF.Tensor TF.Value Float) <- TF.render $ TF.constant (TF.Shape [1, 2, 2, 1 :: Int64]) [1, 2, 3, 4]
shape <- TF.render $ TF.vector [2, 2 :: Int32]
paddings <- TF.render $ TF.constant (TF.Shape [2, 2]) [0, 0, 0, 0 :: Int32]
let y = TF.spaceToBatchND x shape paddings
calculateGradWithShape y x
V.fromList [1, 1, 1, 1] @=? dx
V.fromList [1, 2, 2, 1] @=? s
testSqueeze :: Test
testSqueeze =
testCase "testSqueeze" $ do
([dx], [s]) <-
TF.runSession $ do
(x :: TF.Tensor TF.Value Float) <- TF.render $ TF.zeros $ TF.Shape [1, 2, 3 :: Int64]
let y = TF.squeeze x
calculateGradWithShape y x
V.fromList [1, 1, 1, 1, 1, 1] @=? dx
V.fromList [1, 2, 3] @=? s
calculateGradWithShape :: TF.Tensor TF.Build Float -> TF.Tensor TF.Value Float -> SessionT IO ([V.Vector Float], [V.Vector Int32])
calculateGradWithShape y x = do
gs <- TF.gradients y [x]
xs <- TF.run gs
(shapes :: [V.Vector Int32]) <- mapM (TF.run . TF.shape) gs
return (xs, shapes)
testFillGrad :: Test
testFillGrad = testCase "testFillGrad" $ do
[dx] <- TF.runSession $ do
x <- TF.render $ TF.scalar (9 :: Float)
let shape = TF.vector [2, 3 :: Int32]
let y = TF.fill shape x
TF.gradients y [x] >>= TF.run
V.fromList [6] @=? dx
testTileGrad :: Test
testTileGrad = testCase "testTileGrad" $ do
[dx] <- TF.runSession $ do
x <- TF.render $ TF.vector [5, 9 :: Float]
let multiples = TF.vector [2 :: Int32]
let y = TF.tile x multiples
TF.gradients y [x] >>= TF.run
V.fromList [2, 2] @=? dx
testTile2DGrad :: Test
testTile2DGrad = testCase "testTileGrad2D" $ do
(dx, shapeDX, shapeX) <- TF.runSession $ do
let shape = TF.vector [3, 2 :: Int32]
x <- TF.render $ TF.fill shape (TF.scalar (1::Float))
let multiples = TF.vector [2, 3 :: Int32]
let y = TF.tile x multiples
[dx] <- TF.gradients y [x]
TF.run (dx, TF.shape dx, TF.shape x)
shapeX @=? (shapeDX :: V.Vector Int32)
V.fromList [6, 6, 6, 6, 6, 6::Float] @=? (dx :: V.Vector Float)
testResizeBilinearGrad :: Test
testResizeBilinearGrad = testCase "testResizeBilinearGrad" $ do
(dx, shapeDX, shapeX) <- TF.runSession $ do
let shape = TF.vector [1, 2, 2, 1 :: Int32]
x <- TF.render $ TF.fill shape (TF.scalar (1 :: Float))
let outSize = TF.vector [4, 4 :: Int32]
align = TF.opAttr "align_corners" .~ True
y = TF.resizeBilinear' align x outSize
[dx] <- TF.gradients y [x]
TF.run (dx, TF.shape dx, TF.shape x)
shapeX @=? (shapeDX :: V.Vector Int32)
let expect = V.fromList [4, 4, 4, 4 :: Float]
near = 0.00001 > (V.sum $ V.zipWith (-) expect (dx :: V.Vector Float))
near @=? True
matMulGradient :: Test
matMulGradient = testCase "matMulGradients" $ do
let dfBuild = do
x <- TF.render $ TF.zeros $ TF.Shape [3, 1 :: Int64]
w <- TF.zeroInitializedVariable $ TF.Shape [1, 2 :: Int64]
let f = x `TF.matMul` TF.readValue w :: TF.Tensor TF.Build Float
dfs <- TF.gradients f [x]
return (x, dfs)
(xShape, dxShape) <- TF.runSession $ do
(x, [dx]) <- TF.build dfBuild
TF.run (TF.shape x, TF.shape dx)
assertEqual "Shape of gradient must match shape of input" xShape (dxShape :: V.Vector Int32)
-- test that gradient of matMul can be taken gradient of
matMulGradGrad :: Test
matMulGradGrad = testCase "matMulGradGrad" $ do
let width = 2 :: Int64
batch = 4 :: Int64
let tower = do
x <- TF.render $ TF.zeros $ TF.Shape [batch, 1]
w <- TF.zeroInitializedVariable $ TF.Shape [1, width]
let f = x `TF.matMul` TF.readValue w
l1 <- TF.gradients f [x]
let dfdx = head l1 -- avoid MonadFail
let f'x = TF.reduceSum dfdx
l2 <- TF.gradients f'x [w] -- take gradient again (this time over w)
let dfdw = head l2
return [TF.readValue w, TF.expr dfdw]
TF.runSession $ do
l <- TF.build tower
(w, dfdw) <-
case l of
[w, dfdw] -> pure (w, dfdw)
_ -> liftIO $ assertFailure "pattern-match failure in matMulGradMad"
(wShape, dfdwShape) <- TF.run (TF.shape w, TF.shape dfdw)
liftIO $ assertEqual "Shape of gradient must match input" wShape (dfdwShape :: V.Vector Int32)
let step = w `TF.add` dfdw
w0 <- TF.run step
liftIO $ V.fromList [4, 4 :: Float] @=? w0
-- test that gradient of matMul deals correctly with transpose_a and transpose_b
matMulTransposeGradient :: (Bool, Bool) -> Test
matMulTransposeGradient txw = testCase ("matMulTransposeGradients " ++ show txw) $ do
let (transposeX, transposeW) = txw
let dfBuild = do
let xShape = TF.Shape [3, 1 :: Int64]
let xZeros = TF.zeros xShape
x <- TF.render $ if transposeX then TF.matTranspose xZeros else xZeros
variable <- TF.zeroInitializedVariable $ TF.Shape [1, 2 :: Int64]
let wv = if transposeW then TF.matTranspose (TF.readValue variable) else TF.readValue variable
let f = TF.matMul' (transAttrs transposeX transposeW) x wv :: TF.Tensor TF.Build Float
w <- TF.render wv
ds <- TF.gradients f [x, w]
return (x, w, ds)
TF.runSession $ do
(x, w, d) <- TF.build dfBuild
(dx, dw) <-
case d of
[dx, dw] -> pure (dx, dw)
_ -> liftIO $ assertFailure "pattern-match failure in matMulTransposeGradient"
xShape <- TF.run $ TF.shape x
dxShape <- TF.run $ TF.shape dx
liftIO $ assertEqual "xShape must match dxShape" xShape (dxShape :: V.Vector Int32)
wShape <- TF.run $ TF.shape w
dwShape <- TF.run $ TF.shape dw
liftIO $ assertEqual "wShape must match dwShape" wShape (dwShape :: V.Vector Int32)
transAttrs :: (TF.Attribute a,
TF.Attribute b) =>
a -> b -> TF.OpDef -> TF.OpDef
transAttrs a b =
(TF.opAttr "transpose_a" .~ a) . (TF.opAttr "transpose_b" .~ b)
batchMatMulGradient :: Test
batchMatMulGradient = testCase "batchMatMulGradients" $ do
let dfBuild = do
x <- TF.render $ TF.zeros $ TF.Shape [2,3, 1 :: Int64]
w <- TF.zeroInitializedVariable $ TF.Shape [2,1, 2 :: Int64]
let f = x `TF.batchMatMul` TF.readValue w :: TF.Tensor TF.Build Float
dfs <- TF.gradients f [x]
return (x, dfs)
(xShape, dxShape) <- TF.runSession $ do
(x, dl) <- TF.build dfBuild
dx <-
case dl of
[dx] -> pure dx
_ -> liftIO $ assertFailure "pattern-match failure in batchMatMulGradient"
TF.run (TF.shape x, TF.shape dx)
assertEqual "Shape of gradient must match shape of input" xShape (dxShape :: V.Vector Int32)
-- test that gradient of batchMatMul can be taken gradient of
batchMatMulGradGrad :: Test
batchMatMulGradGrad = testCase "batchMatMulGradGrad" $ do
let width = 2 :: Int64
height = 3 :: Int64
batch = 4 :: Int64
let tower = do
x <- TF.render $ TF.zeros $ TF.Shape [batch, height, 1]
w <- TF.zeroInitializedVariable $ TF.Shape [batch, 1, width]
let f = x `TF.batchMatMul` TF.readValue w
l1 <- TF.gradients f [x]
let dfdx = head l1
let f'x = TF.sum dfdx (TF.vector [1, 2 :: Int32])
l2 <- TF.gradients f'x [w] -- take gradient again (this time over w)
let dfdw = head l2
return [TF.readValue w, TF.expr dfdw]
TF.runSession $ do
l <- TF.build tower
(w, dfdw) <-
case l of
[w, dfdw] -> pure (w, dfdw)
_ -> liftIO $ assertFailure "pattern-match failure in batchMatMulGradGrad"
(wShape, dfdwShape) <- TF.run (TF.shape w, TF.shape dfdw)
liftIO $ assertEqual "Shape of gradient must match input" wShape (dfdwShape :: V.Vector Int32)
let step = w `TF.add` dfdw
w0 <- TF.run step
liftIO $ V.fromList [3.0,3.0,3.0,3.0,3.0,3.0,3.0,3.0 :: Float] @=? w0
-- test that gradient of batchMatMul deals correctly with adj_x and adj_y
batchMatMulAdjointGradient :: (Bool, Bool) -> Test
batchMatMulAdjointGradient axw = testCase ("batchMatMulAdjointGradients " ++ show axw) $ do
let (adjX, adjW) = axw
let dfBuild = do
let xShape = TF.Shape [2, 3, 1 :: Int64]
let xZeros = TF.zeros xShape
x <- TF.render $ if adjX then TF.conjugateTranspose xZeros (TF.vector [0, 2, 1 :: Int32]) else xZeros
variable <- TF.zeroInitializedVariable $ TF.Shape [2, 1, 2 :: Int64]
let wv = if adjW then TF.conjugateTranspose (TF.readValue variable) (TF.vector [0, 2, 1 :: Int32]) else TF.readValue variable
let f = TF.batchMatMul' (adjAttrs adjX adjW) x wv :: TF.Tensor TF.Build Float
w <- TF.render wv
ds <- TF.gradients f [x, w]
return (x, w, ds)
TF.runSession $ do
(x, w, d) <- TF.build dfBuild
(dx, dw) <-
case d of
[dx, dw] -> pure (dx, dw)
_ -> liftIO $ assertFailure "pattern-match failure in batchMatMulAdjointGradient"
xShape <- TF.run $ TF.shape x
dxShape <- TF.run $ TF.shape dx
liftIO $ assertEqual "xShape must match dxShape" xShape (dxShape :: V.Vector Int32)
wShape <- TF.run $ TF.shape w
dwShape <- TF.run $ TF.shape dw
liftIO $ assertEqual "wShape must match dwShape" wShape (dwShape :: V.Vector Int32)
adjAttrs :: (TF.Attribute x,
TF.Attribute y) =>
x -> y -> TF.OpDef -> TF.OpDef
adjAttrs x y =
(TF.opAttr "adj_x" .~ x) . (TF.opAttr "adj_y" .~ y)
-- TODO check gradient with regard to filter also
testConv2DBackpropInputGrad :: Test
testConv2DBackpropInputGrad = testCase "testConv2DBackpropInputGrad" $ do
(dx, shapeDX, shapeX) <- TF.runSession $ do
let conv_input_shape = TF.vector [1, 2, 2, 1 :: Int32] -- [batch, h, w, in_channels]
let conv_out_shape = TF.vector [1, 1, 1, 1 :: Int32] -- [batch, h, w, out_channels]
x <- TF.render $ TF.fill conv_out_shape (TF.scalar (1::Float))
let filterShape = TF.vector [2, 2, 1, 1 :: Int32] -- [fh, fw, inc, out]
filter' <- TF.render $ TF.fill filterShape (TF.scalar (1::Float))
let y = TF.conv2DBackpropInput'
(TF.opAttr "strides" .~ [1::Int64, 1, 1, 1])
TF.PaddingValid TF.ChannelLast conv_input_shape filter' x
[dx] <- TF.gradients y [x]
TF.run (dx, TF.shape dx, TF.shape x)
shapeX @=? (shapeDX :: V.Vector Int32)
V.fromList [4::Float] @=? (dx :: V.Vector Float)
testDepthwiseConv2dGrad :: Test
testDepthwiseConv2dGrad = testCase "testDepthwiseConv2dGrad" $ do
(dx, shapeDX, shapeX) <- TF.runSession $ do
let conv_input_shape = TF.vector [1, 2, 2, 1 :: Int32]
x <- TF.render $ TF.fill conv_input_shape (TF.scalar (2 :: Float))
let filterShape = TF.vector [2, 2, 1, 1 :: Int32]
filter' <- TF.render $ TF.fill filterShape (TF.scalar (1 :: Float))
let y = TF.depthwiseConv2dNative'
(TF.opAttr "strides" .~ [1 :: Int64, 1, 1, 1])
TF.PaddingValid TF.ChannelLast x filter'
[dx] <- TF.gradients y [x]
TF.run (dx, TF.shape dx, TF.shape x)
shapeX @=? (shapeDX :: V.Vector Int32)
V.fromList [1, 1, 1, 1 :: Float] @=? (dx :: V.Vector Float)
-- TODO also test filter gradient
testDepthwiseConv2dBackpropInputGrad :: Test
testDepthwiseConv2dBackpropInputGrad = testCase "testDepthwiseConv2dBackpropInputGrad" $ do
(dx, shapeDX, shapeX) <- TF.runSession $ do
let conv_input_shape = TF.vector [1, 2, 2, 1 :: Int32]
let conv_out_shape = TF.vector [1, 1, 1, 1 :: Int32] -- [batch, h, w, out_channels]
x <- TF.render $ TF.fill conv_out_shape (TF.scalar (1::Float))
let filterShape = TF.vector [2, 2, 1, 1 :: Int32]
filter' <- TF.render $ TF.fill filterShape (TF.scalar (1 :: Float))
let y = TF.depthwiseConv2dNativeBackpropInput'
(TF.opAttr "strides" .~ [1 :: Int64, 1, 1, 1])
TF.PaddingValid TF.ChannelLast conv_input_shape filter' x
[dx] <- TF.gradients y [x]
TF.run (dx, TF.shape dx, TF.shape x)
shapeX @=? (shapeDX :: V.Vector Int32)
V.fromList [4::Float] @=? (dx :: V.Vector Float)
main :: IO ()
main = defaultMain
[ testGradientSimple
, testGradientDisconnected
, testGradientIncidental
, testGradientPruning
, testCreateGraphStateful
, testCreateGraphNameScopes
, testDiamond
, testAddNGradient
, testMeanGradient
, testMeanGradGrad
, testMaxGradient
, testConcatGradient
, testConcatGradientSimple
, testConcatRunAndVerifyGradientsRandom
, testMaximumGrad
, testMaximumGradGrad
, testReluGrad
, testReluGradGrad
, testTanhGrad
, testSigmoidGrad
, testExpandDims
, testReshape
, testPad
, testSqrt
, testSlice
, testBatchToSpaceND
, testSpaceToBatchND
, testSqueeze
, testFillGrad
, testTileGrad
, testTile2DGrad
, testResizeBilinearGrad
, matMulGradient
, matMulGradGrad
, matMulTransposeGradient (False, False)
, matMulTransposeGradient (False, True)
, matMulTransposeGradient (True, False)
, matMulTransposeGradient (True, True)
, batchMatMulGradient
, batchMatMulGradGrad
, batchMatMulAdjointGradient (False, False)
, batchMatMulAdjointGradient (False, True)
, batchMatMulAdjointGradient (True, False)
, batchMatMulAdjointGradient (True, True)
, testConv2DBackpropInputGrad
, testDepthwiseConv2dGrad
, testDepthwiseConv2dBackpropInputGrad
]
| tensorflow/haskell | tensorflow-ops/tests/GradientTest.hs | apache-2.0 | 31,360 | 13 | 20 | 9,164 | 10,895 | 5,576 | 5,319 | -1 | -1 |
{-# LANGUAGE CPP #-}
module Actions.Logout.Url (url) where
url :: String
url = "/logout"
| DataStewardshipPortal/ds-wizard | DSServer/app/Actions/Logout/Url.hs | apache-2.0 | 92 | 0 | 4 | 17 | 23 | 15 | 8 | 4 | 1 |
module HelperSequences.A035516 (a035516, a035516_list, a035516_row) where
import HelperSequences.A000045 (a000045_list)
a035516 :: Int -> Integer
a035516 = (a035516_list !!)
a035516_list :: [Integer]
a035516_list = concatMap a035516_row [0..]
a035516_row :: Integer -> [Integer]
a035516_row 0 = [0]
a035516_row n = h : t where
h = last $ takeWhile (<= toInteger n) a000045_list
t = if n == h then [] else a035516_row (n - h)
| peterokagey/haskellOEIS | src/HelperSequences/A035516.hs | apache-2.0 | 432 | 0 | 10 | 71 | 153 | 87 | 66 | 11 | 2 |
module Camfort.Transformation.CommonSpec (spec) where
import System.Directory
import System.FilePath
import Test.Hspec
import Camfort.Analysis.Logger (LogLevel (..))
import Camfort.Functionality
samplesBase :: FilePath
samplesBase = "tests" </> "fixtures" </> "Transformation"
data Example = Example FilePath FilePath
readSample :: FilePath -> IO String
readSample filename = do
let path = samplesBase </> filename
readFile path
removeSample filename = do
let path = samplesBase </> filename
removeFile path
spec :: Spec
spec =
describe "Common block integration test" $
context "common.f90 into common.expect.f90 and foo.f90" $ do
expected <- runIO $ readSample "common.expected.f90"
expectedMod <- runIO $ readSample "cmn.expected.f90"
let outFile = samplesBase </> "common.f90.out"
commonFile = samplesBase </> "common.f90"
env = CamfortEnv
{ ceInputSources = commonFile
, ceIncludeDir = Just (takeDirectory commonFile)
, ceExcludeFiles = []
, ceLogLevel = LogDebug
}
runIO $ common outFile env
actual <- runIO $ readSample "common.f90.out"
actualMod <- runIO $ readSample "cmn.f90"
runIO $ removeSample "common.f90.out"
runIO $ removeSample "cmn.f90"
it "it eliminates common statement" $
actual `shouldBe` expected
it "it produces a correct module file" $
actualMod `shouldBe` expectedMod
| dorchard/camfort | tests/Camfort/Transformation/CommonSpec.hs | apache-2.0 | 1,534 | 0 | 15 | 411 | 350 | 177 | 173 | 38 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE OverloadedStrings #-}
module Model where
import Control.Applicative (pure)
import Prelude
import Yesod
import Data.Text (Text, pack, unpack)
import Database.Persist.Quasi
import Data.Typeable (Typeable)
import Data.Time (UTCTime)
import Data.ByteString (ByteString)
import Yesod.Auth.HashDB (HashDBUser(..))
import Data.Aeson (withText, Value(..), ToJSON(..), FromJSON(..))
import Data.Text.Encoding (encodeUtf8, decodeUtf8)
import qualified Data.ByteString.Char8 as BC (pack, unpack)
-- You can define all of your database entities in the entities file.
-- You can find more information on persistent and how to declare entities
-- at:
-- http://www.yesodweb.com/book/persistent/
share [mkPersist sqlOnlySettings, mkMigrate "migrateAll"]
$(persistFileWith lowerCaseSettings "config/models")
instance ToJSON ByteString where
toJSON = String . pack . BC.unpack
instance FromJSON ByteString where
parseJSON = withText "ByteString" $ pure . BC.pack . unpack
instance HashDBUser User where
userPasswordHash = Just . userPassword
setPasswordHash p u = u { userPassword = p }
| rennyhernandez/pure-mu | Model.hs | apache-2.0 | 1,213 | 0 | 9 | 176 | 274 | 164 | 110 | -1 | -1 |
-- pp/Main.hs
--
-- Copyright 2014 Jesse Haber-Kucharsky
-- Released under the terms of the Apache License Version 2.0.
-- See /pulsar/LICENSE or http://www.apache.org/licenses/
module Main where
import qualified Pulsar.FrontEnd as FrontEnd
import qualified Pulsar.FrontEnd.Options as FrontEnd.Options
import qualified Pulsar.Output as Output
import Control.Monad (when)
import Options.Applicative
import System.IO
main :: IO ()
main = execParser config >>= FrontEnd.wrapExceptions "pulsar-pp" . execute
where
config =
info
(helper <*> parseConfig)
(fullDesc <> header "pulsar-pp - The pre-processor for DCPU-16 assembly."
<> progDesc "Pre-process the named file by performing text substitutions.")
execute :: Config -> IO ()
execute config =
do when (isVerbose config)
(printSearchPaths paths)
FrontEnd.withPreProcessedFile paths (inputFilePath config) $ \resultFilePath ->
Output.withHandle (outputFilePath config) $ \h ->
do contents <- readFile resultFilePath
hPutStr h contents
where
paths = searchPaths config
printSearchPaths :: [FilePath] -> IO ()
printSearchPaths paths =
do putStrLn "Searching the following extra paths:"
mapM_ print paths
putStrLn ""
data Config = Config
{ inputFilePath :: FilePath
, isVerbose :: Bool
, searchPaths :: [FilePath]
, outputFilePath :: Maybe FilePath }
deriving (Eq, Show)
parseConfig :: Parser Config
parseConfig = Config
<$> argument str (metavar "INPUT-FILE")
<*> switch (long "verbose"
<> short 'v'
<> help "Print out extra execution information")
<*> FrontEnd.Options.pathList
<*> optional FrontEnd.Options.outputFile
| hakuch/Pulsar | src/pp/Main.hs | apache-2.0 | 1,791 | 0 | 14 | 431 | 405 | 212 | 193 | 42 | 1 |
module TestXmlInternal where
import Test.HUnit
import Text.Proton.XmlTypes
import Text.Proton.XmlInternal
import Text.Proton.Xml
matchesTest = TestCase (do
let test1 = matches "" 'a'
let test2 = matches "abc" 'a'
let test3 = matches "abc" 'c'
let test4 = matches "abc" 'z'
assertEqual "Test 1 should not match" False test1
assertEqual "Test 2 should match" True test2
assertEqual "Test 3 should match" True test3
assertEqual "Test 4 should not match" False test4
)
isWhitespaceTest = TestCase (do
assertEqual "Space should be true" True $ isWhitespace ' '
assertEqual "Tab should be true" True $ isWhitespace '\t'
assertEqual "Newline should be true" True $ isWhitespace '\n'
assertEqual "Carriage should be true" True $ isWhitespace '\r'
assertEqual "Non-whitespace char should be false" False $ isWhitespace 'A'
)
spanUntilTest1 = TestCase (do
let (a,b) = spanUntil (==' ') ""
assertEqual "Empty string should result in empty span" ([], []) (a,b)
)
spanUntilTest2 = TestCase (do
let (a,b) = spanUntil (==' ') "abc def"
assertEqual "Span test2 failed" ("abc ", "def") (a,b)
)
splitOnTest1 = TestCase (do
let (a,b) = splitOn ' ' ""
assertEqual "Spliton Test1 failed" ("", "") (a, b)
)
splitOnTest2 = TestCase (do
let (a,b) = splitOn ' ' "abcd efgh"
assertEqual "Spliton Test1 failed" ("abcd", "efgh") (a, b)
)
splitTextTest = TestCase (do
let test1 = splitText "<a>test</a><b>test</b>"
let test2 = splitText "<a href=\"blah\">test</a>"
assertEqual "Split Text failed" ["<a>","test","</a>","<b>","test","</b>"] test1
assertEqual "Split Text failed" ["<a href=\"blah\">","test","</a>"] test2
)
splitUntilCloseTest = TestCase (do
let (splitA1, splitB1) = splitUntilClose ""
let (splitA2, splitB2) = splitUntilClose "\"abc def\""
let (splitA3, splitB3) = splitUntilClose "\"abc def\" id=\"blah\""
let (splitA4, splitB4) = splitUntilClose "\"abc\\\"def\\\"\" id=\"blah\""
let (splitA5, splitB5) = splitUntilClose "'abc\\'def\\'' id=\"blah\""
let (splitA6, splitB6) = splitUntilClose "\"\">"
assertEqual "Split 1 failed" (splitA1, splitB1) ("", "")
assertEqual "Split 2 failed" (splitA2, splitB2) ("abc def", "")
assertEqual "Split 3 failed" (splitA3, splitB3) ("abc def", " id=\"blah\"")
assertEqual "Split 4 failed" (splitA4, splitB4) ("abc\\\"def\\\"", " id=\"blah\"")
assertEqual "Split 5 failed" (splitA5, splitB5) ("abc\\'def\\'", " id=\"blah\"")
assertEqual "Split 6 failed" (splitA6, splitB6) ("", ">")
)
xmlTests = [TestLabel "Matches Test" matchesTest,
TestLabel "Whitespace Test" isWhitespaceTest,
TestLabel "Span Test 1" spanUntilTest1,
TestLabel "Span Test 2" spanUntilTest2,
TestLabel "Split On Test 1" splitOnTest1,
TestLabel "Split On Test 2" splitOnTest2,
TestLabel "Split Text Test" splitTextTest,
TestLabel "Split Until Close Test" splitUntilCloseTest] | jasonrbriggs/proton | haskell/testsuite/TestXmlInternal.hs | apache-2.0 | 3,072 | 0 | 13 | 684 | 856 | 429 | 427 | 58 | 1 |
{-# LANGUAGE TemplateHaskell, FunctionalDependencies #-}
{-| Implementation of the Ganeti config objects.
-}
{-
Copyright (C) 2011, 2012, 2013, 2014 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Objects
( HvParams
, OsParams
, OsParamsPrivate
, PartialNicParams(..)
, FilledNicParams(..)
, allNicParamFields
, PartialNic(..)
, FileDriver(..)
, DataCollectorConfig(..)
, DiskTemplate(..)
, PartialBeParams(..)
, FilledBeParams(..)
, PartialNDParams(..)
, FilledNDParams(..)
, allNDParamFields
, Node(..)
, AllocPolicy(..)
, FilledISpecParams(..)
, PartialISpecParams(..)
, allISpecParamFields
, MinMaxISpecs(..)
, FilledIPolicy(..)
, PartialIPolicy(..)
, GroupDiskParams
, NodeGroup(..)
, FilterAction(..)
, FilterPredicate(..)
, FilterRule(..)
, filterRuleOrder
, IpFamily(..)
, ipFamilyToRaw
, ipFamilyToVersion
, fillDict
, ClusterHvParams
, OsHvParams
, ClusterBeParams
, ClusterOsParams
, ClusterOsParamsPrivate
, ClusterNicParams
, UidPool
, formatUidRange
, UidRange
, Cluster(..)
, ConfigData(..)
, TimeStampObject(..) -- re-exported from Types
, UuidObject(..) -- re-exported from Types
, SerialNoObject(..) -- re-exported from Types
, TagsObject(..) -- re-exported from Types
, DictObject(..) -- re-exported from THH
, TagSet(..) -- re-exported from THH
, emptyTagSet -- re-exported from THH
, Network(..)
, AddressPool(..)
, Ip4Address()
, mkIp4Address
, Ip4Network()
, mkIp4Network
, ip4netAddr
, ip4netMask
, readIp4Address
, ip4AddressToList
, ip4AddressToNumber
, ip4AddressFromNumber
, nextIp4Address
, IAllocatorParams
, MasterNetworkParameters(..)
, module Ganeti.PartialParams
, module Ganeti.Objects.Disk
, module Ganeti.Objects.Instance
) where
import Control.Arrow (first)
import Control.Monad.State
import qualified Data.ByteString.UTF8 as UTF8
import Data.List (foldl', intercalate)
import Data.Maybe
import qualified Data.Map as Map
import Data.Ord (comparing)
import Data.Ratio (numerator, denominator)
import qualified Data.Semigroup as Sem
import Data.Tuple (swap)
import Data.Word
import Text.JSON (showJSON, readJSON, JSON, JSValue(..), fromJSString,
toJSString)
import qualified Text.JSON as J
import qualified AutoConf
import qualified Ganeti.Constants as C
import qualified Ganeti.ConstantUtils as ConstantUtils
import Ganeti.JSON (DictObject(..), Container, emptyContainer, GenericContainer)
import Ganeti.Objects.BitArray (BitArray)
import Ganeti.Objects.Disk
import Ganeti.Objects.Nic
import Ganeti.Objects.Instance
import Ganeti.Query.Language
import Ganeti.PartialParams
import Ganeti.Types
import Ganeti.THH
import Ganeti.THH.Field
import Ganeti.Utils (sepSplit, tryRead)
-- * Generic definitions
-- | Fills one map with keys from the other map, if not already
-- existing. Mirrors objects.py:FillDict.
fillDict :: (Ord k) => Map.Map k v -> Map.Map k v -> [k] -> Map.Map k v
fillDict defaults custom skip_keys =
let updated = Map.union custom defaults
in foldl' (flip Map.delete) updated skip_keys
-- * Network definitions
-- ** Ipv4 types
data Ip4Address = Ip4Address Word8 Word8 Word8 Word8
deriving (Eq, Ord)
mkIp4Address :: (Word8, Word8, Word8, Word8) -> Ip4Address
mkIp4Address (a, b, c, d) = Ip4Address a b c d
instance Show Ip4Address where
show (Ip4Address a b c d) = intercalate "." $ map show [a, b, c, d]
readIp4Address :: (Applicative m, Monad m) => String -> m Ip4Address
readIp4Address s =
case sepSplit '.' s of
[a, b, c, d] -> Ip4Address <$>
tryRead "first octect" a <*>
tryRead "second octet" b <*>
tryRead "third octet" c <*>
tryRead "fourth octet" d
_ -> fail $ "Can't parse IPv4 address from string " ++ s
instance JSON Ip4Address where
showJSON = showJSON . show
readJSON (JSString s) = readIp4Address (fromJSString s)
readJSON v = fail $ "Invalid JSON value " ++ show v ++ " for an IPv4 address"
-- Converts an address to a list of numbers
ip4AddressToList :: Ip4Address -> [Word8]
ip4AddressToList (Ip4Address a b c d) = [a, b, c, d]
-- | Converts an address into its ordinal number.
-- This is needed for indexing IP adresses in reservation pools.
ip4AddressToNumber :: Ip4Address -> Integer
ip4AddressToNumber = foldl (\n i -> 256 * n + toInteger i) 0 . ip4AddressToList
-- | Converts a number into an address.
-- This is needed for indexing IP adresses in reservation pools.
ip4AddressFromNumber :: Integer -> Ip4Address
ip4AddressFromNumber n =
let s = state $ first fromInteger . swap . (`divMod` 256)
(d, c, b, a) = evalState ((,,,) <$> s <*> s <*> s <*> s) n
in Ip4Address a b c d
nextIp4Address :: Ip4Address -> Ip4Address
nextIp4Address = ip4AddressFromNumber . (+ 1) . ip4AddressToNumber
-- | Custom type for an IPv4 network.
data Ip4Network = Ip4Network { ip4netAddr :: Ip4Address
, ip4netMask :: Word8
}
deriving (Eq)
mkIp4Network :: Ip4Address -> Word8 -> Ip4Network
mkIp4Network = Ip4Network
instance Show Ip4Network where
show (Ip4Network ip netmask) = show ip ++ "/" ++ show netmask
-- | JSON instance for 'Ip4Network'.
instance JSON Ip4Network where
showJSON = showJSON . show
readJSON (JSString s) =
case sepSplit '/' (fromJSString s) of
[ip, nm] -> do
ip' <- readIp4Address ip
nm' <- tryRead "parsing netmask" nm
if nm' >= 0 && nm' <= 32
then return $ Ip4Network ip' nm'
else fail $ "Invalid netmask " ++ show nm' ++ " from string " ++
fromJSString s
_ -> fail $ "Can't parse IPv4 network from string " ++ fromJSString s
readJSON v = fail $ "Invalid JSON value " ++ show v ++ " for an IPv4 network"
-- ** Address pools
-- | Currently address pools just wrap a reservation 'BitArray'.
--
-- In future, 'Network' might be extended to include several address pools
-- and address pools might include their own ranges of addresses.
newtype AddressPool = AddressPool { apReservations :: BitArray }
deriving (Eq, Ord, Show)
instance JSON AddressPool where
showJSON = showJSON . apReservations
readJSON = liftM AddressPool . readJSON
-- ** Ganeti \"network\" config object.
-- FIXME: Not all types might be correct here, since they
-- haven't been exhaustively deduced from the python code yet.
--
-- FIXME: When parsing, check that the ext_reservations and reservations
-- have the same length
$(buildObject "Network" "network" $
[ simpleField "name" [t| NonEmptyString |]
, optionalField $
simpleField "mac_prefix" [t| String |]
, simpleField "network" [t| Ip4Network |]
, optionalField $
simpleField "network6" [t| String |]
, optionalField $
simpleField "gateway" [t| Ip4Address |]
, optionalField $
simpleField "gateway6" [t| String |]
, optionalField $
simpleField "reservations" [t| AddressPool |]
, optionalField $
simpleField "ext_reservations" [t| AddressPool |]
]
++ uuidFields
++ timeStampFields
++ serialFields
++ tagsFields)
instance SerialNoObject Network where
serialOf = networkSerial
instance TagsObject Network where
tagsOf = networkTags
instance UuidObject Network where
uuidOf = UTF8.toString . networkUuid
instance TimeStampObject Network where
cTimeOf = networkCtime
mTimeOf = networkMtime
-- * Datacollector definitions
type MicroSeconds = Integer
-- | The configuration regarding a single data collector.
$(buildObject "DataCollectorConfig" "dataCollector" [
simpleField "active" [t| Bool|],
simpleField "interval" [t| MicroSeconds |]
])
-- | Central default values of the data collector config.
instance Sem.Semigroup DataCollectorConfig where
_ <> a = a
instance Monoid DataCollectorConfig where
mempty = DataCollectorConfig
{ dataCollectorActive = True
, dataCollectorInterval = 10^(6::Integer) * fromIntegral C.mondTimeInterval
}
mappend = (Sem.<>)
-- * IPolicy definitions
$(buildParam "ISpec" "ispec"
[ simpleField ConstantUtils.ispecMemSize [t| Int |]
, simpleField ConstantUtils.ispecDiskSize [t| Int |]
, simpleField ConstantUtils.ispecDiskCount [t| Int |]
, simpleField ConstantUtils.ispecCpuCount [t| Int |]
, simpleField ConstantUtils.ispecNicCount [t| Int |]
, simpleField ConstantUtils.ispecSpindleUse [t| Int |]
])
$(buildObject "MinMaxISpecs" "mmis"
[ renameField "MinSpec" $ simpleField "min" [t| FilledISpecParams |]
, renameField "MaxSpec" $ simpleField "max" [t| FilledISpecParams |]
])
-- | Custom partial ipolicy. This is not built via buildParam since it
-- has a special 2-level inheritance mode.
$(buildObject "PartialIPolicy" "ipolicy"
[ optionalField . renameField "MinMaxISpecsP" $
simpleField ConstantUtils.ispecsMinmax [t| [MinMaxISpecs] |]
, optionalField . renameField "StdSpecP" $
simpleField "std" [t| PartialISpecParams |]
, optionalField . renameField "SpindleRatioP" $
simpleField "spindle-ratio" [t| Double |]
, optionalField . renameField "VcpuRatioP" $
simpleField "vcpu-ratio" [t| Double |]
, optionalField . renameField "DiskTemplatesP" $
simpleField "disk-templates" [t| [DiskTemplate] |]
])
-- | Custom filled ipolicy. This is not built via buildParam since it
-- has a special 2-level inheritance mode.
$(buildObject "FilledIPolicy" "ipolicy"
[ renameField "MinMaxISpecs" $
simpleField ConstantUtils.ispecsMinmax [t| [MinMaxISpecs] |]
, renameField "StdSpec" $ simpleField "std" [t| FilledISpecParams |]
, simpleField "spindle-ratio" [t| Double |]
, simpleField "vcpu-ratio" [t| Double |]
, simpleField "disk-templates" [t| [DiskTemplate] |]
])
-- | Custom filler for the ipolicy types.
instance PartialParams FilledIPolicy PartialIPolicy where
fillParams
(FilledIPolicy { ipolicyMinMaxISpecs = fminmax
, ipolicyStdSpec = fstd
, ipolicySpindleRatio = fspindleRatio
, ipolicyVcpuRatio = fvcpuRatio
, ipolicyDiskTemplates = fdiskTemplates})
(PartialIPolicy { ipolicyMinMaxISpecsP = pminmax
, ipolicyStdSpecP = pstd
, ipolicySpindleRatioP = pspindleRatio
, ipolicyVcpuRatioP = pvcpuRatio
, ipolicyDiskTemplatesP = pdiskTemplates}) =
FilledIPolicy
{ ipolicyMinMaxISpecs = fromMaybe fminmax pminmax
, ipolicyStdSpec = maybe fstd (fillParams fstd) pstd
, ipolicySpindleRatio = fromMaybe fspindleRatio pspindleRatio
, ipolicyVcpuRatio = fromMaybe fvcpuRatio pvcpuRatio
, ipolicyDiskTemplates = fromMaybe fdiskTemplates
pdiskTemplates
}
toPartial (FilledIPolicy { ipolicyMinMaxISpecs = fminmax
, ipolicyStdSpec = fstd
, ipolicySpindleRatio = fspindleRatio
, ipolicyVcpuRatio = fvcpuRatio
, ipolicyDiskTemplates = fdiskTemplates}) =
PartialIPolicy
{ ipolicyMinMaxISpecsP = Just fminmax
, ipolicyStdSpecP = Just $ toPartial fstd
, ipolicySpindleRatioP = Just fspindleRatio
, ipolicyVcpuRatioP = Just fvcpuRatio
, ipolicyDiskTemplatesP = Just fdiskTemplates
}
toFilled (PartialIPolicy { ipolicyMinMaxISpecsP = pminmax
, ipolicyStdSpecP = pstd
, ipolicySpindleRatioP = pspindleRatio
, ipolicyVcpuRatioP = pvcpuRatio
, ipolicyDiskTemplatesP = pdiskTemplates}) =
FilledIPolicy <$> pminmax <*> (toFilled =<< pstd) <*> pspindleRatio
<*> pvcpuRatio <*> pdiskTemplates
-- * Node definitions
$(buildParam "ND" "ndp"
[ simpleField "oob_program" [t| String |]
, simpleField "spindle_count" [t| Int |]
, simpleField "exclusive_storage" [t| Bool |]
, simpleField "ovs" [t| Bool |]
, simpleField "ovs_name" [t| String |]
, simpleField "ovs_link" [t| String |]
, simpleField "ssh_port" [t| Int |]
, simpleField "cpu_speed" [t| Double |]
])
-- | Disk state parameters.
--
-- As according to the documentation this option is unused by Ganeti,
-- the content is just a 'JSValue'.
type DiskState = Container JSValue
-- | Hypervisor state parameters.
--
-- As according to the documentation this option is unused by Ganeti,
-- the content is just a 'JSValue'.
type HypervisorState = Container JSValue
$(buildObject "Node" "node" $
[ simpleField "name" [t| String |]
, simpleField "primary_ip" [t| String |]
, simpleField "secondary_ip" [t| String |]
, simpleField "master_candidate" [t| Bool |]
, simpleField "offline" [t| Bool |]
, simpleField "drained" [t| Bool |]
, simpleField "group" [t| String |]
, simpleField "master_capable" [t| Bool |]
, simpleField "vm_capable" [t| Bool |]
, simpleField "ndparams" [t| PartialNDParams |]
, simpleField "powered" [t| Bool |]
, notSerializeDefaultField [| emptyContainer |] $
simpleField "hv_state_static" [t| HypervisorState |]
, notSerializeDefaultField [| emptyContainer |] $
simpleField "disk_state_static" [t| DiskState |]
]
++ timeStampFields
++ uuidFields
++ serialFields
++ tagsFields)
instance TimeStampObject Node where
cTimeOf = nodeCtime
mTimeOf = nodeMtime
instance UuidObject Node where
uuidOf = UTF8.toString . nodeUuid
instance SerialNoObject Node where
serialOf = nodeSerial
instance TagsObject Node where
tagsOf = nodeTags
-- * NodeGroup definitions
-- | The cluster/group disk parameters type.
type GroupDiskParams = Container DiskParams
-- | A mapping from network UUIDs to nic params of the networks.
type Networks = Container PartialNicParams
$(buildObject "NodeGroup" "group" $
[ simpleField "name" [t| String |]
, defaultField [| [] |] $ simpleField "members" [t| [String] |]
, simpleField "ndparams" [t| PartialNDParams |]
, simpleField "alloc_policy" [t| AllocPolicy |]
, simpleField "ipolicy" [t| PartialIPolicy |]
, simpleField "diskparams" [t| GroupDiskParams |]
, simpleField "networks" [t| Networks |]
, notSerializeDefaultField [| emptyContainer |] $
simpleField "hv_state_static" [t| HypervisorState |]
, notSerializeDefaultField [| emptyContainer |] $
simpleField "disk_state_static" [t| DiskState |]
]
++ timeStampFields
++ uuidFields
++ serialFields
++ tagsFields)
instance TimeStampObject NodeGroup where
cTimeOf = groupCtime
mTimeOf = groupMtime
instance UuidObject NodeGroup where
uuidOf = UTF8.toString . groupUuid
instance SerialNoObject NodeGroup where
serialOf = groupSerial
instance TagsObject NodeGroup where
tagsOf = groupTags
-- * Job scheduler filtering definitions
-- | Actions that can be performed when a filter matches.
data FilterAction
= Accept
| Pause
| Reject
| Continue
| RateLimit Int
deriving (Eq, Ord, Show)
instance JSON FilterAction where
showJSON fa = case fa of
Accept -> JSString (toJSString "ACCEPT")
Pause -> JSString (toJSString "PAUSE")
Reject -> JSString (toJSString "REJECT")
Continue -> JSString (toJSString "CONTINUE")
RateLimit n -> JSArray [ JSString (toJSString "RATE_LIMIT")
, JSRational False (fromIntegral n)
]
readJSON v = case v of
-- `FilterAction`s are case-sensitive.
JSString s | fromJSString s == "ACCEPT" -> return Accept
JSString s | fromJSString s == "PAUSE" -> return Pause
JSString s | fromJSString s == "REJECT" -> return Reject
JSString s | fromJSString s == "CONTINUE" -> return Continue
JSArray (JSString s : rest) | fromJSString s == "RATE_LIMIT" ->
case rest of
[JSRational False n] | denominator n == 1 && numerator n > 0 ->
return . RateLimit . fromIntegral $ numerator n
_ -> fail "RATE_LIMIT argument must be a positive integer"
x -> fail $ "malformed FilterAction JSON: " ++ J.showJSValue x ""
data FilterPredicate
= FPJobId (Filter FilterField)
| FPOpCode (Filter FilterField)
| FPReason (Filter FilterField)
deriving (Eq, Ord, Show)
instance JSON FilterPredicate where
showJSON fp = case fp of
FPJobId expr -> JSArray [string "jobid", showJSON expr]
FPOpCode expr -> JSArray [string "opcode", showJSON expr]
FPReason expr -> JSArray [string "reason", showJSON expr]
where
string = JSString . toJSString
readJSON v = case v of
-- Predicate names are case-sensitive.
JSArray [JSString name, expr]
| name == toJSString "jobid" -> FPJobId <$> readJSON expr
| name == toJSString "opcode" -> FPOpCode <$> readJSON expr
| name == toJSString "reason" -> FPReason <$> readJSON expr
JSArray (JSString name:params) ->
fail $ "malformed FilterPredicate: bad parameter list for\
\ '" ++ fromJSString name ++ "' predicate: "
++ J.showJSArray params ""
_ -> fail "malformed FilterPredicate: must be a list with the first\
\ entry being a string describing the predicate type"
$(buildObject "FilterRule" "fr" $
[ simpleField "watermark" [t| JobId |]
, simpleField "priority" [t| NonNegative Int |]
, simpleField "predicates" [t| [FilterPredicate] |]
, simpleField "action" [t| FilterAction |]
, simpleField "reason_trail" [t| ReasonTrail |]
]
++ uuidFields)
instance UuidObject FilterRule where
uuidOf = UTF8.toString . frUuid
-- | Order in which filter rules are evaluated, according to
-- `doc/design-optables.rst`.
-- For `FilterRule` fields not specified as important for the order,
-- we choose an arbitrary ordering effect (after the ones from the spec).
--
-- The `Ord` instance for `FilterRule` agrees with this function.
-- Yet it is recommended to use this function instead of `compare` to be
-- explicit that the spec order is used.
filterRuleOrder :: FilterRule -> FilterRule -> Ordering
filterRuleOrder = compare
instance Ord FilterRule where
-- It is important that the Ord instance respects the ordering given in
-- `doc/design-optables.rst` for the fields defined in there. The other
-- fields may be ordered arbitrarily.
-- Use `filterRuleOrder` when relying on the spec order.
compare =
comparing $ \(FilterRule watermark prio predicates action reason uuid) ->
( prio, watermark, uuid -- spec part
, predicates, action, reason -- arbitrary part
)
-- | IP family type
$(declareIADT "IpFamily"
[ ("IpFamilyV4", 'AutoConf.pyAfInet4)
, ("IpFamilyV6", 'AutoConf.pyAfInet6)
])
$(makeJSONInstance ''IpFamily)
-- | Conversion from IP family to IP version. This is needed because
-- Python uses both, depending on context.
ipFamilyToVersion :: IpFamily -> Int
ipFamilyToVersion IpFamilyV4 = C.ip4Version
ipFamilyToVersion IpFamilyV6 = C.ip6Version
-- | Cluster HvParams (hvtype to hvparams mapping).
type ClusterHvParams = GenericContainer Hypervisor HvParams
-- | Cluster Os-HvParams (os to hvparams mapping).
type OsHvParams = Container ClusterHvParams
-- | Cluser BeParams.
type ClusterBeParams = Container FilledBeParams
-- | Cluster OsParams.
type ClusterOsParams = Container OsParams
type ClusterOsParamsPrivate = Container (Private OsParams)
-- | Cluster NicParams.
type ClusterNicParams = Container FilledNicParams
-- | A low-high UID ranges.
type UidRange = (Int, Int)
formatUidRange :: UidRange -> String
formatUidRange (lower, higher)
| lower == higher = show lower
| otherwise = show lower ++ "-" ++ show higher
-- | Cluster UID Pool, list (low, high) UID ranges.
type UidPool = [UidRange]
-- | The iallocator parameters type.
type IAllocatorParams = Container JSValue
-- | The master candidate client certificate digests
type CandidateCertificates = Container String
-- * Cluster definitions
$(buildObject "Cluster" "cluster" $
[ simpleField "rsahostkeypub" [t| String |]
, optionalField $
simpleField "dsahostkeypub" [t| String |]
, simpleField "highest_used_port" [t| Int |]
, simpleField "tcpudp_port_pool" [t| [Int] |]
, simpleField "mac_prefix" [t| String |]
, optionalField $
simpleField "volume_group_name" [t| String |]
, simpleField "reserved_lvs" [t| [String] |]
, optionalField $
simpleField "drbd_usermode_helper" [t| String |]
, simpleField "master_node" [t| String |]
, simpleField "master_ip" [t| String |]
, simpleField "master_netdev" [t| String |]
, simpleField "master_netmask" [t| Int |]
, simpleField "use_external_mip_script" [t| Bool |]
, simpleField "cluster_name" [t| String |]
, simpleField "file_storage_dir" [t| String |]
, simpleField "shared_file_storage_dir" [t| String |]
, simpleField "gluster_storage_dir" [t| String |]
, simpleField "enabled_hypervisors" [t| [Hypervisor] |]
, simpleField "hvparams" [t| ClusterHvParams |]
, simpleField "os_hvp" [t| OsHvParams |]
, simpleField "beparams" [t| ClusterBeParams |]
, simpleField "osparams" [t| ClusterOsParams |]
, simpleField "osparams_private_cluster" [t| ClusterOsParamsPrivate |]
, simpleField "nicparams" [t| ClusterNicParams |]
, simpleField "ndparams" [t| FilledNDParams |]
, simpleField "diskparams" [t| GroupDiskParams |]
, simpleField "candidate_pool_size" [t| Int |]
, simpleField "modify_etc_hosts" [t| Bool |]
, simpleField "modify_ssh_setup" [t| Bool |]
, simpleField "maintain_node_health" [t| Bool |]
, simpleField "uid_pool" [t| UidPool |]
, simpleField "default_iallocator" [t| String |]
, simpleField "default_iallocator_params" [t| IAllocatorParams |]
, simpleField "hidden_os" [t| [String] |]
, simpleField "blacklisted_os" [t| [String] |]
, simpleField "primary_ip_family" [t| IpFamily |]
, simpleField "prealloc_wipe_disks" [t| Bool |]
, simpleField "ipolicy" [t| FilledIPolicy |]
, defaultField [| emptyContainer |] $
simpleField "hv_state_static" [t| HypervisorState |]
, defaultField [| emptyContainer |] $
simpleField "disk_state_static" [t| DiskState |]
, simpleField "enabled_disk_templates" [t| [DiskTemplate] |]
, simpleField "candidate_certs" [t| CandidateCertificates |]
, simpleField "max_running_jobs" [t| Int |]
, simpleField "max_tracked_jobs" [t| Int |]
, simpleField "install_image" [t| String |]
, simpleField "instance_communication_network" [t| String |]
, simpleField "zeroing_image" [t| String |]
, simpleField "compression_tools" [t| [String] |]
, simpleField "enabled_user_shutdown" [t| Bool |]
, simpleField "data_collectors" [t| Container DataCollectorConfig |]
, simpleField "ssh_key_type" [t| SshKeyType |]
, simpleField "ssh_key_bits" [t| Int |]
]
++ timeStampFields
++ uuidFields
++ serialFields
++ tagsFields)
instance TimeStampObject Cluster where
cTimeOf = clusterCtime
mTimeOf = clusterMtime
instance UuidObject Cluster where
uuidOf = UTF8.toString . clusterUuid
instance SerialNoObject Cluster where
serialOf = clusterSerial
instance TagsObject Cluster where
tagsOf = clusterTags
-- * ConfigData definitions
$(buildObject "ConfigData" "config" $
-- timeStampFields ++
[ simpleField "version" [t| Int |]
, simpleField "cluster" [t| Cluster |]
, simpleField "nodes" [t| Container Node |]
, simpleField "nodegroups" [t| Container NodeGroup |]
, simpleField "instances" [t| Container Instance |]
, simpleField "networks" [t| Container Network |]
, simpleField "disks" [t| Container Disk |]
, simpleField "filters" [t| Container FilterRule |]
]
++ timeStampFields
++ serialFields)
instance SerialNoObject ConfigData where
serialOf = configSerial
instance TimeStampObject ConfigData where
cTimeOf = configCtime
mTimeOf = configMtime
-- * Master network parameters
$(buildObject "MasterNetworkParameters" "masterNetworkParameters"
[ simpleField "uuid" [t| String |]
, simpleField "ip" [t| String |]
, simpleField "netmask" [t| Int |]
, simpleField "netdev" [t| String |]
, simpleField "ip_family" [t| IpFamily |]
])
| mbakke/ganeti | src/Ganeti/Objects.hs | bsd-2-clause | 27,427 | 0 | 19 | 7,338 | 5,385 | 3,146 | 2,239 | -1 | -1 |
module CVSU.Moments
( Moments(..)
, calculateMoments
, quadTreeMoments
) where
import CVSU.QuadForest
data Moments =
Moments
{ momentCenter :: (Float,Float)
, momentArea :: Float
, momentOrientation :: Float
, momentEccentricity :: Float
}
calculateMoments :: [(Int,Int)] -> Moments
calculateMoments cs = Moments (cx,cy) m00 t e
where
m00 :: Float
m00 = fromIntegral $ length cs
m10 :: Float
m10 = fromIntegral $ sum $ map fst cs
m01 :: Float
m01 = fromIntegral $ sum $ map snd cs
m20 :: Float
m20 = sum $ map ((**2).fromIntegral.fst) cs
m02 :: Float
m02 = sum $ map ((**2).fromIntegral.snd) cs
m11 :: Float
m11 = fromIntegral $ sum $ map (\(f,s) -> f*s) cs
cx :: Float
cx = m10 / m00
cy :: Float
cy = m01 / m00
c20 :: Float
c20 = m20 / m00 - cx**2
c02 :: Float
c02 = m02 / m00 - cy**2
c11 :: Float
c11 = m11 / m00 - cx*cy
l1 :: Float
l1 = 0.5 * (c20 - c02) + 0.5 * (sqrt $ 4 * c11**2 + (c20 - c02)**2)
l2 :: Float
l2 = 0.5 * (c20 - c02) - 0.5 * (sqrt $ 4 * c11**2 + (c20 - c02)**2)
e :: Float
e = sqrt $ 1 - l2 / l1
t :: Float
t = 0.5 * (atan $ 2 * c11 / (c20 - c02))
quadTreePixels t = [(x,y) | x <- [tx..tx+ts-1], y <- [ty..ty+ts-1]]
where
tx = quadTreeX t
ty = quadTreeY t
ts = quadTreeSize t
quadTreeMoments :: [QuadTree] -> Moments
quadTreeMoments ts = calculateMoments $ concatMap quadTreePixels ts
| amnipar/hs-cvsu | CVSU/Moments.hs | bsd-3-clause | 1,459 | 0 | 13 | 422 | 656 | 364 | 292 | 49 | 1 |
module Main where
import System.Environment (getProgName, getArgs)
import System.Exit (die)
import Control.Monad
import Data.Monoid
import qualified Y2015.Day01 as D01
import qualified Y2015.Day02 as D02
import qualified Y2015.Day03 as D03
import qualified Y2015.Day04 as D04
import qualified Y2015.Day05 as D05
import qualified Y2015.Day06 as D06
import qualified Y2015.Day07 as D07
import qualified Y2015.Day08 as D08
import qualified Y2015.Day09 as D09
import qualified Y2015.Day10 as D10
import qualified Y2015.Day11 as D11
import qualified Y2015.Day12 as D12
import qualified Y2015.Day13 as D13
import qualified Y2015.Day14 as D14
import qualified Y2015.Day15 as D15
import qualified Y2015.Day16 as D16
import qualified Y2015.Day17 as D17
import qualified Y2015.Day18 as D18
import qualified Y2015.Day19 as D19
import qualified Y2015.Day20 as D20
import qualified Y2015.Day21 as D21
import qualified Y2015.Day22 as D22
import qualified Y2015.Day23 as D23
import qualified Y2015.Day24 as D24
import qualified Y2015.Day25 as D25
import qualified Y2016.Day11 as Y2016D11
import qualified Y2016.Day15 as Y2016D15
import qualified Y2016.Day19 as Y2016D19
import qualified Y2016.Day22 as Y2016D22
import qualified Y2017.Day01 as Y2017D01
import qualified Y2017.Day02 as Y2017D02
import qualified Y2017.Day03 as Y2017D03
import qualified Y2017.Day04 as Y2017D04
import qualified Y2017.Day05 as Y2017D05
import qualified Y2017.Day06 as Y2017D06
import qualified Y2017.Day07 as Y2017D07
import qualified Y2017.Day08 as Y2017D08
import qualified Y2017.Day09 as Y2017D09
import qualified Y2017.Day10 as Y2017D10
import qualified Y2017.Day11 as Y2017D11
import qualified Y2017.Day12 as Y2017D12
import qualified Y2017.Day13 as Y2017D13
import qualified Y2017.Day14 as Y2017D14
import qualified Y2017.Day15 as Y2017D15
import qualified Y2017.Day16 as Y2017D16
import qualified Y2017.Day17 as Y2017D17
import qualified Y2017.Day18 as Y2017D18
import qualified Y2017.Day19 as Y2017D19
import qualified Y2017.Day20 as Y2017D20
import qualified Y2017.Day21 as Y2017D21
import qualified Y2017.Day22 as Y2017D22
import qualified Y2017.Day23 as Y2017D23
import qualified Y2017.Day24 as Y2017D24
import qualified Y2017.Day25 as Y2017D25
import qualified Y2018.Day01 as Y2018D01
import qualified Y2018.Day02 as Y2018D02
import qualified Y2018.Day03 as Y2018D03
import qualified Y2018.Day04 as Y2018D04
import qualified Y2018.Day05 as Y2018D05
import qualified Y2018.Day06 as Y2018D06
import qualified Y2018.Day07 as Y2018D07
import qualified Y2018.Day08 as Y2018D08
import qualified Y2018.Day09 as Y2018D09
import qualified Y2018.Day10 as Y2018D10
import qualified Y2018.Day11 as Y2018D11
import qualified Y2018.Day12 as Y2018D12
import qualified Y2018.Day13 as Y2018D13
import qualified Y2018.Day14 as Y2018D14
import qualified Y2018.Day16 as Y2018D16
import qualified Y2018.Day17 as Y2018D17
import qualified Y2018.Day18 as Y2018D18
import qualified Y2018.Day19 as Y2018D19
import qualified Y2018.Day20 as Y2018D20
import qualified Y2018.Day21 as Y2018D21
import qualified Y2018.Day22 as Y2018D22
main :: IO ()
main = do
args <- getArgs
when (length args /= 3) $ do
progName <- getProgName
die
( "Usage: "
<> progName
<> " Y day problemNumber. Ex: "
<> progName
<> " 2015 7 1"
)
let (year:day:pbNumber:rest) = map read args :: [Int]
case year of
2015 -> run2015 day pbNumber
2016 -> run2016 day pbNumber
2017 -> run2017 day pbNumber
2018 -> run2018 day pbNumber
_ -> die $ "year unknown: " <> show year
run2015 :: Int -> Int -> IO ()
run2015 day pbNumber = case day * 10 + pbNumber of
11 -> D01.answer1
12 -> D01.answer2
21 -> D02.answer1
22 -> D02.answer2
31 -> D03.answer1
32 -> D03.answer2
41 -> D04.answer1
42 -> D04.answer2
51 -> D05.answer1
52 -> D05.answer2
61 -> D06.answer1
62 -> D06.answer2
71 -> D07.answer1
72 -> D07.answer2
81 -> D08.answer1
82 -> D08.answer2
91 -> D09.answer1
92 -> D09.answer2
101 -> D10.answer1
102 -> D10.answer2
111 -> D11.answer1
112 -> D11.answer2
121 -> D12.answer1
122 -> D12.answer2
131 -> D13.answer1
132 -> D13.answer2
141 -> D14.answer1
142 -> D14.answer2
151 -> D15.answer1
152 -> D15.answer2
161 -> D16.answer1
162 -> D16.answer2
171 -> D17.answer1
172 -> D17.answer2
181 -> D18.answer1
182 -> D18.answer2
191 -> D19.answer1
192 -> D19.answer2
201 -> D20.answer1
202 -> D20.answer2
211 -> D21.answer1
212 -> D21.answer2
221 -> D22.answer1
222 -> D22.answer2
231 -> D23.answer1
232 -> D23.answer2
241 -> D24.answer1
242 -> D24.answer2
251 -> D25.answer1
_ -> putStrLn "Invalid puzzle number"
run2016 :: Int -> Int -> IO ()
run2016 day pbNumber = case day * 10 + pbNumber of
111 -> Y2016D11.answer1
112 -> Y2016D11.answer2
151 -> Y2016D15.answer1
152 -> Y2016D15.answer2
192 -> Y2016D19.answer2
221 -> Y2016D22.answer1 >>= print
222 -> Y2016D22.answer2 >>= print
_ -> print "Invalid puzzle number"
run2017 :: Int -> Int -> IO ()
run2017 day pbNumber = case day * 10 + pbNumber of
11 -> Y2017D01.answer1
12 -> Y2017D01.answer2
21 -> Y2017D02.answer1
22 -> Y2017D02.answer2
31 -> Y2017D03.answer1
32 -> Y2017D03.answer2
41 -> Y2017D04.answer1
42 -> Y2017D04.answer2
51 -> Y2017D05.answer1
52 -> Y2017D05.answer2
61 -> Y2017D06.answer1
62 -> Y2017D06.answer2
71 -> Y2017D07.answer1
72 -> Y2017D07.answer2
81 -> Y2017D08.answer1
82 -> Y2017D08.answer2
91 -> Y2017D09.answer1
92 -> Y2017D09.answer2
101 -> Y2017D10.answer1
102 -> Y2017D10.answer2
111 -> Y2017D11.answer1
112 -> Y2017D11.answer2
121 -> Y2017D12.answer1
122 -> Y2017D12.answer2
131 -> Y2017D13.answer1
132 -> Y2017D13.answer2
141 -> Y2017D14.answer1
142 -> Y2017D14.answer2
151 -> Y2017D15.answer1
152 -> Y2017D15.answer2
161 -> Y2017D16.answer1
162 -> Y2017D16.answer2
171 -> Y2017D17.answer1
172 -> Y2017D17.answer2
181 -> Y2017D18.answer1
182 -> Y2017D18.answer2
191 -> Y2017D19.answer1
192 -> Y2017D19.answer2
201 -> Y2017D20.answer1
202 -> Y2017D20.answer2
211 -> Y2017D21.answer1
212 -> Y2017D21.answer2
221 -> Y2017D22.answer1
222 -> Y2017D22.answer2
231 -> Y2017D23.answer1
232 -> Y2017D23.answer2
241 -> Y2017D24.answer1
242 -> Y2017D24.answer2
251 -> Y2017D25.answer1
_ -> putStrLn "Invalid puzzle number"
run2018 :: Int -> Int -> IO ()
run2018 day pbNumber = case day * 10 + pbNumber of
11 -> Y2018D01.answer1
12 -> Y2018D01.answer2
21 -> Y2018D02.answer1
22 -> Y2018D02.answer2
31 -> Y2018D03.answer1
32 -> Y2018D03.answer2
41 -> Y2018D04.answer1
42 -> Y2018D04.answer2
51 -> Y2018D05.answer1
52 -> Y2018D05.answer2
61 -> Y2018D06.answer1
62 -> Y2018D06.answer2
71 -> Y2018D07.answer1
72 -> Y2018D07.answer2
81 -> Y2018D08.answer1
82 -> Y2018D08.answer2
91 -> Y2018D09.answer1
92 -> Y2018D09.answer2
101 -> Y2018D10.answer1
102 -> Y2018D10.answer2
111 -> Y2018D11.answer1
112 -> Y2018D11.answer2
121 -> Y2018D12.answer1
122 -> Y2018D12.answer2
131 -> Y2018D13.answer1
132 -> Y2018D13.answer2
141 -> Y2018D14.answer1
142 -> Y2018D14.answer2
161 -> Y2018D16.answer1
162 -> Y2018D16.answer2
171 -> Y2018D17.answer1
172 -> Y2018D17.answer2
181 -> Y2018D18.answer1
182 -> Y2018D18.answer2
191 -> Y2018D19.answer1
192 -> Y2018D19.answer2
201 -> Y2018D20.answer1
202 -> Y2018D20.answer2
211 -> Y2018D21.answer1
212 -> Y2018D21.answer2
221 -> Y2018D22.answer1
222 -> Y2018D22.answer2
_ -> print "Invalid puzzle number"
| geekingfrog/advent-of-code | src/Main.hs | bsd-3-clause | 7,999 | 0 | 15 | 1,804 | 2,195 | 1,245 | 950 | 257 | 50 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
-- |
-- Module : Snap.Snaplet.ReCaptcha
-- Copyright : (c) Mike Ledger 2014
-- (c) Lars Petersen 2012
--
-- License : BSD-style
--
-- Maintainer : [email protected], [email protected]
-- Stability : experimental
-- Portability : portable
--
-- This is a snaplet for google's ReCaptcha verification api. This library uses
-- `http-conduit` and keeps connections alive (a maximum of 10). This is an
-- important point in order to avoid denial of service attacks.
--
-- See 'Snap.Snaplet.ReCaptcha.Example' and the docs provided here for example
-- usage.
--
module Snap.Snaplet.ReCaptcha
( -- * Snaplet and Initialization
ReCaptcha ()
, HasReCaptcha (..)
, initReCaptcha
, initReCaptcha'
-- * Handlers
, checkCaptcha
, withCaptcha
, getCaptcha
-- * Types
, Captcha(..)
, PrivateKey
, SiteKey
-- * Extra
, cstate
, recaptchaScript, recaptchaDiv
) where
import qualified Blaze.ByteString.Builder as Blaze
import Control.Applicative
import Control.Lens
import Control.Monad.Reader (runReaderT)
import qualified Data.Aeson as JSON
import qualified Data.Aeson.TH as JSON
import qualified Data.ByteString.Char8 as BS
import qualified Data.Configurator as Conf
import Data.Text (Text)
import Data.Text.Encoding (encodeUtf8)
import Data.Foldable (fold, for_, toList)
import Data.Monoid
import Data.Typeable
import Heist
import Heist.Compiled
import qualified Network.HTTP.Client.Conduit as HTTP
import Snap
import Snap.Snaplet.Heist.Compiled
type PrivateKey = BS.ByteString
type SiteKey = BS.ByteString
type UserIP = BS.ByteString
type UserAnswer = BS.ByteString
data Captcha
= Success
| Failure
-- | Errors returned by the Captcha. See <https://developers.google.com/recaptcha/docs/verify>
-- for possible error codes. Note that 'Failure' is used for the case that the
-- only error code returned is "invalid-input-response".
| Errors [Text]
-- | The server didn't respond with the JSON object required as per
-- <https://developers.google.com/recaptcha/docs/verify>
| InvalidServerResponse
-- | There was no "recaptcha_response_field" parameter set in the user request.
| MissingResponseParam
deriving (Show, Typeable)
data ReCaptcha = ReCaptcha
{ connectionManager :: !HTTP.Manager
, recaptchaQuery :: !(UserIP -> UserAnswer -> HTTP.Request)
, _cstate :: !Captcha
} deriving (Typeable)
makeLenses ''ReCaptcha
class HasReCaptcha b where
captchaLens :: SnapletLens (Snaplet b) ReCaptcha
instance HasReCaptcha ReCaptcha where
captchaLens = id
-- This is kinda lame - should we just parse it manually?
data ReCaptchaResponse = ReCaptchaResponse
{ success :: !Bool
, error_codes :: !(Maybe [Text])
}
JSON.deriveJSON JSON.defaultOptions ''Captcha
JSON.deriveFromJSON JSON.defaultOptions
{ JSON.fieldLabelModifier = map $ \c -> case c of
'_' -> '-'
_ -> c
} ''ReCaptchaResponse
initialiser :: Maybe (Snaplet (Heist b)) -> (SiteKey, PrivateKey)
-> Initializer b v ReCaptcha
initialiser mheist (site,key) = do
-- this has to parse for the snaplet to work at all
req <- liftIO (HTTP.parseUrl "https://www.google.com/recaptcha/api/siteverify")
man <- liftIO HTTP.newManager
for_ mheist (\heist -> addReCaptchaHeist heist site)
return ReCaptcha
{ connectionManager = man
, recaptchaQuery = \ip answer ->
HTTP.urlEncodedBody
[ ("secret" , key)
, ("response" , answer)
, ("remoteip" , ip) ]
req
, _cstate = Failure
}
-- | Initialise the 'ReCaptcha' snaplet. You are required to have "site_key" and
-- "secret_key" set in the snaplet's configuration file. See 'initReCaptcha\''
-- if you don't want to use Snap's snaplet configuration mechanism.
--
-- This provides optional Heist support, which is implemented using
-- 'recaptchaScript' and 'recaptchaDiv'.
initReCaptcha :: Maybe (Snaplet (Heist b)) -> SnapletInit b ReCaptcha
initReCaptcha heist =
makeSnaplet "recaptcha" "ReCaptcha integration" Nothing $
initialiser heist =<< do
conf <- getSnapletUserConfig
(,) <$> require conf "site_key"
<*> require conf "secret_key"
where
require conf field = do
v <- liftIO (Conf.lookup conf field)
case v of
Just v' -> return v'
Nothing -> do
spath <- BS.pack `fmap` getSnapletFilePath
err <- errorMsg (encodeUtf8 field <> " not in the config " <> spath
<> "/devel.cfg")
fail (BS.unpack err)
-- | Same as 'initReCaptcha', but passing the site key and private key
-- explicitly - no configuration on the filesystem is required.
initReCaptcha' :: Maybe (Snaplet (Heist b)) -> (SiteKey, PrivateKey)
-> SnapletInit b ReCaptcha
initReCaptcha' heist keys =
makeSnaplet "recaptcha" "ReCaptcha integration" Nothing
(initialiser heist keys)
addReCaptchaHeist :: Snaplet (Heist b) -> BS.ByteString -> Initializer b v ()
addReCaptchaHeist heist site = addConfig heist $ mempty &~ do
scCompiledSplices .= do
"recaptcha-div" ## pureSplice id (return (recaptchaDiv site))
"recaptcha-script" ## pureSplice id (return recaptchaScript)
-- | @<script src='https://www.google.com/recaptcha/api.js' async defer></script> @
recaptchaScript :: Blaze.Builder
recaptchaScript = Blaze.fromByteString
"<script src='https://www.google.com/recaptcha/api.js' async defer></script>"
-- | For use in a HTML form.
recaptchaDiv :: BS.ByteString -> Blaze.Builder
recaptchaDiv site = Blaze.fromByteString $!
"<div class='g-recaptcha' data-sitekey='" <> site <> "'></div>"
-- | Get the ReCaptcha result by querying Google's API.
--
-- This requires a "g-recaptcha-response" (POST) parameter to be set in the
-- current request.
--
-- See 'ReCaptchaResult' for possible failure types.
--
-- @
-- cstate <- getCaptcha
-- case cstate of
-- Success -> writeText "Congratulations! You won."
-- Failure -> writeText "Incorrect cstate answer."
-- MissingResponseParam -> writeText "No g-recaptcha-response in POST"
-- InvalidServerResponse -> writeText "Did Google change their API?"
-- Errors errs -> writeText ("Errors: " <> 'T.pack' ('show' errs))
-- @
--
-- This may throw a 'HTTP.HttpException' if there is a connection-related error.
getCaptcha :: HasReCaptcha b => Handler b c Captcha
getCaptcha = do
mresponse <- getPostParam "g-recaptcha-response"
case mresponse of
Just answer -> withTop' captchaLens $ do
manager <- gets connectionManager
getQuery <- gets recaptchaQuery
remoteip <- getsRequest rqRemoteAddr
response <- runReaderT (HTTP.httpLbs (getQuery remoteip answer)) manager
-- The reply is a JSON object looking like
-- {
-- "success": true|false,
-- "error-codes": [...] // optional
-- }
-- see <https://developers.google.com/recaptcha/docs/verify>
-- we just use aeson and the derived FromJSON instance here
return $! case JSON.decode (HTTP.responseBody response) of
Just obj
| success obj -> Success
| invalidInput obj -> Failure
| otherwise -> Errors (fold (error_codes obj))
Nothing -> InvalidServerResponse
Nothing -> return MissingResponseParam
where
invalidInput obj = error_codes obj == Just ["invalid-input-response"]
-- | Run one of two handlers on either failing or succeeding a captcha.
--
-- @
-- 'withCaptcha' banForever $ do
-- postId <- 'getParam' "id"
-- thing <- 'getPostParam' thing
-- addCommentToDB postId thing
-- @
--
-- See 'getCaptcha'
withCaptcha
:: HasReCaptcha b
=> Handler b c () -- ^ Ran on failure
-> Handler b c () -- ^ Ran on success
-> Handler b c ()
withCaptcha onFail onSuccess = do
s <- getCaptcha
withTop' captchaLens (cstate .= s)
case s of
Success -> onSuccess
_ -> onFail
-- | 'pass' if the cstate failed. Logs errors (not incorrect captchas) with
-- 'logError'.
--
-- @ 'checkCaptcha' '<|>' 'writeText' "Captcha failed!" @
--
-- See 'getCaptcha'
checkCaptcha :: HasReCaptcha b => Handler b c ()
checkCaptcha = do
s <- getCaptcha
withTop' captchaLens (cstate .= s)
case s of
Success -> return ()
Failure -> pass
someError -> do
logError =<< errorMsg (BS.pack (show someError))
pass
errorMsg :: (MonadSnaplet m, Monad (m b v)) => BS.ByteString
-> m b v BS.ByteString
errorMsg err = do
ancestry <- getSnapletAncestry
name <- getSnapletName
return $! showTextList (ancestry++toList name) <> " (ReCaptcha) : " <> err
where
showTextList :: [Text] -> BS.ByteString
showTextList = BS.intercalate "/" . map encodeUtf8
| lpeterse/snaplet-recaptcha | src/Snap/Snaplet/ReCaptcha.hs | bsd-3-clause | 9,185 | 0 | 22 | 2,134 | 1,703 | 919 | 784 | 174 | 3 |
module T453 where
import Control.Monad.Trans.Class
import Data.Kind
import Data.Singletons.TH
import Data.Singletons.TH.Options
$(withOptions defaultOptions{genSingKindInsts = False} $
singletons [d|
type T1 :: forall k. k -> Type
data T1 a
type T2 :: k -> Type
data T2 a
|])
| goldfirere/singletons | singletons-base/tests/compile-and-dump/Singletons/T453.hs | bsd-3-clause | 299 | 0 | 10 | 62 | 58 | 36 | 22 | -1 | -1 |
{-# LANGUAGE MultiParamTypeClasses
,FunctionalDependencies
,FlexibleInstances
,FlexibleContexts
,GeneralizedNewtypeDeriving
,TypeSynonymInstances
,TypeOperators
,ParallelListComp
,BangPatterns
#-}
{-
This file is part of funsat.
funsat is free software: it is released under the BSD3 open source license.
You can find details of this license in the file LICENSE at the root of the
source tree.
Copyright 2008 Denis Bueno
-}
-- | Data types used when dealing with SAT problems in funsat.
module Funsat.Types where
import Data.Array.ST
import Data.Array.Unboxed
import Data.BitSet ( BitSet )
import Data.Int( Int64 )
import Data.List( intercalate )
import Data.Map ( Map )
import Data.Set ( Set )
import Data.STRef
import Prelude hiding ( sum, concatMap, elem, foldr, foldl, any, maximum )
import qualified Data.BitSet as BitSet
import qualified Data.Foldable as Fl
import qualified Data.Graph.Inductive.Graph as Graph
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Data.Set as Set
-- * Basic Types
newtype Var = V {unVar :: Int} deriving (Eq, Ord, Enum, Ix)
instance Show Var where
show (V i) = show i ++ "v"
instance Num Var where
_ + _ = error "+ doesn't make sense for variables"
_ - _ = error "- doesn't make sense for variables"
_ * _ = error "* doesn't make sense for variables"
signum _ = error "signum doesn't make sense for variables"
negate = error "negate doesn't make sense for variables"
abs = id
fromInteger l | l <= 0 = error $ show l ++ " is not a variable"
| otherwise = V $ fromInteger l
newtype Lit = L {unLit :: Int} deriving (Eq, Ord, Enum, Ix)
instance Num Lit where
_ + _ = error "+ doesn't make sense for literals"
_ - _ = error "- doesn't make sense for literals"
_ * _ = error "* doesn't make sense for literals"
signum _ = error "signum doesn't make sense for literals"
negate = inLit negate
abs = inLit abs
fromInteger l | l == 0 = error "0 is not a literal"
| otherwise = L $ fromInteger l
-- | Transform the number inside the literal.
inLit :: (Int -> Int) -> Lit -> Lit
inLit f = L . f . unLit
-- | The polarity of the literal. Negative literals are false; positive
-- literals are true. The 0-literal is an error.
litSign :: Lit -> Bool
litSign (L x) | x < 0 = False
| x > 0 = True
| otherwise = error "litSign of 0"
instance Show Lit where show = show . unLit
instance Read Lit where
readsPrec i s = map (\(i,s) -> (L i, s)) (readsPrec i s)
-- | The variable for the given literal.
var :: Lit -> Var
var = V . abs . unLit
-- | The positive literal for the given variable.
lit :: Var -> Lit
lit = L . unVar
type Clause = [Lit]
data CNF = CNF
{ numVars :: Int
, numClauses :: Int
, clauses :: Set Clause } deriving (Show, Read, Eq)
-- | The solution to a SAT problem. In each case we return an assignment,
-- which is obviously right in the `Sat' case; in the `Unsat' case, the reason
-- is to assist in the generation of an unsatisfiable core.
data Solution = Sat !IAssignment | Unsat !IAssignment deriving (Eq)
instance Show Solution where
show (Sat a) = "satisfiable: " ++ showAssignment a
show (Unsat _) = "unsatisfiable"
finalAssignment :: Solution -> IAssignment
finalAssignment (Sat a) = a
finalAssignment (Unsat a) = a
-- | Represents a container of type @t@ storing elements of type @a@ that
-- support membership, insertion, and deletion.
--
-- There are various data structures used in funsat which are essentially used
-- as ''set-like'' objects. I've distilled their interface into three
-- methods. These methods are used extensively in the implementation of the
-- solver.
class Ord a => Setlike t a where
-- | The set-like object with an element removed.
without :: t -> a -> t
-- | The set-like object with an element included.
with :: t -> a -> t
-- | Whether the set-like object contains a certain element.
contains :: t -> a -> Bool
instance Ord a => Setlike (Set a) a where
without = flip Set.delete
with = flip Set.insert
contains = flip Set.member
instance Ord a => Setlike [a] a where
without = flip List.delete
with = flip (:)
contains = flip List.elem
instance Setlike IAssignment Lit where
without a l = a // [(var l, 0)]
with a l = a // [(var l, unLit l)]
contains a l = unLit l == a ! (var l)
instance (Ord k, Ord a) => Setlike (Map k a) (k, a) where
with m (k,v) = Map.insert k v m
without m (k,_) = Map.delete k m
contains = error "no contains for Setlike (Map k a) (k, a)"
instance (Ord a, Enum a) => Setlike (BitSet a) a where
with = flip BitSet.insert
without = flip BitSet.delete
contains = flip BitSet.member
-- * Assignments
-- | An ''immutable assignment''. Stores the current assignment according to
-- the following convention. A literal @L i@ is in the assignment if in
-- location @(abs i)@ in the array, @i@ is present. Literal @L i@ is absent
-- if in location @(abs i)@ there is 0. It is an error if the location @(abs
-- i)@ is any value other than @0@ or @i@ or @negate i@.
--
-- Note that the `Model' instance for `Lit' and `IAssignment' takes constant
-- time to execute because of this representation for assignments. Also
-- updating an assignment with newly-assigned literals takes constant time,
-- and can be done destructively, but safely.
type IAssignment = UArray Var Int
showAssignment :: IAssignment -> String
showAssignment a = intercalate " " ([show (a!i) | i <- range . bounds $ a,
(a!i) /= 0])
-- | Mutable array corresponding to the `IAssignment' representation.
type MAssignment s = STUArray s Var Int
-- | The union of the reason side and the conflict side are all the nodes in
-- the `cutGraph' (excepting, perhaps, the nodes on the reason side at
-- decision level 0, which should never be present in a learned clause).
data Cut f gr a b =
Cut { reasonSide :: f Graph.Node
-- ^ The reason side contains at least the decision variables.
, conflictSide :: f Graph.Node
-- ^ The conflict side contains the conflicting literal.
, cutUIP :: Graph.Node
, cutGraph :: gr a b }
instance (Show (f Graph.Node), Show (gr a b)) => Show (Cut f gr a b) where
show (Cut { conflictSide = c, cutUIP = uip }) =
"Cut (uip=" ++ show uip ++ ", cSide=" ++ show c ++ ")"
-- | Annotate each variable in the conflict graph with literal (indicating its
-- assignment) and decision level. The only reason we make a new datatype for
-- this is for its `Show' instance.
data CGNodeAnnot = CGNA Lit Int
-- | Just a graph with special node annotations.
type ConflictGraph g = g CGNodeAnnot ()
-- | The lambda node is connected exactly to the two nodes causing the conflict.
cgLambda :: CGNodeAnnot
cgLambda = CGNA (L 0) (-1)
instance Show CGNodeAnnot where
show (CGNA (L 0) _) = "lambda"
show (CGNA l lev) = show l ++ " (" ++ show lev ++ ")"
-- * Model
-- | An instance of this class is able to answer the question, Is a
-- truth-functional object @x@ true under the model @m@? Or is @m@ a model
-- for @x@? There are three possible answers for this question: `True' (''the
-- object is true under @m@''), `False' (''the object is false under @m@''),
-- and undefined, meaning its status is uncertain or unknown (as is the case
-- with a partial assignment).
--
-- The only method in this class is so named so it reads well when used infix.
-- Also see: `isTrueUnder', `isFalseUnder', `isUndefUnder'.
class Model a m where
-- | @x ``statusUnder`` m@ should use @Right@ if the status of @x@ is
-- defined, and @Left@ otherwise.
statusUnder :: a -> m -> Either () Bool
-- /O(1)/.
instance Model Lit IAssignment where
statusUnder l a | a `contains` l = Right True
| a `contains` negate l = Right False
| otherwise = Left ()
instance Model Var IAssignment where
statusUnder v a | a `contains` pos = Right True
| a `contains` neg = Right False
| otherwise = Left ()
where pos = L (unVar v)
neg = negate pos
instance Model Clause IAssignment where
statusUnder c m
-- true if c intersect m is not null == a member of c in m
| Fl.any (\e -> m `contains` e) c = Right True
-- false if all its literals are false under m.
| Fl.all (`isFalseUnder` m) c = Right False
| otherwise = Left ()
where
isFalseUnder x m = isFalse $ x `statusUnder` m
where isFalse (Right False) = True
isFalse _ = False
-- * Internal data types
type Level = Int
-- | A /level array/ maintains a record of the decision level of each variable
-- in the solver. If @level@ is such an array, then @level[i] == j@ means the
-- decision level for var number @i@ is @j@. @j@ must be non-negative when
-- the level is defined, and `noLevel' otherwise.
--
-- Whenever an assignment of variable @v@ is made at decision level @i@,
-- @level[unVar v]@ is set to @i@.
type LevelArray s = STUArray s Var Level
-- | Immutable version.
type FrozenLevelArray = UArray Var Level
-- | The VSIDS-like dynamic variable ordering.
newtype VarOrder s = VarOrder { varOrderArr :: STUArray s Var Double }
deriving Show
newtype FrozenVarOrder = FrozenVarOrder (UArray Var Double)
deriving Show
-- | Each pair of watched literals is paired with its clause and id.
type WatchedPair s = (STRef s (Lit, Lit), Clause, ClauseId)
type WatchArray s = STArray s Lit [WatchedPair s]
data PartialResolutionTrace = PartialResolutionTrace
{ resTraceIdCount :: !Int
, resTrace :: ![Int]
, resTraceOriginalSingles :: ![(Clause, ClauseId)]
-- Singleton clauses are not stored in the database, they are assigned.
-- But we need to record their ids, so we put them here.
, resSourceMap :: Map ClauseId [ClauseId] } deriving (Show)
type ReasonMap = Map Var (Clause, ClauseId)
type ClauseId = Int
instance Show (STRef s a) where show = const "<STRef>"
instance Show (STUArray s Var Int) where show = const "<STUArray Var Int>"
instance Show (STUArray s Var Double) where show = const "<STUArray Var Double>"
instance Show (STArray s a b) where show = const "<STArray>"
-- * Configuration
-- | A choice of conflict graph cut for learning clauses.
data ConflictCut = FirstUipCut
| DecisionLitCut
deriving (Show)
-- | Configuration parameters for the solver.
data FunsatConfig = Cfg
{ configRestart :: !Int64 -- ^ Number of conflicts before a restart.
, configRestartBump :: !Double -- ^ `configRestart' is altered after each
-- restart by multiplying it by this value.
, configUseVSIDS :: !Bool -- ^ If true, use dynamic variable ordering.
, configUseRestarts :: !Bool
, configCut :: !ConflictCut
}
deriving (Show)
| dbueno/funsat | src/Funsat/Types.hs | bsd-3-clause | 11,327 | 0 | 12 | 2,972 | 2,391 | 1,301 | 1,090 | 186 | 1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
Taken quite directly from the Peyton Jones/Lester paper.
-}
{-# LANGUAGE CPP #-}
-- | A module concerned with finding the free variables of an expression.
module CoreFVs (
-- * Free variables of expressions and binding groups
exprFreeVars,
exprFreeVarsDSet,
exprFreeVarsList,
exprFreeIds,
exprFreeIdsDSet,
exprFreeIdsList,
exprsFreeIdsDSet,
exprsFreeIdsList,
exprsFreeVars,
exprsFreeVarsList,
bindFreeVars,
-- * Selective free variables of expressions
InterestingVarFun,
exprSomeFreeVars, exprsSomeFreeVars,
exprSomeFreeVarsList, exprsSomeFreeVarsList,
-- * Free variables of Rules, Vars and Ids
varTypeTyCoVars,
varTypeTyCoFVs,
idUnfoldingVars, idFreeVars, dIdFreeVars,
bndrRuleAndUnfoldingVarsDSet,
idFVs,
idRuleVars, idRuleRhsVars, stableUnfoldingVars,
ruleRhsFreeVars, ruleFreeVars, rulesFreeVars,
rulesFreeVarsDSet,
ruleLhsFreeIds, ruleLhsFreeIdsList,
vectsFreeVars,
expr_fvs,
-- * Orphan names
orphNamesOfType, orphNamesOfCo, orphNamesOfAxiom,
orphNamesOfTypes, orphNamesOfCoCon,
exprsOrphNames, orphNamesOfFamInst,
-- * Core syntax tree annotation with free variables
FVAnn, -- annotation, abstract
CoreExprWithFVs, -- = AnnExpr Id FVAnn
CoreExprWithFVs', -- = AnnExpr' Id FVAnn
CoreBindWithFVs, -- = AnnBind Id FVAnn
CoreAltWithFVs, -- = AnnAlt Id FVAnn
freeVars, -- CoreExpr -> CoreExprWithFVs
freeVarsBind, -- CoreBind -> DVarSet -> (DVarSet, CoreBindWithFVs)
freeVarsOf, -- CoreExprWithFVs -> DIdSet
freeVarsOfAnn
) where
#include "HsVersions.h"
import GhcPrelude
import CoreSyn
import Id
import IdInfo
import NameSet
import UniqSet
import Unique (Uniquable (..))
import Name
import VarSet
import Var
import Type
import TyCoRep
import TyCon
import CoAxiom
import FamInstEnv
import TysPrim( funTyConName )
import Maybes( orElse )
import Util
import BasicTypes( Activation )
import Outputable
import FV
{-
************************************************************************
* *
\section{Finding the free variables of an expression}
* *
************************************************************************
This function simply finds the free variables of an expression.
So far as type variables are concerned, it only finds tyvars that are
* free in type arguments,
* free in the type of a binder,
but not those that are free in the type of variable occurrence.
-}
-- | Find all locally-defined free Ids or type variables in an expression
-- returning a non-deterministic set.
exprFreeVars :: CoreExpr -> VarSet
exprFreeVars = fvVarSet . exprFVs
-- | Find all locally-defined free Ids or type variables in an expression
-- returning a composable FV computation. See Note [FV naming conventions] in FV
-- for why export it.
exprFVs :: CoreExpr -> FV
exprFVs = filterFV isLocalVar . expr_fvs
-- | Find all locally-defined free Ids or type variables in an expression
-- returning a deterministic set.
exprFreeVarsDSet :: CoreExpr -> DVarSet
exprFreeVarsDSet = fvDVarSet . exprFVs
-- | Find all locally-defined free Ids or type variables in an expression
-- returning a deterministically ordered list.
exprFreeVarsList :: CoreExpr -> [Var]
exprFreeVarsList = fvVarList . exprFVs
-- | Find all locally-defined free Ids in an expression
exprFreeIds :: CoreExpr -> IdSet -- Find all locally-defined free Ids
exprFreeIds = exprSomeFreeVars isLocalId
-- | Find all locally-defined free Ids in an expression
-- returning a deterministic set.
exprFreeIdsDSet :: CoreExpr -> DIdSet -- Find all locally-defined free Ids
exprFreeIdsDSet = exprSomeFreeVarsDSet isLocalId
-- | Find all locally-defined free Ids in an expression
-- returning a deterministically ordered list.
exprFreeIdsList :: CoreExpr -> [Id] -- Find all locally-defined free Ids
exprFreeIdsList = exprSomeFreeVarsList isLocalId
-- | Find all locally-defined free Ids in several expressions
-- returning a deterministic set.
exprsFreeIdsDSet :: [CoreExpr] -> DIdSet -- Find all locally-defined free Ids
exprsFreeIdsDSet = exprsSomeFreeVarsDSet isLocalId
-- | Find all locally-defined free Ids in several expressions
-- returning a deterministically ordered list.
exprsFreeIdsList :: [CoreExpr] -> [Id] -- Find all locally-defined free Ids
exprsFreeIdsList = exprsSomeFreeVarsList isLocalId
-- | Find all locally-defined free Ids or type variables in several expressions
-- returning a non-deterministic set.
exprsFreeVars :: [CoreExpr] -> VarSet
exprsFreeVars = fvVarSet . exprsFVs
-- | Find all locally-defined free Ids or type variables in several expressions
-- returning a composable FV computation. See Note [FV naming conventions] in FV
-- for why export it.
exprsFVs :: [CoreExpr] -> FV
exprsFVs exprs = mapUnionFV exprFVs exprs
-- | Find all locally-defined free Ids or type variables in several expressions
-- returning a deterministically ordered list.
exprsFreeVarsList :: [CoreExpr] -> [Var]
exprsFreeVarsList = fvVarList . exprsFVs
-- | Find all locally defined free Ids in a binding group
bindFreeVars :: CoreBind -> VarSet
bindFreeVars (NonRec b r) = fvVarSet $ filterFV isLocalVar $ rhs_fvs (b,r)
bindFreeVars (Rec prs) = fvVarSet $ filterFV isLocalVar $
addBndrs (map fst prs)
(mapUnionFV rhs_fvs prs)
-- | Finds free variables in an expression selected by a predicate
exprSomeFreeVars :: InterestingVarFun -- ^ Says which 'Var's are interesting
-> CoreExpr
-> VarSet
exprSomeFreeVars fv_cand e = fvVarSet $ filterFV fv_cand $ expr_fvs e
-- | Finds free variables in an expression selected by a predicate
-- returning a deterministically ordered list.
exprSomeFreeVarsList :: InterestingVarFun -- ^ Says which 'Var's are interesting
-> CoreExpr
-> [Var]
exprSomeFreeVarsList fv_cand e = fvVarList $ filterFV fv_cand $ expr_fvs e
-- | Finds free variables in an expression selected by a predicate
-- returning a deterministic set.
exprSomeFreeVarsDSet :: InterestingVarFun -- ^ Says which 'Var's are interesting
-> CoreExpr
-> DVarSet
exprSomeFreeVarsDSet fv_cand e = fvDVarSet $ filterFV fv_cand $ expr_fvs e
-- | Finds free variables in several expressions selected by a predicate
exprsSomeFreeVars :: InterestingVarFun -- Says which 'Var's are interesting
-> [CoreExpr]
-> VarSet
exprsSomeFreeVars fv_cand es =
fvVarSet $ filterFV fv_cand $ mapUnionFV expr_fvs es
-- | Finds free variables in several expressions selected by a predicate
-- returning a deterministically ordered list.
exprsSomeFreeVarsList :: InterestingVarFun -- Says which 'Var's are interesting
-> [CoreExpr]
-> [Var]
exprsSomeFreeVarsList fv_cand es =
fvVarList $ filterFV fv_cand $ mapUnionFV expr_fvs es
-- | Finds free variables in several expressions selected by a predicate
-- returning a deterministic set.
exprsSomeFreeVarsDSet :: InterestingVarFun -- ^ Says which 'Var's are interesting
-> [CoreExpr]
-> DVarSet
exprsSomeFreeVarsDSet fv_cand e =
fvDVarSet $ filterFV fv_cand $ mapUnionFV expr_fvs e
-- Comment about obselete code
-- We used to gather the free variables the RULES at a variable occurrence
-- with the following cryptic comment:
-- "At a variable occurrence, add in any free variables of its rule rhss
-- Curiously, we gather the Id's free *type* variables from its binding
-- site, but its free *rule-rhs* variables from its usage sites. This
-- is a little weird. The reason is that the former is more efficient,
-- but the latter is more fine grained, and a makes a difference when
-- a variable mentions itself one of its own rule RHSs"
-- Not only is this "weird", but it's also pretty bad because it can make
-- a function seem more recursive than it is. Suppose
-- f = ...g...
-- g = ...
-- RULE g x = ...f...
-- Then f is not mentioned in its own RHS, and needn't be a loop breaker
-- (though g may be). But if we collect the rule fvs from g's occurrence,
-- it looks as if f mentions itself. (This bites in the eftInt/eftIntFB
-- code in GHC.Enum.)
--
-- Anyway, it seems plain wrong. The RULE is like an extra RHS for the
-- function, so its free variables belong at the definition site.
--
-- Deleted code looked like
-- foldVarSet add_rule_var var_itself_set (idRuleVars var)
-- add_rule_var var set | keep_it fv_cand in_scope var = extendVarSet set var
-- | otherwise = set
-- SLPJ Feb06
addBndr :: CoreBndr -> FV -> FV
addBndr bndr fv fv_cand in_scope acc
= (varTypeTyCoFVs bndr `unionFV`
-- Include type variables in the binder's type
-- (not just Ids; coercion variables too!)
FV.delFV bndr fv) fv_cand in_scope acc
addBndrs :: [CoreBndr] -> FV -> FV
addBndrs bndrs fv = foldr addBndr fv bndrs
expr_fvs :: CoreExpr -> FV
expr_fvs (Type ty) fv_cand in_scope acc =
tyCoFVsOfType ty fv_cand in_scope acc
expr_fvs (Coercion co) fv_cand in_scope acc =
tyCoFVsOfCo co fv_cand in_scope acc
expr_fvs (Var var) fv_cand in_scope acc = FV.unitFV var fv_cand in_scope acc
expr_fvs (Lit _) fv_cand in_scope acc = emptyFV fv_cand in_scope acc
expr_fvs (Tick t expr) fv_cand in_scope acc =
(tickish_fvs t `unionFV` expr_fvs expr) fv_cand in_scope acc
expr_fvs (App fun arg) fv_cand in_scope acc =
(expr_fvs fun `unionFV` expr_fvs arg) fv_cand in_scope acc
expr_fvs (Lam bndr body) fv_cand in_scope acc =
addBndr bndr (expr_fvs body) fv_cand in_scope acc
expr_fvs (Cast expr co) fv_cand in_scope acc =
(expr_fvs expr `unionFV` tyCoFVsOfCo co) fv_cand in_scope acc
expr_fvs (Case scrut bndr ty alts) fv_cand in_scope acc
= (expr_fvs scrut `unionFV` tyCoFVsOfType ty `unionFV` addBndr bndr
(mapUnionFV alt_fvs alts)) fv_cand in_scope acc
where
alt_fvs (_, bndrs, rhs) = addBndrs bndrs (expr_fvs rhs)
expr_fvs (Let (NonRec bndr rhs) body) fv_cand in_scope acc
= (rhs_fvs (bndr, rhs) `unionFV` addBndr bndr (expr_fvs body))
fv_cand in_scope acc
expr_fvs (Let (Rec pairs) body) fv_cand in_scope acc
= addBndrs (map fst pairs)
(mapUnionFV rhs_fvs pairs `unionFV` expr_fvs body)
fv_cand in_scope acc
---------
rhs_fvs :: (Id, CoreExpr) -> FV
rhs_fvs (bndr, rhs) = expr_fvs rhs `unionFV`
bndrRuleAndUnfoldingFVs bndr
-- Treat any RULES as extra RHSs of the binding
---------
exprs_fvs :: [CoreExpr] -> FV
exprs_fvs exprs = mapUnionFV expr_fvs exprs
tickish_fvs :: Tickish Id -> FV
tickish_fvs (Breakpoint _ ids) = FV.mkFVs ids
tickish_fvs _ = emptyFV
{-
************************************************************************
* *
\section{Free names}
* *
************************************************************************
-}
-- | Finds the free /external/ names of an expression, notably
-- including the names of type constructors (which of course do not show
-- up in 'exprFreeVars').
exprOrphNames :: CoreExpr -> NameSet
-- There's no need to delete local binders, because they will all
-- be /internal/ names.
exprOrphNames e
= go e
where
go (Var v)
| isExternalName n = unitNameSet n
| otherwise = emptyNameSet
where n = idName v
go (Lit _) = emptyNameSet
go (Type ty) = orphNamesOfType ty -- Don't need free tyvars
go (Coercion co) = orphNamesOfCo co
go (App e1 e2) = go e1 `unionNameSet` go e2
go (Lam v e) = go e `delFromNameSet` idName v
go (Tick _ e) = go e
go (Cast e co) = go e `unionNameSet` orphNamesOfCo co
go (Let (NonRec _ r) e) = go e `unionNameSet` go r
go (Let (Rec prs) e) = exprsOrphNames (map snd prs) `unionNameSet` go e
go (Case e _ ty as) = go e `unionNameSet` orphNamesOfType ty
`unionNameSet` unionNameSets (map go_alt as)
go_alt (_,_,r) = go r
-- | Finds the free /external/ names of several expressions: see 'exprOrphNames' for details
exprsOrphNames :: [CoreExpr] -> NameSet
exprsOrphNames es = foldr (unionNameSet . exprOrphNames) emptyNameSet es
{- **********************************************************************
%* *
orphNamesXXX
%* *
%********************************************************************* -}
orphNamesOfTyCon :: TyCon -> NameSet
orphNamesOfTyCon tycon = unitNameSet (getName tycon) `unionNameSet` case tyConClass_maybe tycon of
Nothing -> emptyNameSet
Just cls -> unitNameSet (getName cls)
orphNamesOfType :: Type -> NameSet
orphNamesOfType ty | Just ty' <- coreView ty = orphNamesOfType ty'
-- Look through type synonyms (Trac #4912)
orphNamesOfType (TyVarTy _) = emptyNameSet
orphNamesOfType (LitTy {}) = emptyNameSet
orphNamesOfType (TyConApp tycon tys) = orphNamesOfTyCon tycon
`unionNameSet` orphNamesOfTypes tys
orphNamesOfType (ForAllTy bndr res) = orphNamesOfType (binderKind bndr)
`unionNameSet` orphNamesOfType res
orphNamesOfType (FunTy arg res) = unitNameSet funTyConName -- NB! See Trac #8535
`unionNameSet` orphNamesOfType arg
`unionNameSet` orphNamesOfType res
orphNamesOfType (AppTy fun arg) = orphNamesOfType fun `unionNameSet` orphNamesOfType arg
orphNamesOfType (CastTy ty co) = orphNamesOfType ty `unionNameSet` orphNamesOfCo co
orphNamesOfType (CoercionTy co) = orphNamesOfCo co
orphNamesOfThings :: (a -> NameSet) -> [a] -> NameSet
orphNamesOfThings f = foldr (unionNameSet . f) emptyNameSet
orphNamesOfTypes :: [Type] -> NameSet
orphNamesOfTypes = orphNamesOfThings orphNamesOfType
orphNamesOfCo :: Coercion -> NameSet
orphNamesOfCo (Refl _ ty) = orphNamesOfType ty
orphNamesOfCo (TyConAppCo _ tc cos) = unitNameSet (getName tc) `unionNameSet` orphNamesOfCos cos
orphNamesOfCo (AppCo co1 co2) = orphNamesOfCo co1 `unionNameSet` orphNamesOfCo co2
orphNamesOfCo (ForAllCo _ kind_co co)
= orphNamesOfCo kind_co `unionNameSet` orphNamesOfCo co
orphNamesOfCo (FunCo _ co1 co2) = orphNamesOfCo co1 `unionNameSet` orphNamesOfCo co2
orphNamesOfCo (CoVarCo _) = emptyNameSet
orphNamesOfCo (AxiomInstCo con _ cos) = orphNamesOfCoCon con `unionNameSet` orphNamesOfCos cos
orphNamesOfCo (UnivCo p _ t1 t2) = orphNamesOfProv p `unionNameSet` orphNamesOfType t1 `unionNameSet` orphNamesOfType t2
orphNamesOfCo (SymCo co) = orphNamesOfCo co
orphNamesOfCo (TransCo co1 co2) = orphNamesOfCo co1 `unionNameSet` orphNamesOfCo co2
orphNamesOfCo (NthCo _ co) = orphNamesOfCo co
orphNamesOfCo (LRCo _ co) = orphNamesOfCo co
orphNamesOfCo (InstCo co arg) = orphNamesOfCo co `unionNameSet` orphNamesOfCo arg
orphNamesOfCo (CoherenceCo co1 co2) = orphNamesOfCo co1 `unionNameSet` orphNamesOfCo co2
orphNamesOfCo (KindCo co) = orphNamesOfCo co
orphNamesOfCo (SubCo co) = orphNamesOfCo co
orphNamesOfCo (AxiomRuleCo _ cs) = orphNamesOfCos cs
orphNamesOfProv :: UnivCoProvenance -> NameSet
orphNamesOfProv UnsafeCoerceProv = emptyNameSet
orphNamesOfProv (PhantomProv co) = orphNamesOfCo co
orphNamesOfProv (ProofIrrelProv co) = orphNamesOfCo co
orphNamesOfProv (PluginProv _) = emptyNameSet
orphNamesOfProv (HoleProv _) = emptyNameSet
orphNamesOfCos :: [Coercion] -> NameSet
orphNamesOfCos = orphNamesOfThings orphNamesOfCo
orphNamesOfCoCon :: CoAxiom br -> NameSet
orphNamesOfCoCon (CoAxiom { co_ax_tc = tc, co_ax_branches = branches })
= orphNamesOfTyCon tc `unionNameSet` orphNamesOfCoAxBranches branches
orphNamesOfAxiom :: CoAxiom br -> NameSet
orphNamesOfAxiom axiom
= orphNamesOfTypes (concatMap coAxBranchLHS $ fromBranches $ coAxiomBranches axiom)
`extendNameSet` getName (coAxiomTyCon axiom)
orphNamesOfCoAxBranches :: Branches br -> NameSet
orphNamesOfCoAxBranches
= foldr (unionNameSet . orphNamesOfCoAxBranch) emptyNameSet . fromBranches
orphNamesOfCoAxBranch :: CoAxBranch -> NameSet
orphNamesOfCoAxBranch (CoAxBranch { cab_lhs = lhs, cab_rhs = rhs })
= orphNamesOfTypes lhs `unionNameSet` orphNamesOfType rhs
-- | orphNamesOfAxiom collects the names of the concrete types and
-- type constructors that make up the LHS of a type family instance,
-- including the family name itself.
--
-- For instance, given `type family Foo a b`:
-- `type instance Foo (F (G (H a))) b = ...` would yield [Foo,F,G,H]
--
-- Used in the implementation of ":info" in GHCi.
orphNamesOfFamInst :: FamInst -> NameSet
orphNamesOfFamInst fam_inst = orphNamesOfAxiom (famInstAxiom fam_inst)
{-
************************************************************************
* *
\section[freevars-everywhere]{Attaching free variables to every sub-expression}
* *
************************************************************************
-}
-- | Those variables free in the right hand side of a rule returned as a
-- non-deterministic set
ruleRhsFreeVars :: CoreRule -> VarSet
ruleRhsFreeVars (BuiltinRule {}) = noFVs
ruleRhsFreeVars (Rule { ru_fn = _, ru_bndrs = bndrs, ru_rhs = rhs })
= fvVarSet $ filterFV isLocalVar $ addBndrs bndrs (expr_fvs rhs)
-- See Note [Rule free var hack]
-- | Those variables free in the both the left right hand sides of a rule
-- returned as a non-deterministic set
ruleFreeVars :: CoreRule -> VarSet
ruleFreeVars = fvVarSet . ruleFVs
-- | Those variables free in the both the left right hand sides of a rule
-- returned as FV computation
ruleFVs :: CoreRule -> FV
ruleFVs (BuiltinRule {}) = emptyFV
ruleFVs (Rule { ru_fn = _do_not_include
-- See Note [Rule free var hack]
, ru_bndrs = bndrs
, ru_rhs = rhs, ru_args = args })
= filterFV isLocalVar $ addBndrs bndrs (exprs_fvs (rhs:args))
-- | Those variables free in the both the left right hand sides of rules
-- returned as FV computation
rulesFVs :: [CoreRule] -> FV
rulesFVs = mapUnionFV ruleFVs
-- | Those variables free in the both the left right hand sides of rules
-- returned as a deterministic set
rulesFreeVarsDSet :: [CoreRule] -> DVarSet
rulesFreeVarsDSet rules = fvDVarSet $ rulesFVs rules
idRuleRhsVars :: (Activation -> Bool) -> Id -> VarSet
-- Just the variables free on the *rhs* of a rule
idRuleRhsVars is_active id
= mapUnionVarSet get_fvs (idCoreRules id)
where
get_fvs (Rule { ru_fn = fn, ru_bndrs = bndrs
, ru_rhs = rhs, ru_act = act })
| is_active act
-- See Note [Finding rule RHS free vars] in OccAnal.hs
= delOneFromUniqSet_Directly fvs (getUnique fn)
-- Note [Rule free var hack]
where
fvs = fvVarSet $ filterFV isLocalVar $ addBndrs bndrs (expr_fvs rhs)
get_fvs _ = noFVs
-- | Those variables free in the right hand side of several rules
rulesFreeVars :: [CoreRule] -> VarSet
rulesFreeVars rules = mapUnionVarSet ruleFreeVars rules
ruleLhsFreeIds :: CoreRule -> VarSet
-- ^ This finds all locally-defined free Ids on the left hand side of a rule
-- and returns them as a non-deterministic set
ruleLhsFreeIds = fvVarSet . ruleLhsFVIds
ruleLhsFreeIdsList :: CoreRule -> [Var]
-- ^ This finds all locally-defined free Ids on the left hand side of a rule
-- and returns them as a determinisitcally ordered list
ruleLhsFreeIdsList = fvVarList . ruleLhsFVIds
ruleLhsFVIds :: CoreRule -> FV
-- ^ This finds all locally-defined free Ids on the left hand side of a rule
-- and returns an FV computation
ruleLhsFVIds (BuiltinRule {}) = emptyFV
ruleLhsFVIds (Rule { ru_bndrs = bndrs, ru_args = args })
= filterFV isLocalId $ addBndrs bndrs (exprs_fvs args)
{-
Note [Rule free var hack] (Not a hack any more)
~~~~~~~~~~~~~~~~~~~~~~~~~
We used not to include the Id in its own rhs free-var set.
Otherwise the occurrence analyser makes bindings recursive:
f x y = x+y
RULE: f (f x y) z ==> f x (f y z)
However, the occurrence analyser distinguishes "non-rule loop breakers"
from "rule-only loop breakers" (see BasicTypes.OccInfo). So it will
put this 'f' in a Rec block, but will mark the binding as a non-rule loop
breaker, which is perfectly inlinable.
-}
-- |Free variables of a vectorisation declaration
vectsFreeVars :: [CoreVect] -> VarSet
vectsFreeVars = mapUnionVarSet vectFreeVars
where
vectFreeVars (Vect _ rhs) = fvVarSet $ filterFV isLocalId $ expr_fvs rhs
vectFreeVars (NoVect _) = noFVs
vectFreeVars (VectType _ _ _) = noFVs
vectFreeVars (VectClass _) = noFVs
vectFreeVars (VectInst _) = noFVs
-- this function is only concerned with values, not types
{-
************************************************************************
* *
\section[freevars-everywhere]{Attaching free variables to every sub-expression}
* *
************************************************************************
The free variable pass annotates every node in the expression with its
NON-GLOBAL free variables and type variables.
-}
type FVAnn = DVarSet
-- | Every node in a binding group annotated with its
-- (non-global) free variables, both Ids and TyVars, and type.
type CoreBindWithFVs = AnnBind Id FVAnn
-- | Every node in an expression annotated with its
-- (non-global) free variables, both Ids and TyVars, and type.
type CoreExprWithFVs = AnnExpr Id FVAnn
type CoreExprWithFVs' = AnnExpr' Id FVAnn
-- | Every node in an expression annotated with its
-- (non-global) free variables, both Ids and TyVars, and type.
type CoreAltWithFVs = AnnAlt Id FVAnn
freeVarsOf :: CoreExprWithFVs -> DIdSet
-- ^ Inverse function to 'freeVars'
freeVarsOf (fvs, _) = fvs
-- | Extract the vars reported in a FVAnn
freeVarsOfAnn :: FVAnn -> DIdSet
freeVarsOfAnn fvs = fvs
noFVs :: VarSet
noFVs = emptyVarSet
aFreeVar :: Var -> DVarSet
aFreeVar = unitDVarSet
unionFVs :: DVarSet -> DVarSet -> DVarSet
unionFVs = unionDVarSet
unionFVss :: [DVarSet] -> DVarSet
unionFVss = unionDVarSets
delBindersFV :: [Var] -> DVarSet -> DVarSet
delBindersFV bs fvs = foldr delBinderFV fvs bs
delBinderFV :: Var -> DVarSet -> DVarSet
-- This way round, so we can do it multiple times using foldr
-- (b `delBinderFV` s)
-- * removes the binder b from the free variable set s,
-- * AND *adds* to s the free variables of b's type
--
-- This is really important for some lambdas:
-- In (\x::a -> x) the only mention of "a" is in the binder.
--
-- Also in
-- let x::a = b in ...
-- we should really note that "a" is free in this expression.
-- It'll be pinned inside the /\a by the binding for b, but
-- it seems cleaner to make sure that a is in the free-var set
-- when it is mentioned.
--
-- This also shows up in recursive bindings. Consider:
-- /\a -> letrec x::a = x in E
-- Now, there are no explicit free type variables in the RHS of x,
-- but nevertheless "a" is free in its definition. So we add in
-- the free tyvars of the types of the binders, and include these in the
-- free vars of the group, attached to the top level of each RHS.
--
-- This actually happened in the defn of errorIO in IOBase.hs:
-- errorIO (ST io) = case (errorIO# io) of
-- _ -> bottom
-- where
-- bottom = bottom -- Never evaluated
delBinderFV b s = (s `delDVarSet` b) `unionFVs` dVarTypeTyCoVars b
-- Include coercion variables too!
varTypeTyCoVars :: Var -> TyCoVarSet
-- Find the type/kind variables free in the type of the id/tyvar
varTypeTyCoVars var = fvVarSet $ varTypeTyCoFVs var
dVarTypeTyCoVars :: Var -> DTyCoVarSet
-- Find the type/kind/coercion variables free in the type of the id/tyvar
dVarTypeTyCoVars var = fvDVarSet $ varTypeTyCoFVs var
varTypeTyCoFVs :: Var -> FV
varTypeTyCoFVs var = tyCoFVsOfType (varType var)
idFreeVars :: Id -> VarSet
idFreeVars id = ASSERT( isId id) fvVarSet $ idFVs id
dIdFreeVars :: Id -> DVarSet
dIdFreeVars id = fvDVarSet $ idFVs id
idFVs :: Id -> FV
-- Type variables, rule variables, and inline variables
idFVs id = ASSERT( isId id)
varTypeTyCoFVs id `unionFV`
bndrRuleAndUnfoldingFVs id
bndrRuleAndUnfoldingVarsDSet :: Id -> DVarSet
bndrRuleAndUnfoldingVarsDSet id = fvDVarSet $ bndrRuleAndUnfoldingFVs id
bndrRuleAndUnfoldingFVs :: Id -> FV
bndrRuleAndUnfoldingFVs id
| isId id = idRuleFVs id `unionFV` idUnfoldingFVs id
| otherwise = emptyFV
idRuleVars ::Id -> VarSet -- Does *not* include CoreUnfolding vars
idRuleVars id = fvVarSet $ idRuleFVs id
idRuleFVs :: Id -> FV
idRuleFVs id = ASSERT( isId id)
FV.mkFVs (dVarSetElems $ ruleInfoFreeVars (idSpecialisation id))
idUnfoldingVars :: Id -> VarSet
-- Produce free vars for an unfolding, but NOT for an ordinary
-- (non-inline) unfolding, since it is a dup of the rhs
-- and we'll get exponential behaviour if we look at both unf and rhs!
-- But do look at the *real* unfolding, even for loop breakers, else
-- we might get out-of-scope variables
idUnfoldingVars id = fvVarSet $ idUnfoldingFVs id
idUnfoldingFVs :: Id -> FV
idUnfoldingFVs id = stableUnfoldingFVs (realIdUnfolding id) `orElse` emptyFV
stableUnfoldingVars :: Unfolding -> Maybe VarSet
stableUnfoldingVars unf = fvVarSet `fmap` stableUnfoldingFVs unf
stableUnfoldingFVs :: Unfolding -> Maybe FV
stableUnfoldingFVs unf
= case unf of
CoreUnfolding { uf_tmpl = rhs, uf_src = src }
| isStableSource src
-> Just (filterFV isLocalVar $ expr_fvs rhs)
DFunUnfolding { df_bndrs = bndrs, df_args = args }
-> Just (filterFV isLocalVar $ FV.delFVs (mkVarSet bndrs) $ exprs_fvs args)
-- DFuns are top level, so no fvs from types of bndrs
_other -> Nothing
{-
************************************************************************
* *
\subsection{Free variables (and types)}
* *
************************************************************************
-}
freeVarsBind :: CoreBind
-> DVarSet -- Free vars of scope of binding
-> (CoreBindWithFVs, DVarSet) -- Return free vars of binding + scope
freeVarsBind (NonRec binder rhs) body_fvs
= ( AnnNonRec binder rhs2
, freeVarsOf rhs2 `unionFVs` body_fvs2
`unionFVs` bndrRuleAndUnfoldingVarsDSet binder )
where
rhs2 = freeVars rhs
body_fvs2 = binder `delBinderFV` body_fvs
freeVarsBind (Rec binds) body_fvs
= ( AnnRec (binders `zip` rhss2)
, delBindersFV binders all_fvs )
where
(binders, rhss) = unzip binds
rhss2 = map freeVars rhss
rhs_body_fvs = foldr (unionFVs . freeVarsOf) body_fvs rhss2
binders_fvs = fvDVarSet $ mapUnionFV bndrRuleAndUnfoldingFVs binders
all_fvs = rhs_body_fvs `unionFVs` binders_fvs
-- The "delBinderFV" happens after adding the idSpecVars,
-- since the latter may add some of the binders as fvs
freeVars :: CoreExpr -> CoreExprWithFVs
-- ^ Annotate a 'CoreExpr' with its (non-global) free type and value variables at every tree node
freeVars = go
where
go :: CoreExpr -> CoreExprWithFVs
go (Var v)
| isLocalVar v = (aFreeVar v `unionFVs` ty_fvs, AnnVar v)
| otherwise = (emptyDVarSet, AnnVar v)
where
ty_fvs = dVarTypeTyCoVars v -- Do we need this?
go (Lit lit) = (emptyDVarSet, AnnLit lit)
go (Lam b body)
= ( b_fvs `unionFVs` (b `delBinderFV` body_fvs)
, AnnLam b body' )
where
body'@(body_fvs, _) = go body
b_ty = idType b
b_fvs = tyCoVarsOfTypeDSet b_ty
go (App fun arg)
= ( freeVarsOf fun' `unionFVs` freeVarsOf arg'
, AnnApp fun' arg' )
where
fun' = go fun
arg' = go arg
go (Case scrut bndr ty alts)
= ( (bndr `delBinderFV` alts_fvs)
`unionFVs` freeVarsOf scrut2
`unionFVs` tyCoVarsOfTypeDSet ty
-- don't need to look at (idType bndr)
-- b/c that's redundant with scrut
, AnnCase scrut2 bndr ty alts2 )
where
scrut2 = go scrut
(alts_fvs_s, alts2) = mapAndUnzip fv_alt alts
alts_fvs = unionFVss alts_fvs_s
fv_alt (con,args,rhs) = (delBindersFV args (freeVarsOf rhs2),
(con, args, rhs2))
where
rhs2 = go rhs
go (Let bind body)
= (bind_fvs, AnnLet bind2 body2)
where
(bind2, bind_fvs) = freeVarsBind bind (freeVarsOf body2)
body2 = go body
go (Cast expr co)
= ( freeVarsOf expr2 `unionFVs` cfvs
, AnnCast expr2 (cfvs, co) )
where
expr2 = go expr
cfvs = tyCoVarsOfCoDSet co
go (Tick tickish expr)
= ( tickishFVs tickish `unionFVs` freeVarsOf expr2
, AnnTick tickish expr2 )
where
expr2 = go expr
tickishFVs (Breakpoint _ ids) = mkDVarSet ids
tickishFVs _ = emptyDVarSet
go (Type ty) = (tyCoVarsOfTypeDSet ty, AnnType ty)
go (Coercion co) = (tyCoVarsOfCoDSet co, AnnCoercion co)
| ezyang/ghc | compiler/coreSyn/CoreFVs.hs | bsd-3-clause | 30,461 | 0 | 14 | 7,640 | 5,449 | 2,933 | 2,516 | 408 | 11 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Pickle.Template
( myBlogPost
, myPage
, myIndexPage
, assemble
) where
import qualified Data.Text.Lazy as T
import Prelude hiding (head, id, div)
import Data.Monoid
import Data.Maybe
import Text.Blaze.Html5 ((!))
import Text.Blaze.Html5
import Text.Blaze.Html5.Attributes hiding (title, style, form)
import qualified Text.Blaze.Html5.Attributes as A
-- import qualified Text.Blaze.Html.Renderer.Text as B (renderHtml)
import Pickle.Types
import Pickle.Pandoc
--------------------------------------------------------------------------------
attrs = mconcat
cssImport link = string ("@import " <> show link <> ";")
script0 = script ""
maybeRender f = fromMaybe mempty . fmap f
nbsp = preEscapedString " "
mathJax = "MathJax.Hub.Config({ tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]} });"
googAnalytics = "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','//www.google-analytics.com/analytics.js','ga');ga('create', 'UA-22479172-1', 'auto');ga('send', 'pageview');"
--------------------------------------------------------------------------------
myHead :: Html
myHead = head $ do
title "my page title"
link ! attrs [rel "icon", href "/favicon.ico", type_ "image/x-icon"]
meta ! attrs [name "keywords", content "Matt Chan, Matthew Chan"]
meta ! attrs [name "author" , content "Matt Chan"]
meta ! attrs [name "viewport", content "width=device-width, initial-scale=1.0"]
meta ! attrs [httpEquiv "content-type" , content "text/html; charset=utf-8"]
meta ! attrs [httpEquiv "content-language", content "en-us"]
meta ! attrs [httpEquiv "X-UA-Compatible" , content "IE=edge,chrome=1"]
style ! attrs [type_ "text/css", media "screen", A.title "matt"]
$ foldMap cssImport
[ "//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"
, "/assets/matt.css"
, "/assets/syntax.css"
, "/assets/toc.css"
]
script0 ! src "//code.jquery.com/jquery-latest.min.js"
script0 ! src "//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"
script0 ! src "https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"
script0 ! src "/assets/matt.js"
script ! type_ "text/x-mathjax-config" $ preEscapedString mathJax
script $ preEscapedString googAnalytics
myHeader h sub = do
header $ do
h1 ! class_ "name pull-left" $ do
h <> nbsp <> sub
-- string h <> small (string sub)
div ! A.style "clear:both" $ ""
myBlogHeader = do
header $ do
h1 ! class_ "name pull-left" $ do
string "Matt Chan" <> nbsp <> small (a ! href "/blog" $ string "Blog")
h1 ! class_ "pull-right" $ do
form ! attrs [ id "search"
, class_ "navbar-search"
, method "get"
, action "http://google.com/search"
] $
(do { p (do { input ! attrs [ type_ "hidden", name "q", value "site:themattchan.com"]
; input ! attrs [ type_ "text", class_ "form-control", name "q", placeholder "search"]
})
})
div ! A.style "clear:both" $ ""
myBody0 content = body $ do
div ! id "wrap" $ do
div ! class_ "container" $ do
content
-- | Render the whole html file, including all the extra crap
assemble pg = docTypeHtml (myHead >> body (myBody0 pg))
--------------------------------------------------------------------------------
myIndexPage :: Html -> Html -> Html -> Html
myIndexPage h sub content = do
myHeader h sub
div ! class_ "content" $ do
content
myPage :: Html -> Html -> Html -> Html
myPage h sub content = do
myHeader h sub
div ! class_ "content" $ do
content
br; a ! href "../" $ preEscapedString "← back";
br;br;br
myBlogPost :: Post -> Html
myBlogPost post@Post{..} =
let metaHtml k f = maybeRender (f . pandocUnmeta)
$ lookupMeta k (pandocMeta postContent)
in do
myBlogHeader
div ! class_ "content" $ do
div ! class_ "post" $ do
metaHtml "title" (h1.string)
metaHtml "subtitle" (\s -> i (string s) <> br <> br)
p ! A.style "color:gray;" $ do
metaHtml "date" string
metaHtml "updated" (\s -> string $ "(updated " <> s <> ")")
renderPandoc postContent
-- TODO footer
| themattchan/pickle | src/Pickle/Template.hs | bsd-3-clause | 4,513 | 0 | 24 | 908 | 1,171 | 573 | 598 | 95 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedTuples #-}
module Main where
import Data.Bits
import Data.List
import Data.Time
import GHC.Prim
import GHC.Word
data BW1 = BW1 {-# UNPACK #-}!Word {-# UNPACK #-}!Word
data BW2 = BW2 {-# UNPACK #-}!BW1 {-# UNPACK #-}!BW1
overAddWord !(W# x#) !(W# y#) = (W# z#, W# c#)
where (# c#, z# #) = plusWord2# x# y#
overAddBW1 (BW1 x1 y1) (BW1 x2 y2) = (BW1 s $ t + cs, c)
where
(s, cs) = overAddWord x1 x2
(t0, ct0) = overAddWord y1 y2
(t, ct) = overAddWord t0 cs
c = ct + ct0
addBW1 x y = fst $ overAddBW1 x y
overAddBW2 (BW2 x1 y1) (BW2 x2 y2) = (BW2 s t', c)
where
(s, cs) = overAddBW1 x1 x2
(t, ct) = overAddBW1 y1 y2
(t', ct') = overAddBW1 t $ BW1 cs 0
c = ct .|. ct'
addBW2 x y = z
where (z, _) = overAddBW2 x y
main = do
let
bw1 i = BW1 i i
bw2 i = BW2 (bw1 i) (bw1 i)
a1 = foldl' addBW1 (bw1 0) $ replicate 1000000 (bw1 1)
a2 = foldl' addBW2 (bw2 0) $ replicate 1000000 (bw2 1)
a3 = foldl' (+) 0 $ replicate 1000000 1
t0 <- getCurrentTime
a1 `seq` return ()
t1 <- getCurrentTime
a2 `seq` return ()
t2 <- getCurrentTime
a3 `seq` return ()
t3 <- getCurrentTime
putStrLn ""
putStrLn $ "BW1: " ++ show (diffUTCTime t1 t0)
putStrLn $ "BW2: " ++ show (diffUTCTime t2 t1)
putStrLn $ "Integer: " ++ show (diffUTCTime t3 t2)
| ryanreich/bigint | test/BadPerformanceExample.hs | bsd-3-clause | 1,397 | 0 | 13 | 371 | 647 | 325 | 322 | 44 | 1 |
module Graphics.HsCharts.Helpers where
import Numeric
-- | Shows a Float with the least number of decimals possible, with a maximum
-- of d decimals.
--
-- >>> showFFloat' 3 2.0000001
-- "2"
-- >>> showFFloat' 3 2.1234567
-- "2.123"
-- >>> showFFloat' 3 10.000001
-- "10"
showFFloat' :: Int -> Float -> String
showFFloat' d f = wholeNumbers ++ removeTrailingZeros (take (d + 1) decimals)
where
(wholeNumbers, decimals) = break ('.' ==) $ showFFloat Nothing f ""
removeTrailingZeros [] = []
removeTrailingZeros xs | last xs == '0' = removeTrailingZeros (init xs)
| last xs == '.' = removeTrailingZeros (init xs)
| otherwise = xs
-----------------------------------------------------------------------------
-- | Gets a given quantile from a list of values.
--
-- >>> quantile 0.25 [1,2,3,4,5]
-- 2.0
-- >>> quantile 0.75 [1,2,3,4,5]
-- 4.0
quantile :: (RealFrac a) => a -> [a] -> a
quantile q xs | isWhole l = 0.5 * ((xs !! (round l - 1)) + xs !! round l)
| otherwise = xs !! (ceiling l - 1)
where numXs = length xs
l = fromIntegral numXs * q
isWhole x = x == fromInteger (round x)
-- | Gets the median from a list of values.
median :: (RealFrac a) => [a] -> a
median = quantile 0.5
-- | Gets three values dividing a list into quartiles. (Q1, median, Q3).
--
-- >>> quartiles [1,2,3,4]
-- (1.5,2.5,3.5)
quartiles :: (RealFrac a) => [a] -> (a, a, a)
quartiles xs = (quantile 0.25 xs, median xs, quantile 0.75 xs)
-- | Gets the five-number summary from a list. (min, Q1, median, Q3, max).
--
-- >>> fiveNum [1,2,3,4]
-- (1.0,1.5,2.5,3.5,4.0)
fiveNum :: (RealFrac a) => [a] -> (a, a, a, a, a)
fiveNum xs = (minimum xs, q1, m, q3, maximum xs)
where (q1, m, q3) = quartiles xs
| maciej-wichrowski/HsCharts | source/Graphics/HsCharts/Helpers.hs | bsd-3-clause | 1,854 | 0 | 14 | 486 | 507 | 276 | 231 | 22 | 2 |
{-# LANGUAGE CPP, NondecreasingIndentation, TupleSections #-}
{-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}
-----------------------------------------------------------------------------
--
-- GHC Driver program
--
-- (c) The University of Glasgow 2005
--
-----------------------------------------------------------------------------
module Main (main) where
-- The official GHC API
import qualified GHC
import GHC ( -- DynFlags(..), HscTarget(..),
-- GhcMode(..), GhcLink(..),
Ghc, GhcMonad(..),
LoadHowMuch(..) )
import CmdLineParser
-- Implementations of the various modes (--show-iface, mkdependHS. etc.)
import LoadIface ( showIface )
import HscMain ( newHscEnv )
import DriverPipeline ( oneShot, compileFile, mergeRequirement )
import DriverMkDepend ( doMkDependHS )
#ifdef GHCI
import InteractiveUI ( interactiveUI, ghciWelcomeMsg, defaultGhciSettings )
#endif
-- Various other random stuff that we need
import Config
import Constants
import HscTypes
import Packages ( pprPackages, pprPackagesSimple, pprModuleMap )
import DriverPhases
import BasicTypes ( failed )
import StaticFlags
import DynFlags
import ErrUtils
import FastString
import Outputable
import SrcLoc
import Util
import Panic
import MonadUtils ( liftIO )
-- Imports for --abi-hash
import LoadIface ( loadUserInterface )
import Module ( mkModuleName )
import Finder ( findImportedModule, cannotFindInterface )
import TcRnMonad ( initIfaceCheck )
import Binary ( openBinMem, put_, fingerprintBinMem )
-- Standard Haskell libraries
import System.IO
import System.Environment
import System.Exit
import System.FilePath
import Control.Monad
import Data.Char
import Data.List
import Data.Maybe
-----------------------------------------------------------------------------
-- ToDo:
-- time commands when run with -v
-- user ways
-- Win32 support: proper signal handling
-- reading the package configuration file is too slow
-- -K<size>
-----------------------------------------------------------------------------
-- GHC's command-line interface
main :: IO ()
main = do
initGCStatistics -- See Note [-Bsymbolic and hooks]
hSetBuffering stdout LineBuffering
hSetBuffering stderr LineBuffering
-- Handle GHC-specific character encoding flags, allowing us to control how
-- GHC produces output regardless of OS.
env <- getEnvironment
case lookup "GHC_CHARENC" env of
Just "UTF-8" -> do
hSetEncoding stdout utf8
hSetEncoding stderr utf8
_ -> do
-- Avoid GHC erroring out when trying to display unhandled characters
hSetTranslit stdout
hSetTranslit stderr
GHC.defaultErrorHandler defaultFatalMessager defaultFlushOut $ do
-- 1. extract the -B flag from the args
argv0 <- getArgs
let (minusB_args, argv1) = partition ("-B" `isPrefixOf`) argv0
mbMinusB | null minusB_args = Nothing
| otherwise = Just (drop 2 (last minusB_args))
let argv1' = map (mkGeneralLocated "on the commandline") argv1
(argv2, staticFlagWarnings) <- parseStaticFlags argv1'
-- 2. Parse the "mode" flags (--make, --interactive etc.)
(mode, argv3, modeFlagWarnings) <- parseModeFlags argv2
let flagWarnings = staticFlagWarnings ++ modeFlagWarnings
-- If all we want to do is something like showing the version number
-- then do it now, before we start a GHC session etc. This makes
-- getting basic information much more resilient.
-- In particular, if we wait until later before giving the version
-- number then bootstrapping gets confused, as it tries to find out
-- what version of GHC it's using before package.conf exists, so
-- starting the session fails.
case mode of
Left preStartupMode ->
do case preStartupMode of
ShowSupportedExtensions -> showSupportedExtensions
ShowVersion -> showVersion
ShowNumVersion -> putStrLn cProjectVersion
ShowOptions isInteractive -> showOptions isInteractive
Right postStartupMode ->
-- start our GHC session
GHC.runGhc mbMinusB $ do
dflags <- GHC.getSessionDynFlags
case postStartupMode of
Left preLoadMode ->
liftIO $ do
case preLoadMode of
ShowInfo -> showInfo dflags
ShowGhcUsage -> showGhcUsage dflags
ShowGhciUsage -> showGhciUsage dflags
PrintWithDynFlags f -> putStrLn (f dflags)
Right postLoadMode ->
main' postLoadMode dflags argv3 flagWarnings
main' :: PostLoadMode -> DynFlags -> [Located String] -> [Located String]
-> Ghc ()
main' postLoadMode dflags0 args flagWarnings = do
-- set the default GhcMode, HscTarget and GhcLink. The HscTarget
-- can be further adjusted on a module by module basis, using only
-- the -fvia-C and -fasm flags. If the default HscTarget is not
-- HscC or HscAsm, -fvia-C and -fasm have no effect.
let dflt_target = hscTarget dflags0
(mode, lang, link)
= case postLoadMode of
DoInteractive -> (CompManager, HscInterpreted, LinkInMemory)
DoEval _ -> (CompManager, HscInterpreted, LinkInMemory)
DoMake -> (CompManager, dflt_target, LinkBinary)
DoMkDependHS -> (MkDepend, dflt_target, LinkBinary)
DoAbiHash -> (OneShot, dflt_target, LinkBinary)
DoMergeRequirements -> (OneShot, dflt_target, LinkBinary)
_ -> (OneShot, dflt_target, LinkBinary)
let dflags1 = case lang of
HscInterpreted ->
let platform = targetPlatform dflags0
dflags0a = updateWays $ dflags0 { ways = interpWays }
dflags0b = foldl gopt_set dflags0a
$ concatMap (wayGeneralFlags platform)
interpWays
dflags0c = foldl gopt_unset dflags0b
$ concatMap (wayUnsetGeneralFlags platform)
interpWays
in dflags0c
_ ->
dflags0
dflags2 = dflags1{ ghcMode = mode,
hscTarget = lang,
ghcLink = link,
verbosity = case postLoadMode of
DoEval _ -> 0
_other -> 1
}
-- turn on -fimplicit-import-qualified for GHCi now, so that it
-- can be overriden from the command-line
-- XXX: this should really be in the interactive DynFlags, but
-- we don't set that until later in interactiveUI
dflags3 | DoInteractive <- postLoadMode = imp_qual_enabled
| DoEval _ <- postLoadMode = imp_qual_enabled
| otherwise = dflags2
where imp_qual_enabled = dflags2 `gopt_set` Opt_ImplicitImportQualified
-- The rest of the arguments are "dynamic"
-- Leftover ones are presumably files
(dflags4, fileish_args, dynamicFlagWarnings) <- GHC.parseDynamicFlags dflags3 args
GHC.prettyPrintGhcErrors dflags4 $ do
let flagWarnings' = flagWarnings ++ dynamicFlagWarnings
handleSourceError (\e -> do
GHC.printException e
liftIO $ exitWith (ExitFailure 1)) $ do
liftIO $ handleFlagWarnings dflags4 flagWarnings'
-- make sure we clean up after ourselves
GHC.defaultCleanupHandler dflags4 $ do
liftIO $ showBanner postLoadMode dflags4
let
-- To simplify the handling of filepaths, we normalise all filepaths right
-- away - e.g., for win32 platforms, backslashes are converted
-- into forward slashes.
normal_fileish_paths = map (normalise . unLoc) fileish_args
(srcs, objs) = partition_args normal_fileish_paths [] []
dflags5 = dflags4 { ldInputs = map (FileOption "") objs
++ ldInputs dflags4 }
-- we've finished manipulating the DynFlags, update the session
_ <- GHC.setSessionDynFlags dflags5
dflags6 <- GHC.getSessionDynFlags
hsc_env <- GHC.getSession
---------------- Display configuration -----------
case verbosity dflags6 of
v | v == 4 -> liftIO $ dumpPackagesSimple dflags6
| v >= 5 -> liftIO $ dumpPackages dflags6
| otherwise -> return ()
when (verbosity dflags6 >= 3) $ do
liftIO $ hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
when (dopt Opt_D_dump_mod_map dflags6) . liftIO $
printInfoForUser (dflags6 { pprCols = 200 })
(pkgQual dflags6) (pprModuleMap dflags6)
---------------- Final sanity checking -----------
liftIO $ checkOptions postLoadMode dflags6 srcs objs
---------------- Do the business -----------
handleSourceError (\e -> do
GHC.printException e
liftIO $ exitWith (ExitFailure 1)) $ do
case postLoadMode of
ShowInterface f -> liftIO $ doShowIface dflags6 f
DoMake -> doMake srcs
DoMkDependHS -> doMkDependHS (map fst srcs)
StopBefore p -> liftIO (oneShot hsc_env p srcs)
DoInteractive -> ghciUI srcs Nothing
DoEval exprs -> ghciUI srcs $ Just $ reverse exprs
DoAbiHash -> abiHash (map fst srcs)
DoMergeRequirements -> doMergeRequirements (map fst srcs)
ShowPackages -> liftIO $ showPackages dflags6
liftIO $ dumpFinalStats dflags6
ghciUI :: [(FilePath, Maybe Phase)] -> Maybe [String] -> Ghc ()
#ifndef GHCI
ghciUI _ _ = throwGhcException (CmdLineError "not built for interactive use")
#else
ghciUI = interactiveUI defaultGhciSettings
#endif
-- -----------------------------------------------------------------------------
-- Splitting arguments into source files and object files. This is where we
-- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
-- file indicating the phase specified by the -x option in force, if any.
partition_args :: [String] -> [(String, Maybe Phase)] -> [String]
-> ([(String, Maybe Phase)], [String])
partition_args [] srcs objs = (reverse srcs, reverse objs)
partition_args ("-x":suff:args) srcs objs
| "none" <- suff = partition_args args srcs objs
| StopLn <- phase = partition_args args srcs (slurp ++ objs)
| otherwise = partition_args rest (these_srcs ++ srcs) objs
where phase = startPhase suff
(slurp,rest) = break (== "-x") args
these_srcs = zip slurp (repeat (Just phase))
partition_args (arg:args) srcs objs
| looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
| otherwise = partition_args args srcs (arg:objs)
{-
We split out the object files (.o, .dll) and add them
to ldInputs for use by the linker.
The following things should be considered compilation manager inputs:
- haskell source files (strings ending in .hs, .lhs or other
haskellish extension),
- module names (not forgetting hierarchical module names),
- things beginning with '-' are flags that were not recognised by
the flag parser, and we want them to generate errors later in
checkOptions, so we class them as source files (#5921)
- and finally we consider everything not containing a '.' to be
a comp manager input, as shorthand for a .hs or .lhs filename.
Everything else is considered to be a linker object, and passed
straight through to the linker.
-}
looks_like_an_input :: String -> Bool
looks_like_an_input m = isSourceFilename m
|| looksLikeModuleName m
|| "-" `isPrefixOf` m
|| '.' `notElem` m
-- -----------------------------------------------------------------------------
-- Option sanity checks
-- | Ensure sanity of options.
--
-- Throws 'UsageError' or 'CmdLineError' if not.
checkOptions :: PostLoadMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
-- Final sanity checking before kicking off a compilation (pipeline).
checkOptions mode dflags srcs objs = do
-- Complain about any unknown flags
let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
when (notNull (filter wayRTSOnly (ways dflags))
&& isInterpretiveMode mode) $
hPutStrLn stderr ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
-- -prof and --interactive are not a good combination
when ((filter (not . wayRTSOnly) (ways dflags) /= interpWays)
&& isInterpretiveMode mode) $
do throwGhcException (UsageError
"--interactive can't be used with -prof or -static.")
-- -ohi sanity check
if (isJust (outputHi dflags) &&
(isCompManagerMode mode || srcs `lengthExceeds` 1))
then throwGhcException (UsageError "-ohi can only be used when compiling a single source file")
else do
-- -o sanity checking
if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
&& not (isLinkMode mode))
then throwGhcException (UsageError "can't apply -o to multiple source files")
else do
let not_linking = not (isLinkMode mode) || isNoLink (ghcLink dflags)
when (not_linking && not (null objs)) $
hPutStrLn stderr ("Warning: the following files would be used as linker inputs, but linking is not being done: " ++ unwords objs)
-- Check that there are some input files
-- (except in the interactive case)
if null srcs && (null objs || not_linking) && needsInputsMode mode
then throwGhcException (UsageError "no input files")
else do
case mode of
StopBefore HCc | hscTarget dflags /= HscC
-> throwGhcException $ UsageError $
"the option -C is only available with an unregisterised GHC"
_ -> return ()
-- Verify that output files point somewhere sensible.
verifyOutputFiles dflags
-- Compiler output options
-- Called to verify that the output files point somewhere valid.
--
-- The assumption is that the directory portion of these output
-- options will have to exist by the time 'verifyOutputFiles'
-- is invoked.
--
-- We create the directories for -odir, -hidir, -outputdir etc. ourselves if
-- they don't exist, so don't check for those here (#2278).
verifyOutputFiles :: DynFlags -> IO ()
verifyOutputFiles dflags = do
let ofile = outputFile dflags
when (isJust ofile) $ do
let fn = fromJust ofile
flg <- doesDirNameExist fn
when (not flg) (nonExistentDir "-o" fn)
let ohi = outputHi dflags
when (isJust ohi) $ do
let hi = fromJust ohi
flg <- doesDirNameExist hi
when (not flg) (nonExistentDir "-ohi" hi)
where
nonExistentDir flg dir =
throwGhcException (CmdLineError ("error: directory portion of " ++
show dir ++ " does not exist (used with " ++
show flg ++ " option.)"))
-----------------------------------------------------------------------------
-- GHC modes of operation
type Mode = Either PreStartupMode PostStartupMode
type PostStartupMode = Either PreLoadMode PostLoadMode
data PreStartupMode
= ShowVersion -- ghc -V/--version
| ShowNumVersion -- ghc --numeric-version
| ShowSupportedExtensions -- ghc --supported-extensions
| ShowOptions Bool {- isInteractive -} -- ghc --show-options
showVersionMode, showNumVersionMode, showSupportedExtensionsMode, showOptionsMode :: Mode
showVersionMode = mkPreStartupMode ShowVersion
showNumVersionMode = mkPreStartupMode ShowNumVersion
showSupportedExtensionsMode = mkPreStartupMode ShowSupportedExtensions
showOptionsMode = mkPreStartupMode (ShowOptions False)
mkPreStartupMode :: PreStartupMode -> Mode
mkPreStartupMode = Left
isShowVersionMode :: Mode -> Bool
isShowVersionMode (Left ShowVersion) = True
isShowVersionMode _ = False
isShowNumVersionMode :: Mode -> Bool
isShowNumVersionMode (Left ShowNumVersion) = True
isShowNumVersionMode _ = False
data PreLoadMode
= ShowGhcUsage -- ghc -?
| ShowGhciUsage -- ghci -?
| ShowInfo -- ghc --info
| PrintWithDynFlags (DynFlags -> String) -- ghc --print-foo
showGhcUsageMode, showGhciUsageMode, showInfoMode :: Mode
showGhcUsageMode = mkPreLoadMode ShowGhcUsage
showGhciUsageMode = mkPreLoadMode ShowGhciUsage
showInfoMode = mkPreLoadMode ShowInfo
printSetting :: String -> Mode
printSetting k = mkPreLoadMode (PrintWithDynFlags f)
where f dflags = fromMaybe (panic ("Setting not found: " ++ show k))
$ lookup k (compilerInfo dflags)
mkPreLoadMode :: PreLoadMode -> Mode
mkPreLoadMode = Right . Left
isShowGhcUsageMode :: Mode -> Bool
isShowGhcUsageMode (Right (Left ShowGhcUsage)) = True
isShowGhcUsageMode _ = False
isShowGhciUsageMode :: Mode -> Bool
isShowGhciUsageMode (Right (Left ShowGhciUsage)) = True
isShowGhciUsageMode _ = False
data PostLoadMode
= ShowInterface FilePath -- ghc --show-iface
| DoMkDependHS -- ghc -M
| StopBefore Phase -- ghc -E | -C | -S
-- StopBefore StopLn is the default
| DoMake -- ghc --make
| DoInteractive -- ghc --interactive
| DoEval [String] -- ghc -e foo -e bar => DoEval ["bar", "foo"]
| DoAbiHash -- ghc --abi-hash
| ShowPackages -- ghc --show-packages
| DoMergeRequirements -- ghc --merge-requirements
doMkDependHSMode, doMakeMode, doInteractiveMode,
doAbiHashMode, showPackagesMode, doMergeRequirementsMode :: Mode
doMkDependHSMode = mkPostLoadMode DoMkDependHS
doMakeMode = mkPostLoadMode DoMake
doInteractiveMode = mkPostLoadMode DoInteractive
doAbiHashMode = mkPostLoadMode DoAbiHash
showPackagesMode = mkPostLoadMode ShowPackages
doMergeRequirementsMode = mkPostLoadMode DoMergeRequirements
showInterfaceMode :: FilePath -> Mode
showInterfaceMode fp = mkPostLoadMode (ShowInterface fp)
stopBeforeMode :: Phase -> Mode
stopBeforeMode phase = mkPostLoadMode (StopBefore phase)
doEvalMode :: String -> Mode
doEvalMode str = mkPostLoadMode (DoEval [str])
mkPostLoadMode :: PostLoadMode -> Mode
mkPostLoadMode = Right . Right
isDoInteractiveMode :: Mode -> Bool
isDoInteractiveMode (Right (Right DoInteractive)) = True
isDoInteractiveMode _ = False
isStopLnMode :: Mode -> Bool
isStopLnMode (Right (Right (StopBefore StopLn))) = True
isStopLnMode _ = False
isDoMakeMode :: Mode -> Bool
isDoMakeMode (Right (Right DoMake)) = True
isDoMakeMode _ = False
isDoEvalMode :: Mode -> Bool
isDoEvalMode (Right (Right (DoEval _))) = True
isDoEvalMode _ = False
#ifdef GHCI
isInteractiveMode :: PostLoadMode -> Bool
isInteractiveMode DoInteractive = True
isInteractiveMode _ = False
#endif
-- isInterpretiveMode: byte-code compiler involved
isInterpretiveMode :: PostLoadMode -> Bool
isInterpretiveMode DoInteractive = True
isInterpretiveMode (DoEval _) = True
isInterpretiveMode _ = False
needsInputsMode :: PostLoadMode -> Bool
needsInputsMode DoMkDependHS = True
needsInputsMode (StopBefore _) = True
needsInputsMode DoMake = True
needsInputsMode _ = False
-- True if we are going to attempt to link in this mode.
-- (we might not actually link, depending on the GhcLink flag)
isLinkMode :: PostLoadMode -> Bool
isLinkMode (StopBefore StopLn) = True
isLinkMode DoMake = True
isLinkMode DoInteractive = True
isLinkMode (DoEval _) = True
isLinkMode _ = False
isCompManagerMode :: PostLoadMode -> Bool
isCompManagerMode DoMake = True
isCompManagerMode DoInteractive = True
isCompManagerMode (DoEval _) = True
isCompManagerMode _ = False
-- -----------------------------------------------------------------------------
-- Parsing the mode flag
parseModeFlags :: [Located String]
-> IO (Mode,
[Located String],
[Located String])
parseModeFlags args = do
let ((leftover, errs1, warns), (mModeFlag, errs2, flags')) =
runCmdLine (processArgs mode_flags args)
(Nothing, [], [])
mode = case mModeFlag of
Nothing -> doMakeMode
Just (m, _) -> m
-- See Note [Handling errors when parsing commandline flags]
unless (null errs1 && null errs2) $ throwGhcException $ errorsToGhcException $
map (("on the commandline", )) $ map unLoc errs1 ++ errs2
return (mode, flags' ++ leftover, warns)
type ModeM = CmdLineP (Maybe (Mode, String), [String], [Located String])
-- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
-- so we collect the new ones and return them.
mode_flags :: [Flag ModeM]
mode_flags =
[ ------- help / version ----------------------------------------------
defFlag "?" (PassFlag (setMode showGhcUsageMode))
, defFlag "-help" (PassFlag (setMode showGhcUsageMode))
, defFlag "V" (PassFlag (setMode showVersionMode))
, defFlag "-version" (PassFlag (setMode showVersionMode))
, defFlag "-numeric-version" (PassFlag (setMode showNumVersionMode))
, defFlag "-info" (PassFlag (setMode showInfoMode))
, defFlag "-show-options" (PassFlag (setMode showOptionsMode))
, defFlag "-supported-languages" (PassFlag (setMode showSupportedExtensionsMode))
, defFlag "-supported-extensions" (PassFlag (setMode showSupportedExtensionsMode))
, defFlag "-show-packages" (PassFlag (setMode showPackagesMode))
] ++
[ defFlag k' (PassFlag (setMode (printSetting k)))
| k <- ["Project version",
"Project Git commit id",
"Booter version",
"Stage",
"Build platform",
"Host platform",
"Target platform",
"Have interpreter",
"Object splitting supported",
"Have native code generator",
"Support SMP",
"Unregisterised",
"Tables next to code",
"RTS ways",
"Leading underscore",
"Debug on",
"LibDir",
"Global Package DB",
"C compiler flags",
"Gcc Linker flags",
"Ld Linker flags"],
let k' = "-print-" ++ map (replaceSpace . toLower) k
replaceSpace ' ' = '-'
replaceSpace c = c
] ++
------- interfaces ----------------------------------------------------
[ defFlag "-show-iface" (HasArg (\f -> setMode (showInterfaceMode f)
"--show-iface"))
------- primary modes ------------------------------------------------
, defFlag "c" (PassFlag (\f -> do setMode (stopBeforeMode StopLn) f
addFlag "-no-link" f))
, defFlag "M" (PassFlag (setMode doMkDependHSMode))
, defFlag "E" (PassFlag (setMode (stopBeforeMode anyHsc)))
, defFlag "C" (PassFlag (setMode (stopBeforeMode HCc)))
, defFlag "S" (PassFlag (setMode (stopBeforeMode (As False))))
, defFlag "-make" (PassFlag (setMode doMakeMode))
, defFlag "-merge-requirements" (PassFlag (setMode doMergeRequirementsMode))
, defFlag "-interactive" (PassFlag (setMode doInteractiveMode))
, defFlag "-abi-hash" (PassFlag (setMode doAbiHashMode))
, defFlag "e" (SepArg (\s -> setMode (doEvalMode s) "-e"))
]
setMode :: Mode -> String -> EwM ModeM ()
setMode newMode newFlag = liftEwM $ do
(mModeFlag, errs, flags') <- getCmdLineState
let (modeFlag', errs') =
case mModeFlag of
Nothing -> ((newMode, newFlag), errs)
Just (oldMode, oldFlag) ->
case (oldMode, newMode) of
-- -c/--make are allowed together, and mean --make -no-link
_ | isStopLnMode oldMode && isDoMakeMode newMode
|| isStopLnMode newMode && isDoMakeMode oldMode ->
((doMakeMode, "--make"), [])
-- If we have both --help and --interactive then we
-- want showGhciUsage
_ | isShowGhcUsageMode oldMode &&
isDoInteractiveMode newMode ->
((showGhciUsageMode, oldFlag), [])
| isShowGhcUsageMode newMode &&
isDoInteractiveMode oldMode ->
((showGhciUsageMode, newFlag), [])
-- If we have both -e and --interactive then -e always wins
_ | isDoEvalMode oldMode &&
isDoInteractiveMode newMode ->
((oldMode, oldFlag), [])
| isDoEvalMode newMode &&
isDoInteractiveMode oldMode ->
((newMode, newFlag), [])
-- Otherwise, --help/--version/--numeric-version always win
| isDominantFlag oldMode -> ((oldMode, oldFlag), [])
| isDominantFlag newMode -> ((newMode, newFlag), [])
-- We need to accumulate eval flags like "-e foo -e bar"
(Right (Right (DoEval esOld)),
Right (Right (DoEval [eNew]))) ->
((Right (Right (DoEval (eNew : esOld))), oldFlag),
errs)
-- Saying e.g. --interactive --interactive is OK
_ | oldFlag == newFlag -> ((oldMode, oldFlag), errs)
-- --interactive and --show-options are used together
(Right (Right DoInteractive), Left (ShowOptions _)) ->
((Left (ShowOptions True),
"--interactive --show-options"), errs)
(Left (ShowOptions _), (Right (Right DoInteractive))) ->
((Left (ShowOptions True),
"--show-options --interactive"), errs)
-- Otherwise, complain
_ -> let err = flagMismatchErr oldFlag newFlag
in ((oldMode, oldFlag), err : errs)
putCmdLineState (Just modeFlag', errs', flags')
where isDominantFlag f = isShowGhcUsageMode f ||
isShowGhciUsageMode f ||
isShowVersionMode f ||
isShowNumVersionMode f
flagMismatchErr :: String -> String -> String
flagMismatchErr oldFlag newFlag
= "cannot use `" ++ oldFlag ++ "' with `" ++ newFlag ++ "'"
addFlag :: String -> String -> EwM ModeM ()
addFlag s flag = liftEwM $ do
(m, e, flags') <- getCmdLineState
putCmdLineState (m, e, mkGeneralLocated loc s : flags')
where loc = "addFlag by " ++ flag ++ " on the commandline"
-- ----------------------------------------------------------------------------
-- Run --make mode
doMake :: [(String,Maybe Phase)] -> Ghc ()
doMake srcs = do
let (hs_srcs, non_hs_srcs) = partition haskellish srcs
haskellish (f,Nothing) =
looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
haskellish (_,Just phase) =
phase `notElem` [ As True, As False, Cc, Cobjc, Cobjcxx, CmmCpp, Cmm
, StopLn]
hsc_env <- GHC.getSession
-- if we have no haskell sources from which to do a dependency
-- analysis, then just do one-shot compilation and/or linking.
-- This means that "ghc Foo.o Bar.o -o baz" links the program as
-- we expect.
if (null hs_srcs)
then liftIO (oneShot hsc_env StopLn srcs)
else do
o_files <- mapM (\x -> liftIO $ compileFile hsc_env StopLn x)
non_hs_srcs
dflags <- GHC.getSessionDynFlags
let dflags' = dflags { ldInputs = map (FileOption "") o_files
++ ldInputs dflags }
_ <- GHC.setSessionDynFlags dflags'
targets <- mapM (uncurry GHC.guessTarget) hs_srcs
GHC.setTargets targets
ok_flag <- GHC.load LoadAllTargets
when (failed ok_flag) (liftIO $ exitWith (ExitFailure 1))
return ()
-- ----------------------------------------------------------------------------
-- Run --merge-requirements mode
doMergeRequirements :: [String] -> Ghc ()
doMergeRequirements srcs = mapM_ doMergeRequirement srcs
doMergeRequirement :: String -> Ghc ()
doMergeRequirement src = do
hsc_env <- getSession
liftIO $ mergeRequirement hsc_env (mkModuleName src)
-- ---------------------------------------------------------------------------
-- --show-iface mode
doShowIface :: DynFlags -> FilePath -> IO ()
doShowIface dflags file = do
hsc_env <- newHscEnv dflags
showIface hsc_env file
-- ---------------------------------------------------------------------------
-- Various banners and verbosity output.
showBanner :: PostLoadMode -> DynFlags -> IO ()
showBanner _postLoadMode dflags = do
let verb = verbosity dflags
#ifdef GHCI
-- Show the GHCi banner
when (isInteractiveMode _postLoadMode && verb >= 1) $ putStrLn ghciWelcomeMsg
#endif
-- Display details of the configuration in verbose mode
when (verb >= 2) $
do hPutStr stderr "Glasgow Haskell Compiler, Version "
hPutStr stderr cProjectVersion
hPutStr stderr ", stage "
hPutStr stderr cStage
hPutStr stderr " booted by GHC version "
hPutStrLn stderr cBooterVersion
-- We print out a Read-friendly string, but a prettier one than the
-- Show instance gives us
showInfo :: DynFlags -> IO ()
showInfo dflags = do
let sq x = " [" ++ x ++ "\n ]"
putStrLn $ sq $ intercalate "\n ," $ map show $ compilerInfo dflags
showSupportedExtensions :: IO ()
showSupportedExtensions = mapM_ putStrLn supportedLanguagesAndExtensions
showVersion :: IO ()
showVersion = putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
showOptions :: Bool -> IO ()
showOptions isInteractive = putStr (unlines availableOptions)
where
availableOptions = concat [
flagsForCompletion isInteractive,
map ('-':) (concat [
getFlagNames mode_flags
, (filterUnwantedStatic . getFlagNames $ flagsStatic)
, flagsStaticNames
])
]
getFlagNames opts = map flagName opts
-- this is a hack to get rid of two unwanted entries that get listed
-- as static flags. Hopefully this hack will disappear one day together
-- with static flags
filterUnwantedStatic = filter (`notElem`["f", "fno-"])
showGhcUsage :: DynFlags -> IO ()
showGhcUsage = showUsage False
showGhciUsage :: DynFlags -> IO ()
showGhciUsage = showUsage True
showUsage :: Bool -> DynFlags -> IO ()
showUsage ghci dflags = do
let usage_path = if ghci then ghciUsagePath dflags
else ghcUsagePath dflags
usage <- readFile usage_path
dump usage
where
dump "" = return ()
dump ('$':'$':s) = putStr progName >> dump s
dump (c:s) = putChar c >> dump s
dumpFinalStats :: DynFlags -> IO ()
dumpFinalStats dflags =
when (gopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
dumpFastStringStats :: DynFlags -> IO ()
dumpFastStringStats dflags = do
buckets <- getFastStringTable
let (entries, longest, has_z) = countFS 0 0 0 buckets
msg = text "FastString stats:" $$
nest 4 (vcat [text "size: " <+> int (length buckets),
text "entries: " <+> int entries,
text "longest chain: " <+> int longest,
text "has z-encoding: " <+> (has_z `pcntOf` entries)
])
-- we usually get more "has z-encoding" than "z-encoded", because
-- when we z-encode a string it might hash to the exact same string,
-- which will is not counted as "z-encoded". Only strings whose
-- Z-encoding is different from the original string are counted in
-- the "z-encoded" total.
putMsg dflags msg
where
x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
countFS :: Int -> Int -> Int -> [[FastString]] -> (Int, Int, Int)
countFS entries longest has_z [] = (entries, longest, has_z)
countFS entries longest has_z (b:bs) =
let
len = length b
longest' = max len longest
entries' = entries + len
has_zs = length (filter hasZEncoding b)
in
countFS entries' longest' (has_z + has_zs) bs
showPackages, dumpPackages, dumpPackagesSimple :: DynFlags -> IO ()
showPackages dflags = putStrLn (showSDoc dflags (pprPackages dflags))
dumpPackages dflags = putMsg dflags (pprPackages dflags)
dumpPackagesSimple dflags = putMsg dflags (pprPackagesSimple dflags)
-- -----------------------------------------------------------------------------
-- ABI hash support
{-
ghc --abi-hash Data.Foo System.Bar
Generates a combined hash of the ABI for modules Data.Foo and
System.Bar. The modules must already be compiled, and appropriate -i
options may be necessary in order to find the .hi files.
This is used by Cabal for generating the ComponentId for a
package. The ComponentId must change when the visible ABI of
the package chagnes, so during registration Cabal calls ghc --abi-hash
to get a hash of the package's ABI.
-}
-- | Print ABI hash of input modules.
--
-- The resulting hash is the MD5 of the GHC version used (Trac #5328,
-- see 'hiVersion') and of the existing ABI hash from each module (see
-- 'mi_mod_hash').
abiHash :: [String] -- ^ List of module names
-> Ghc ()
abiHash strs = do
hsc_env <- getSession
let dflags = hsc_dflags hsc_env
liftIO $ do
let find_it str = do
let modname = mkModuleName str
r <- findImportedModule hsc_env modname Nothing
case r of
Found _ m -> return m
_error -> throwGhcException $ CmdLineError $ showSDoc dflags $
cannotFindInterface dflags modname r
mods <- mapM find_it strs
let get_iface modl = loadUserInterface False (text "abiHash") modl
ifaces <- initIfaceCheck hsc_env $ mapM get_iface mods
bh <- openBinMem (3*1024) -- just less than a block
put_ bh hiVersion
-- package hashes change when the compiler version changes (for now)
-- see #5328
mapM_ (put_ bh . mi_mod_hash) ifaces
f <- fingerprintBinMem bh
putStrLn (showPpr dflags f)
-- -----------------------------------------------------------------------------
-- Util
unknownFlagsErr :: [String] -> a
unknownFlagsErr fs = throwGhcException $ UsageError $ concatMap oneError fs
where
oneError f =
"unrecognised flag: " ++ f ++ "\n" ++
(case fuzzyMatch f (nub allFlags) of
[] -> ""
suggs -> "did you mean one of:\n" ++ unlines (map (" " ++) suggs))
{- Note [-Bsymbolic and hooks]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Bsymbolic is a flag that prevents the binding of references to global
symbols to symbols outside the shared library being compiled (see `man
ld`). When dynamically linking, we don't use -Bsymbolic on the RTS
package: that is because we want hooks to be overridden by the user,
we don't want to constrain them to the RTS package.
Unfortunately this seems to have broken somehow on OS X: as a result,
defaultHooks (in hschooks.c) is not called, which does not initialize
the GC stats. As a result, this breaks things like `:set +s` in GHCi
(#8754). As a hacky workaround, we instead call 'defaultHooks'
directly to initalize the flags in the RTS.
A byproduct of this, I believe, is that hooks are likely broken on OS
X when dynamically linking. But this probably doesn't affect most
people since we're linking GHC dynamically, but most things themselves
link statically.
-}
foreign import ccall safe "initGCStatistics"
initGCStatistics :: IO ()
| siddhanathan/ghc | ghc/Main.hs | bsd-3-clause | 36,623 | 3 | 27 | 10,195 | 7,481 | 3,854 | 3,627 | 575 | 17 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Main where
import qualified Data.List as L
import qualified Data.Set as Set
import qualified Data.Map as M
import Data.Set (Set)
import Text.Printf (printf)
import EFA2.Solver.Equation
import EFA2.Solver.EquationOrder (order)
import EFA2.Solver.IsVar (maybeStaticVar)
import EFA2.Interpreter.Interpreter
(eqToInTerm, interpretFromScratch, interpretTerm)
import EFA2.Interpreter.Env
import EFA2.Interpreter.Arith (Val)
import qualified EFA2.Report.Format as Format
import qualified EFA2.Signal.Index as Idx
import qualified EFA2.Signal.Signal as S
import EFA2.Signal.Signal (Sc)
import EFA2.Topology.Topology (makeAllEquations)
import EFA2.Topology.TopologyData (SequFlowGraph)
import EFA2.Topology.Draw (drawDeltaTopology, drawTopology, drawAll)
import EFA2.Example.Dreibein
symbolic :: SequFlowGraph -> Envs NoRecord EqTerm
symbolic g = mapEqTermEnv (setEqTerms (emptyEnv { dxMap = dx1eq })) res
where
envs0 = emptyEnv { recordNumber = SingleRecord rec0,
powerMap = power0eq,
dtimeMap = dtimes0eq,
xMap = x0eq,
fetaMap = eta0eq }
envs1 = emptyEnv { recordNumber = SingleRecord rec1,
powerMap = power1eq,
dpowerMap = dpower1eq,
fetaMap = eta1eq,
detaMap = deta1eq,
xMap = x1eq,
dxMap = dx1eq,
dtimeMap = dtimes1eq }
ts0 = snd $ makeAllEquations g [envs0]
ts1 = snd $ makeAllEquations g [envs1]
ts0o = order ts0
ts1o = order ts1
difftseq = mkDiffEqTermEquations rec0 ts1o
ts =
toAbsEquations $ order $ map assignToEquation $
ts0o ++ ts1o ++ difftseq
res = interpretEqTermFromScratch ts
numeric :: SequFlowGraph -> Envs MixedRecord Sc
numeric g = res -- trace ("---------\n" ++ showAssigns ts1o ++ "\n------\n") res
where envs0 = emptyEnv { recordNumber = SingleRecord rec0,
powerMap = power0num,
dtimeMap = dtimes0num,
xMap = x0num,
fetaMap = eta0num }
envs1 = emptyEnv { recordNumber = SingleRecord rec1,
powerMap = power1num,
dpowerMap = dpower1num,
fetaMap = eta1num,
detaMap = deta1num,
xMap = x1num,
dxMap = dx1num,
dtimeMap = dtimes1num }
(envs0', ts0) = makeAllEquations g [envs0]
(envs1', ts1) = makeAllEquations g [envs1]
ts0o = order ts0
ts1o = order ts1
difftseq = mkDiffEqTermEquations rec0 ts1o
envs = envUnion [envs0', envs1']
ts = toAbsEquations $ ts0o ++ ts1o ++ difftseq
res = interpretFromScratch (recordNumber envs) 1 (map (eqToInTerm envs) ts)
deltaEnv :: SequFlowGraph -> Envs MixedRecord Sc
deltaEnv g = res1 `minusEnv` res0
where
envs0 = emptyEnv { recordNumber = SingleRecord rec0,
powerMap = power0num,
dtimeMap = dtimes0num,
xMap = x0num,
fetaMap = eta0num }
envs1 = emptyEnv { recordNumber = SingleRecord rec1,
powerMap = power1num,
--dpowerMap = dpower1num,
--detaMap = deta1num,
dtimeMap = dtimes1num,
xMap = x1num,
fetaMap = eta1num }
(envs0', ts0) = makeAllEquations g [envs0]
(envs1', ts1) = makeAllEquations g [envs1]
ts0' = toAbsEquations $ order ts0
ts1' = toAbsEquations $ order ts1
res0 = interpretFromScratch (recordNumber envs0') 1 (map (eqToInTerm envs0') ts0')
res1 = interpretFromScratch (recordNumber envs1') 1 (map (eqToInTerm envs1') ts1')
class MyShow a where
myshow :: a -> String
instance MyShow Int where
myshow = show
instance MyShow Double where
myshow = printf "%.6f"
instance MyShow Sc where
myshow = show
instance MyShow Idx.DPower where
myshow (Idx.DPower r f t) =
Format.unUnicode $
Format.edgeVar Format.Delta Format.Power r f t
instance ToIndex idx => MyShow (Term idx) where
myshow t = Format.unUnicode $ formatTerm t
instance MyShow a => MyShow [a] where
myshow xs = "[ " ++ L.intercalate ", " (map myshow xs) ++ " ]"
instance MyShow a => MyShow (Set a) where
myshow s = myshow $ Set.toList s
format :: (MyShow a, MyShow b) => [(a, b)] -> String
format xs = L.intercalate "\n" (map f xs)
where f (x, y) = myshow x ++ " = " ++ myshow y
main :: IO ()
main = do
let g = graph
sym = symbolic g
num = numeric g
dpnum = dpowerMap num
dpsym = dpowerMap sym
dpsymEq = M.map pushMult dpsym
dpsymIn = dpsym
dpsyminterp = M.map (interpretTerm 1 num) dpsymIn
detailsSym = M.map additiveTerms dpsymEq
details :: M.Map Idx.DPower [Val]
details = M.map (map (S.fromScalar . interpretTerm 1 num)) detailsSym
sumdetails = M.map sum details
control = dpowerMap (deltaEnv g)
vars = M.map (length . map (mkVarSet maybeStaticVar)) detailsSym
putStrLn "\n== Control delta environment (later env - former env, computed independently) =="
putStrLn (format $ M.toList control)
putStrLn "\n== Numeric solution =="
putStrLn (format $ M.toList dpnum)
putStrLn "\n== Symbolic solution =="
putStrLn (format $ M.toList dpsymEq)
putStrLn "\n== Numeric interpretation of symbolic solution =="
putStrLn (format $ M.toList dpsyminterp)
putStrLn "\n== Symbolic additive terms =="
putStrLn (format $ M.toList detailsSym)
putStrLn "\n== Numeric additive terms =="
putStrLn (format $ M.toList details)
putStrLn "\n== Sums of numeric additive terms =="
putStrLn (format $ M.toList sumdetails)
putStrLn "\n== Additive terms per stack =="
putStrLn (format $ M.toList vars)
drawAll [
drawTopology g ((mapEqTermEnv ((:[]) . simplify) sym) { recordNumber = SingleRecord rec0 }),
drawDeltaTopology g ((mapEqTermEnv additiveTerms sym) { recordNumber = SingleRecord rec1 }) ]
| energyflowanalysis/efa-2.1 | attic/examples/elementary/additive_terms/Main.hs | bsd-3-clause | 6,556 | 0 | 17 | 2,153 | 1,730 | 933 | 797 | 144 | 1 |
module Paint
( module Paint.DisplayCommand
, module Paint.Rect
, module Paint.Text
, paint
) where
import Paint.DisplayCommand
import Paint.Rect
import Paint.Text
paint :: SDLContext -> [DisplayCommand] -> IO ()
paint ctx = mapM_ ($ ctx)
| forestbelton/orb | src/Paint.hs | bsd-3-clause | 260 | 0 | 8 | 57 | 78 | 46 | 32 | 10 | 1 |
Subsets and Splits