code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
---------------------------------------------------------------
-- |
-- Module : Data.Minecraft.Release17.Protocol
-- Copyright : (c) 2016 Michael Carpenter
-- License : BSD3
-- Maintainer : Michael Carpenter <oldmanmike.dev@gmail.com>
-- Stability : experimental
-- Portability : portable
--
---------------------------------------------------------------
module Data.Minecraft.Release17.Protocol
( ServerBoundHandshakingPacket (..)
, ClientBoundStatusPacket (..)
, ServerBoundStatusPacket (..)
, ClientBoundLoginPacket (..)
, ServerBoundLoginPacket (..)
, ClientBoundPlayPacket (..)
, ServerBoundPlayPacket (..)
) where
import Data.Attoparsec.ByteString
import Data.ByteString as B
import Data.ByteString.Builder as BB
import Data.Int
import Data.Fixed
import Data.Minecraft.Types
import Data.NBT
import Data.Serialize hiding (putByteString,getByteString)
import Data.Text as T
import Data.UUID
import Data.Word
data ServerBoundHandshakingPacket
= ServerBoundSetProtocol VarInt Text Word16 VarInt
| ServerBoundLegacyServerListPing Word8
deriving (Show,Eq)
data ClientBoundStatusPacket
= ClientBoundServerInfo Text
| ClientBoundPing Int64
deriving (Show,Eq)
data ServerBoundStatusPacket
= ServerBoundPingStart
| ServerBoundPing Int64
deriving (Show,Eq)
data ClientBoundLoginPacket
= ClientBoundDisconnect Text
| ClientBoundEncryptionBegin Text Buffer Buffer
| ClientBoundSuccess Text Text
deriving (Show,Eq)
data ServerBoundLoginPacket
= ServerBoundLoginStart Text
| ServerBoundEncryptionBegin Buffer Buffer
deriving (Show,Eq)
data ClientBoundPlayPacket
= ClientBoundKeepAlive Int32
| ClientBoundLogin Int32 Word8 Int8 Word8 Word8 Text
| ClientBoundChat Text
| ClientBoundUpdateTime Int64 Int64
| ClientBoundEntityEquipment Int32 Int16 Slot
| ClientBoundSpawnPosition PositionIII
| ClientBoundUpdateHealth Float Int16 Float
| ClientBoundRespawn Int32 Word8 Word8 Text
| ClientBoundPosition Double Double Double Float Float Bool
| ClientBoundHeldItemSlot Int8
| ClientBoundBed Int32 PositionIBI
| ClientBoundAnimation VarInt Word8
| ClientBoundNamedEntitySpawn VarInt Text Text Array Int32 Int32 Int32 Int8 Int8 Int16 EntityMetadata
| ClientBoundCollect Int32 Int32
| ClientBoundSpawnEntity VarInt Int8 Int32 Int32 Int32 Int8 Int8 Container
| ClientBoundSpawnEntityLiving VarInt Word8 Int32 Int32 Int32 Int8 Int8 Int8 Int16 Int16 Int16 EntityMetadata
| ClientBoundSpawnEntityPainting VarInt Text PositionIII Word8
| ClientBoundSpawnEntityExperienceOrb VarInt Int32 Int32 Int32 Int16
| ClientBoundEntityVelocity Int32 Int16 Int16 Int16
| ClientBoundEntityDestroy Array
| ClientBoundEntity Int32
| ClientBoundRelEntityMove Int32 Int8 Int8 Int8
| ClientBoundEntityLook Int32 Int8 Int8
| ClientBoundEntityMoveLook Int32 Int8 Int8 Int8 Int8 Int8
| ClientBoundEntityTeleport Int32 Int32 Int32 Int32 Int8 Int8
| ClientBoundEntityHeadRotation Int32 Int8
| ClientBoundEntityStatus Int32 Int8
| ClientBoundAttachEntity Int32 Int32 Bool
| ClientBoundEntityMetadata Int32 EntityMetadata
| ClientBoundEntityEffect Int32 Int8 Int8 Int16
| ClientBoundRemoveEntityEffect Int32 Int8
| ClientBoundExperience Float Int16 Int16
| ClientBoundUpdateAttributes Int32 Array
| ClientBoundMapChunk Int32 Int32 Bool Word16 Word16 Buffer
| ClientBoundMultiBlockChange Int32 Int32 (Count Int16) Int32 Array
| ClientBoundBlockChange PositionIBI VarInt Word8
| ClientBoundBlockAction PositionISI Word8 Word8 VarInt
| ClientBoundBlockBreakAnimation VarInt PositionIII Int8
| ClientBoundMapChunkBulk (Count Int16) (Count Int32) Bool Buffer Array
| ClientBoundExplosion Float Float Float Float Array Float Float Float
| ClientBoundWorldEvent Int32 PositionIBI Int32 Bool
| ClientBoundNamedSoundEffect Text Int32 Int32 Int32 Float Word8
| ClientBoundWorldParticles Text Float Float Float Float Float Float Float Int32
| ClientBoundGameStateChange Word8 Float
| ClientBoundSpawnEntityWeather VarInt Int8 Int32 Int32 Int32
| ClientBoundOpenWindow Word8 Word8 Text Word8 Bool (Maybe Int32)
| ClientBoundCloseWindow Word8
| ClientBoundSetSlot Int8 Int16 Slot
| ClientBoundWindowItems Word8 Array
| ClientBoundCraftProgressBar Word8 Int16 Int16
| ClientBoundTransaction Word8 Int16 Bool
| ClientBoundUpdateSign PositionISI Text Text Text Text
| ClientBoundMap VarInt Buffer
| ClientBoundTileEntityData PositionISI Word8 CompressedNBT
| ClientBoundOpenSignEntity PositionIII
| ClientBoundStatistics Array
| ClientBoundPlayerInfo Text Bool Int16
| ClientBoundAbilities Int8 Float Float
| ClientBoundTabComplete Array
| ClientBoundScoreboardObjective Text Text Int8
| ClientBoundScoreboardScore Text Int8 Text (Maybe Int32)
| ClientBoundScoreboardDisplayObjective Int8 Text
| ClientBoundScoreboardTeam Text Int8 (Maybe Text) (Maybe Text) (Maybe Text) (Maybe Int8) (Maybe Text) (Maybe Int8) (Maybe Array)
| ClientBoundCustomPayload Text Buffer
| ClientBoundKickDisconnect Text
deriving (Show,Eq)
data ServerBoundPlayPacket
= ServerBoundKeepAlive Int32
| ServerBoundChat Text
| ServerBoundUseEntity Int32 Int8 (Maybe Float) (Maybe Float) (Maybe Float)
| ServerBoundFlying Bool
| ServerBoundPosition Double Double Double Double Bool
| ServerBoundLook Float Float Bool
| ServerBoundPositionLook Double Double Double Double Float Float Bool
| ServerBoundBlockDig Int8 PositionIBI Int8
| ServerBoundBlockPlace PositionIBI Int8 Slot Int8 Int8 Int8
| ServerBoundHeldItemSlot Int16
| ServerBoundArmAnimation Int32 Int8
| ServerBoundEntityAction Int32 Int8 Int32
| ServerBoundSteerVehicle Float Float Bool Bool
| ServerBoundCloseWindow Word8
| ServerBoundWindowClick Int8 Int16 Int8 Int16 Int8 Slot
| ServerBoundTransaction Int8 Int16 Bool
| ServerBoundSetCreativeSlot Int16 Slot
| ServerBoundEnchantItem Int8 Int8
| ServerBoundUpdateSign PositionISI Text Text Text Text
| ServerBoundAbilities Int8 Float Float
| ServerBoundTabComplete Text
| ServerBoundSettings Text Int8 Int8 Bool Word8 Bool
| ServerBoundClientCommand Int8
| ServerBoundCustomPayload Text Buffer
deriving (Show,Eq)
instance Serialize ServerBoundHandshakingPacket where
put (ServerBoundSetProtocol protocolVersion serverHost serverPort nextState) = do
putWord8 0x00
putVarInt protocolVersion
putText serverHost
putWord16 serverPort
putVarInt nextState
put (ServerBoundLegacyServerListPing payload) = do
putWord8 0xfe
putWord8 payload
get = do
packetId <- getWord8
case packetId of
0x00 -> do
protocolVersion <- getVarInt
serverHost <- getText
serverPort <- getWord16
nextState <- getVarInt
return $ ServerBoundSetProtocol protocolVersion serverHost serverPort nextState
0xfe -> do
payload <- getWord8
return $ ServerBoundLegacyServerListPing payload
instance Serialize ClientBoundStatusPacket where
put (ClientBoundServerInfo response) = do
putWord8 0x00
putText response
put (ClientBoundPing time) = do
putWord8 0x01
putInt64 time
get = do
packetId <- getWord8
case packetId of
0x00 -> do
response <- getText
return $ ClientBoundServerInfo response
0x01 -> do
time <- getInt64
return $ ClientBoundPing time
instance Serialize ServerBoundStatusPacket where
put (ServerBoundPingStart ) = do
putWord8 0x00
put (ServerBoundPing time) = do
putWord8 0x01
putInt64 time
get = do
packetId <- getWord8
case packetId of
0x00 -> do
return $ ServerBoundPingStart
0x01 -> do
time <- getInt64
return $ ServerBoundPing time
instance Serialize ClientBoundLoginPacket where
put (ClientBoundDisconnect reason) = do
putWord8 0x00
putText reason
put (ClientBoundEncryptionBegin serverId publicKey verifyToken) = do
putWord8 0x01
putText serverId
putBuffer publicKey
putBuffer verifyToken
put (ClientBoundSuccess uuid username) = do
putWord8 0x02
putText uuid
putText username
get = do
packetId <- getWord8
case packetId of
0x00 -> do
reason <- getText
return $ ClientBoundDisconnect reason
0x01 -> do
serverId <- getText
publicKey <- getBuffer
verifyToken <- getBuffer
return $ ClientBoundEncryptionBegin serverId publicKey verifyToken
0x02 -> do
uuid <- getText
username <- getText
return $ ClientBoundSuccess uuid username
instance Serialize ServerBoundLoginPacket where
put (ServerBoundLoginStart username) = do
putWord8 0x00
putText username
put (ServerBoundEncryptionBegin sharedSecret verifyToken) = do
putWord8 0x01
putBuffer sharedSecret
putBuffer verifyToken
get = do
packetId <- getWord8
case packetId of
0x00 -> do
username <- getText
return $ ServerBoundLoginStart username
0x01 -> do
sharedSecret <- getBuffer
verifyToken <- getBuffer
return $ ServerBoundEncryptionBegin sharedSecret verifyToken
instance Serialize ClientBoundPlayPacket where
put (ClientBoundKeepAlive keepAliveId) = do
putWord8 0x00
putInt32 keepAliveId
put (ClientBoundLogin entityId gameMode dimension difficulty maxPlayers levelType) = do
putWord8 0x01
putInt32 entityId
putWord8 gameMode
putInt8 dimension
putWord8 difficulty
putWord8 maxPlayers
putText levelType
put (ClientBoundChat message) = do
putWord8 0x02
putText message
put (ClientBoundUpdateTime age time) = do
putWord8 0x03
putInt64 age
putInt64 time
put (ClientBoundEntityEquipment entityId slot item) = do
putWord8 0x04
putInt32 entityId
putInt16 slot
putSlot item
put (ClientBoundSpawnPosition location) = do
putWord8 0x05
putPositionIII location
put (ClientBoundUpdateHealth health food foodSaturation) = do
putWord8 0x06
putFloat health
putInt16 food
putFloat foodSaturation
put (ClientBoundRespawn dimension difficulty gamemode levelType) = do
putWord8 0x07
putInt32 dimension
putWord8 difficulty
putWord8 gamemode
putText levelType
put (ClientBoundPosition x y z yaw pitch onGround) = do
putWord8 0x08
putDouble x
putDouble y
putDouble z
putFloat yaw
putFloat pitch
putBool onGround
put (ClientBoundHeldItemSlot slot) = do
putWord8 0x09
putInt8 slot
put (ClientBoundBed entityId location) = do
putWord8 0x0a
putInt32 entityId
putPositionIBI location
put (ClientBoundAnimation entityId animation) = do
putWord8 0x0b
putVarInt entityId
putWord8 animation
put (ClientBoundNamedEntitySpawn entityId playerUUID playerName pData x y z yaw pitch currentItem metadata) = do
putWord8 0x0c
putVarInt entityId
putText playerUUID
putText playerName
putArray pData
putInt32 x
putInt32 y
putInt32 z
putInt8 yaw
putInt8 pitch
putInt16 currentItem
putEntityMetadata metadata
put (ClientBoundCollect collectedEntityId collectorEntityId) = do
putWord8 0x0d
putInt32 collectedEntityId
putInt32 collectorEntityId
put (ClientBoundSpawnEntity entityId pType x y z pitch yaw objectData) = do
putWord8 0x0e
putVarInt entityId
putInt8 pType
putInt32 x
putInt32 y
putInt32 z
putInt8 pitch
putInt8 yaw
putContainer objectData
put (ClientBoundSpawnEntityLiving entityId pType x y z yaw pitch headPitch velocityX velocityY velocityZ metadata) = do
putWord8 0x0f
putVarInt entityId
putWord8 pType
putInt32 x
putInt32 y
putInt32 z
putInt8 yaw
putInt8 pitch
putInt8 headPitch
putInt16 velocityX
putInt16 velocityY
putInt16 velocityZ
putEntityMetadata metadata
put (ClientBoundSpawnEntityPainting entityId title location direction) = do
putWord8 0x10
putVarInt entityId
putText title
putPositionIII location
putWord8 direction
put (ClientBoundSpawnEntityExperienceOrb entityId x y z count) = do
putWord8 0x11
putVarInt entityId
putInt32 x
putInt32 y
putInt32 z
putInt16 count
put (ClientBoundEntityVelocity entityId velocityX velocityY velocityZ) = do
putWord8 0x12
putInt32 entityId
putInt16 velocityX
putInt16 velocityY
putInt16 velocityZ
put (ClientBoundEntityDestroy entityIds) = do
putWord8 0x13
putArray entityIds
put (ClientBoundEntity entityId) = do
putWord8 0x14
putInt32 entityId
put (ClientBoundRelEntityMove entityId dX dY dZ) = do
putWord8 0x15
putInt32 entityId
putInt8 dX
putInt8 dY
putInt8 dZ
put (ClientBoundEntityLook entityId yaw pitch) = do
putWord8 0x16
putInt32 entityId
putInt8 yaw
putInt8 pitch
put (ClientBoundEntityMoveLook entityId dX dY dZ yaw pitch) = do
putWord8 0x17
putInt32 entityId
putInt8 dX
putInt8 dY
putInt8 dZ
putInt8 yaw
putInt8 pitch
put (ClientBoundEntityTeleport entityId x y z yaw pitch) = do
putWord8 0x18
putInt32 entityId
putInt32 x
putInt32 y
putInt32 z
putInt8 yaw
putInt8 pitch
put (ClientBoundEntityHeadRotation entityId headYaw) = do
putWord8 0x19
putInt32 entityId
putInt8 headYaw
put (ClientBoundEntityStatus entityId entityStatus) = do
putWord8 0x1a
putInt32 entityId
putInt8 entityStatus
put (ClientBoundAttachEntity entityId vehicleId leash) = do
putWord8 0x1b
putInt32 entityId
putInt32 vehicleId
putBool leash
put (ClientBoundEntityMetadata entityId metadata) = do
putWord8 0x1c
putInt32 entityId
putEntityMetadata metadata
put (ClientBoundEntityEffect entityId effectId amplifier duration) = do
putWord8 0x1d
putInt32 entityId
putInt8 effectId
putInt8 amplifier
putInt16 duration
put (ClientBoundRemoveEntityEffect entityId effectId) = do
putWord8 0x1e
putInt32 entityId
putInt8 effectId
put (ClientBoundExperience experienceBar level totalExperience) = do
putWord8 0x1f
putFloat experienceBar
putInt16 level
putInt16 totalExperience
put (ClientBoundUpdateAttributes entityId properties) = do
putWord8 0x20
putInt32 entityId
putArray properties
put (ClientBoundMapChunk x z groundUp bitMap addBitMap compressedChunkData) = do
putWord8 0x21
putInt32 x
putInt32 z
putBool groundUp
putWord16 bitMap
putWord16 addBitMap
putBuffer compressedChunkData
put (ClientBoundMultiBlockChange chunkX chunkZ recordCount dataLength records) = do
putWord8 0x22
putInt32 chunkX
putInt32 chunkZ
putCount recordCount
putInt32 dataLength
putArray records
put (ClientBoundBlockChange location pType metadata) = do
putWord8 0x23
putPositionIBI location
putVarInt pType
putWord8 metadata
put (ClientBoundBlockAction location byte1 byte2 blockId) = do
putWord8 0x24
putPositionISI location
putWord8 byte1
putWord8 byte2
putVarInt blockId
put (ClientBoundBlockBreakAnimation entityId location destroyStage) = do
putWord8 0x25
putVarInt entityId
putPositionIII location
putInt8 destroyStage
put (ClientBoundMapChunkBulk chunkColumnCount dataLength skyLightSent compressedChunkData meta) = do
putWord8 0x26
putCount chunkColumnCount
putCount dataLength
putBool skyLightSent
putBuffer compressedChunkData
putArray meta
put (ClientBoundExplosion x y z radius affectedBlockOffsets playerMotionX playerMotionY playerMotionZ) = do
putWord8 0x27
putFloat x
putFloat y
putFloat z
putFloat radius
putArray affectedBlockOffsets
putFloat playerMotionX
putFloat playerMotionY
putFloat playerMotionZ
put (ClientBoundWorldEvent effectId location pData global) = do
putWord8 0x28
putInt32 effectId
putPositionIBI location
putInt32 pData
putBool global
put (ClientBoundNamedSoundEffect soundName x y z volume pitch) = do
putWord8 0x29
putText soundName
putInt32 x
putInt32 y
putInt32 z
putFloat volume
putWord8 pitch
put (ClientBoundWorldParticles particleName x y z offsetX offsetY offsetZ particleData particles) = do
putWord8 0x2a
putText particleName
putFloat x
putFloat y
putFloat z
putFloat offsetX
putFloat offsetY
putFloat offsetZ
putFloat particleData
putInt32 particles
put (ClientBoundGameStateChange reason gameMode) = do
putWord8 0x2b
putWord8 reason
putFloat gameMode
put (ClientBoundSpawnEntityWeather entityId pType x y z) = do
putWord8 0x2c
putVarInt entityId
putInt8 pType
putInt32 x
putInt32 y
putInt32 z
put (ClientBoundOpenWindow windowId inventoryType windowTitle slotCount useProvidedTitle entityId) = do
putWord8 0x2d
putWord8 windowId
putWord8 inventoryType
putText windowTitle
putWord8 slotCount
putBool useProvidedTitle
case entityId of
Just entityId' -> putInt32 entityId'
Nothing -> return ()
put (ClientBoundCloseWindow windowId) = do
putWord8 0x2e
putWord8 windowId
put (ClientBoundSetSlot windowId slot item) = do
putWord8 0x2f
putInt8 windowId
putInt16 slot
putSlot item
put (ClientBoundWindowItems windowId items) = do
putWord8 0x30
putWord8 windowId
putArray items
put (ClientBoundCraftProgressBar windowId property value) = do
putWord8 0x31
putWord8 windowId
putInt16 property
putInt16 value
put (ClientBoundTransaction windowId action accepted) = do
putWord8 0x32
putWord8 windowId
putInt16 action
putBool accepted
put (ClientBoundUpdateSign location text1 text2 text3 text4) = do
putWord8 0x33
putPositionISI location
putText text1
putText text2
putText text3
putText text4
put (ClientBoundMap itemDamage pData) = do
putWord8 0x34
putVarInt itemDamage
putBuffer pData
put (ClientBoundTileEntityData location action nbtData) = do
putWord8 0x35
putPositionISI location
putWord8 action
putCompressedNBT nbtData
put (ClientBoundOpenSignEntity location) = do
putWord8 0x36
putPositionIII location
put (ClientBoundStatistics entries) = do
putWord8 0x37
putArray entries
put (ClientBoundPlayerInfo playerName online ping) = do
putWord8 0x38
putText playerName
putBool online
putInt16 ping
put (ClientBoundAbilities flags flyingSpeed walkingSpeed) = do
putWord8 0x39
putInt8 flags
putFloat flyingSpeed
putFloat walkingSpeed
put (ClientBoundTabComplete matches) = do
putWord8 0x3a
putArray matches
put (ClientBoundScoreboardObjective name displayText action) = do
putWord8 0x3b
putText name
putText displayText
putInt8 action
put (ClientBoundScoreboardScore itemName action scoreName value) = do
putWord8 0x3c
putText itemName
putInt8 action
putText scoreName
case value of
Just value' -> putInt32 value'
Nothing -> return ()
put (ClientBoundScoreboardDisplayObjective position name) = do
putWord8 0x3d
putInt8 position
putText name
put (ClientBoundScoreboardTeam team mode name prefix suffix friendlyFire nameTagVisibility color players) = do
putWord8 0x3e
putText team
putInt8 mode
case name of
Just name' -> putText name'
Nothing -> return ()
case prefix of
Just prefix' -> putText prefix'
Nothing -> return ()
case suffix of
Just suffix' -> putText suffix'
Nothing -> return ()
case friendlyFire of
Just friendlyFire' -> putInt8 friendlyFire'
Nothing -> return ()
case nameTagVisibility of
Just nameTagVisibility' -> putText nameTagVisibility'
Nothing -> return ()
case color of
Just color' -> putInt8 color'
Nothing -> return ()
case players of
Just players' -> putArray players'
Nothing -> return ()
put (ClientBoundCustomPayload channel pData) = do
putWord8 0x3f
putText channel
putBuffer pData
put (ClientBoundKickDisconnect reason) = do
putWord8 0x40
putText reason
get = do
packetId <- getWord8
case packetId of
0x00 -> do
keepAliveId <- getInt32
return $ ClientBoundKeepAlive keepAliveId
0x01 -> do
entityId <- getInt32
gameMode <- getWord8
dimension <- getInt8
difficulty <- getWord8
maxPlayers <- getWord8
levelType <- getText
return $ ClientBoundLogin entityId gameMode dimension difficulty maxPlayers levelType
0x02 -> do
message <- getText
return $ ClientBoundChat message
0x03 -> do
age <- getInt64
time <- getInt64
return $ ClientBoundUpdateTime age time
0x04 -> do
entityId <- getInt32
slot <- getInt16
item <- getSlot
return $ ClientBoundEntityEquipment entityId slot item
0x05 -> do
location <- getPositionIII
return $ ClientBoundSpawnPosition location
0x06 -> do
health <- getFloat
food <- getInt16
foodSaturation <- getFloat
return $ ClientBoundUpdateHealth health food foodSaturation
0x07 -> do
dimension <- getInt32
difficulty <- getWord8
gamemode <- getWord8
levelType <- getText
return $ ClientBoundRespawn dimension difficulty gamemode levelType
0x08 -> do
x <- getDouble
y <- getDouble
z <- getDouble
yaw <- getFloat
pitch <- getFloat
onGround <- getBool
return $ ClientBoundPosition x y z yaw pitch onGround
0x09 -> do
slot <- getInt8
return $ ClientBoundHeldItemSlot slot
0x0a -> do
entityId <- getInt32
location <- getPositionIBI
return $ ClientBoundBed entityId location
0x0b -> do
entityId <- getVarInt
animation <- getWord8
return $ ClientBoundAnimation entityId animation
0x0c -> do
entityId <- getVarInt
playerUUID <- getText
playerName <- getText
pData <- getArray
x <- getInt32
y <- getInt32
z <- getInt32
yaw <- getInt8
pitch <- getInt8
currentItem <- getInt16
metadata <- getEntityMetadata
return $ ClientBoundNamedEntitySpawn entityId playerUUID playerName pData x y z yaw pitch currentItem metadata
0x0d -> do
collectedEntityId <- getInt32
collectorEntityId <- getInt32
return $ ClientBoundCollect collectedEntityId collectorEntityId
0x0e -> do
entityId <- getVarInt
pType <- getInt8
x <- getInt32
y <- getInt32
z <- getInt32
pitch <- getInt8
yaw <- getInt8
objectData <- getContainer
return $ ClientBoundSpawnEntity entityId pType x y z pitch yaw objectData
0x0f -> do
entityId <- getVarInt
pType <- getWord8
x <- getInt32
y <- getInt32
z <- getInt32
yaw <- getInt8
pitch <- getInt8
headPitch <- getInt8
velocityX <- getInt16
velocityY <- getInt16
velocityZ <- getInt16
metadata <- getEntityMetadata
return $ ClientBoundSpawnEntityLiving entityId pType x y z yaw pitch headPitch velocityX velocityY velocityZ metadata
0x10 -> do
entityId <- getVarInt
title <- getText
location <- getPositionIII
direction <- getWord8
return $ ClientBoundSpawnEntityPainting entityId title location direction
0x11 -> do
entityId <- getVarInt
x <- getInt32
y <- getInt32
z <- getInt32
count <- getInt16
return $ ClientBoundSpawnEntityExperienceOrb entityId x y z count
0x12 -> do
entityId <- getInt32
velocityX <- getInt16
velocityY <- getInt16
velocityZ <- getInt16
return $ ClientBoundEntityVelocity entityId velocityX velocityY velocityZ
0x13 -> do
entityIds <- getArray
return $ ClientBoundEntityDestroy entityIds
0x14 -> do
entityId <- getInt32
return $ ClientBoundEntity entityId
0x15 -> do
entityId <- getInt32
dX <- getInt8
dY <- getInt8
dZ <- getInt8
return $ ClientBoundRelEntityMove entityId dX dY dZ
0x16 -> do
entityId <- getInt32
yaw <- getInt8
pitch <- getInt8
return $ ClientBoundEntityLook entityId yaw pitch
0x17 -> do
entityId <- getInt32
dX <- getInt8
dY <- getInt8
dZ <- getInt8
yaw <- getInt8
pitch <- getInt8
return $ ClientBoundEntityMoveLook entityId dX dY dZ yaw pitch
0x18 -> do
entityId <- getInt32
x <- getInt32
y <- getInt32
z <- getInt32
yaw <- getInt8
pitch <- getInt8
return $ ClientBoundEntityTeleport entityId x y z yaw pitch
0x19 -> do
entityId <- getInt32
headYaw <- getInt8
return $ ClientBoundEntityHeadRotation entityId headYaw
0x1a -> do
entityId <- getInt32
entityStatus <- getInt8
return $ ClientBoundEntityStatus entityId entityStatus
0x1b -> do
entityId <- getInt32
vehicleId <- getInt32
leash <- getBool
return $ ClientBoundAttachEntity entityId vehicleId leash
0x1c -> do
entityId <- getInt32
metadata <- getEntityMetadata
return $ ClientBoundEntityMetadata entityId metadata
0x1d -> do
entityId <- getInt32
effectId <- getInt8
amplifier <- getInt8
duration <- getInt16
return $ ClientBoundEntityEffect entityId effectId amplifier duration
0x1e -> do
entityId <- getInt32
effectId <- getInt8
return $ ClientBoundRemoveEntityEffect entityId effectId
0x1f -> do
experienceBar <- getFloat
level <- getInt16
totalExperience <- getInt16
return $ ClientBoundExperience experienceBar level totalExperience
0x20 -> do
entityId <- getInt32
properties <- getArray
return $ ClientBoundUpdateAttributes entityId properties
0x21 -> do
x <- getInt32
z <- getInt32
groundUp <- getBool
bitMap <- getWord16
addBitMap <- getWord16
compressedChunkData <- getBuffer
return $ ClientBoundMapChunk x z groundUp bitMap addBitMap compressedChunkData
0x22 -> do
chunkX <- getInt32
chunkZ <- getInt32
recordCount <- get(Count Int16)
dataLength <- getInt32
records <- getArray
return $ ClientBoundMultiBlockChange chunkX chunkZ recordCount dataLength records
0x23 -> do
location <- getPositionIBI
pType <- getVarInt
metadata <- getWord8
return $ ClientBoundBlockChange location pType metadata
0x24 -> do
location <- getPositionISI
byte1 <- getWord8
byte2 <- getWord8
blockId <- getVarInt
return $ ClientBoundBlockAction location byte1 byte2 blockId
0x25 -> do
entityId <- getVarInt
location <- getPositionIII
destroyStage <- getInt8
return $ ClientBoundBlockBreakAnimation entityId location destroyStage
0x26 -> do
chunkColumnCount <- get(Count Int16)
dataLength <- get(Count Int32)
skyLightSent <- getBool
compressedChunkData <- getBuffer
meta <- getArray
return $ ClientBoundMapChunkBulk chunkColumnCount dataLength skyLightSent compressedChunkData meta
0x27 -> do
x <- getFloat
y <- getFloat
z <- getFloat
radius <- getFloat
affectedBlockOffsets <- getArray
playerMotionX <- getFloat
playerMotionY <- getFloat
playerMotionZ <- getFloat
return $ ClientBoundExplosion x y z radius affectedBlockOffsets playerMotionX playerMotionY playerMotionZ
0x28 -> do
effectId <- getInt32
location <- getPositionIBI
pData <- getInt32
global <- getBool
return $ ClientBoundWorldEvent effectId location pData global
0x29 -> do
soundName <- getText
x <- getInt32
y <- getInt32
z <- getInt32
volume <- getFloat
pitch <- getWord8
return $ ClientBoundNamedSoundEffect soundName x y z volume pitch
0x2a -> do
particleName <- getText
x <- getFloat
y <- getFloat
z <- getFloat
offsetX <- getFloat
offsetY <- getFloat
offsetZ <- getFloat
particleData <- getFloat
particles <- getInt32
return $ ClientBoundWorldParticles particleName x y z offsetX offsetY offsetZ particleData particles
0x2b -> do
reason <- getWord8
gameMode <- getFloat
return $ ClientBoundGameStateChange reason gameMode
0x2c -> do
entityId <- getVarInt
pType <- getInt8
x <- getInt32
y <- getInt32
z <- getInt32
return $ ClientBoundSpawnEntityWeather entityId pType x y z
0x2d -> do
windowId <- getWord8
inventoryType <- getWord8
windowTitle <- getText
slotCount <- getWord8
useProvidedTitle <- getBool
let entityId =
case inventoryType of
EntityHorse ->
_ ->
return $ ClientBoundOpenWindow windowId inventoryType windowTitle slotCount useProvidedTitle entityId
0x2e -> do
windowId <- getWord8
return $ ClientBoundCloseWindow windowId
0x2f -> do
windowId <- getInt8
slot <- getInt16
item <- getSlot
return $ ClientBoundSetSlot windowId slot item
0x30 -> do
windowId <- getWord8
items <- getArray
return $ ClientBoundWindowItems windowId items
0x31 -> do
windowId <- getWord8
property <- getInt16
value <- getInt16
return $ ClientBoundCraftProgressBar windowId property value
0x32 -> do
windowId <- getWord8
action <- getInt16
accepted <- getBool
return $ ClientBoundTransaction windowId action accepted
0x33 -> do
location <- getPositionISI
text1 <- getText
text2 <- getText
text3 <- getText
text4 <- getText
return $ ClientBoundUpdateSign location text1 text2 text3 text4
0x34 -> do
itemDamage <- getVarInt
pData <- getBuffer
return $ ClientBoundMap itemDamage pData
0x35 -> do
location <- getPositionISI
action <- getWord8
nbtData <- getCompressedNBT
return $ ClientBoundTileEntityData location action nbtData
0x36 -> do
location <- getPositionIII
return $ ClientBoundOpenSignEntity location
0x37 -> do
entries <- getArray
return $ ClientBoundStatistics entries
0x38 -> do
playerName <- getText
online <- getBool
ping <- getInt16
return $ ClientBoundPlayerInfo playerName online ping
0x39 -> do
flags <- getInt8
flyingSpeed <- getFloat
walkingSpeed <- getFloat
return $ ClientBoundAbilities flags flyingSpeed walkingSpeed
0x3a -> do
matches <- getArray
return $ ClientBoundTabComplete matches
0x3b -> do
name <- getText
displayText <- getText
action <- getInt8
return $ ClientBoundScoreboardObjective name displayText action
0x3c -> do
itemName <- getText
action <- getInt8
scoreName <- getText
let value =
case action of
1 ->
_ ->
return $ ClientBoundScoreboardScore itemName action scoreName value
0x3d -> do
position <- getInt8
name <- getText
return $ ClientBoundScoreboardDisplayObjective position name
0x3e -> do
team <- getText
mode <- getInt8
let name =
case mode of
0 ->
2 ->
_ ->
let prefix =
case mode of
0 ->
2 ->
_ ->
let suffix =
case mode of
0 ->
2 ->
_ ->
let friendlyFire =
case mode of
0 ->
2 ->
_ ->
let nameTagVisibility =
case mode of
0 ->
2 ->
_ ->
let color =
case mode of
0 ->
2 ->
_ ->
let players =
case mode of
0 ->
4 ->
3 ->
_ ->
return $ ClientBoundScoreboardTeam team mode name prefix suffix friendlyFire nameTagVisibility color players
0x3f -> do
channel <- getText
pData <- getBuffer
return $ ClientBoundCustomPayload channel pData
0x40 -> do
reason <- getText
return $ ClientBoundKickDisconnect reason
instance Serialize ServerBoundPlayPacket where
put (ServerBoundKeepAlive keepAliveId) = do
putWord8 0x00
putInt32 keepAliveId
put (ServerBoundChat message) = do
putWord8 0x01
putText message
put (ServerBoundUseEntity target mouse x y z) = do
putWord8 0x02
putInt32 target
putInt8 mouse
case x of
Just x' -> putFloat x'
Nothing -> return ()
case y of
Just y' -> putFloat y'
Nothing -> return ()
case z of
Just z' -> putFloat z'
Nothing -> return ()
put (ServerBoundFlying onGround) = do
putWord8 0x03
putBool onGround
put (ServerBoundPosition x stance y z onGround) = do
putWord8 0x04
putDouble x
putDouble stance
putDouble y
putDouble z
putBool onGround
put (ServerBoundLook yaw pitch onGround) = do
putWord8 0x05
putFloat yaw
putFloat pitch
putBool onGround
put (ServerBoundPositionLook x stance y z yaw pitch onGround) = do
putWord8 0x06
putDouble x
putDouble stance
putDouble y
putDouble z
putFloat yaw
putFloat pitch
putBool onGround
put (ServerBoundBlockDig status location face) = do
putWord8 0x07
putInt8 status
putPositionIBI location
putInt8 face
put (ServerBoundBlockPlace location direction heldItem cursorX cursorY cursorZ) = do
putWord8 0x08
putPositionIBI location
putInt8 direction
putSlot heldItem
putInt8 cursorX
putInt8 cursorY
putInt8 cursorZ
put (ServerBoundHeldItemSlot slotId) = do
putWord8 0x09
putInt16 slotId
put (ServerBoundArmAnimation entityId animation) = do
putWord8 0x0a
putInt32 entityId
putInt8 animation
put (ServerBoundEntityAction entityId actionId jumpBoost) = do
putWord8 0x0b
putInt32 entityId
putInt8 actionId
putInt32 jumpBoost
put (ServerBoundSteerVehicle sideways forward jump unmount) = do
putWord8 0x0c
putFloat sideways
putFloat forward
putBool jump
putBool unmount
put (ServerBoundCloseWindow windowId) = do
putWord8 0x0d
putWord8 windowId
put (ServerBoundWindowClick windowId slot mouseButton action mode item) = do
putWord8 0x0e
putInt8 windowId
putInt16 slot
putInt8 mouseButton
putInt16 action
putInt8 mode
putSlot item
put (ServerBoundTransaction windowId action accepted) = do
putWord8 0x0f
putInt8 windowId
putInt16 action
putBool accepted
put (ServerBoundSetCreativeSlot slot item) = do
putWord8 0x10
putInt16 slot
putSlot item
put (ServerBoundEnchantItem windowId enchantment) = do
putWord8 0x11
putInt8 windowId
putInt8 enchantment
put (ServerBoundUpdateSign location text1 text2 text3 text4) = do
putWord8 0x12
putPositionISI location
putText text1
putText text2
putText text3
putText text4
put (ServerBoundAbilities flags flyingSpeed walkingSpeed) = do
putWord8 0x13
putInt8 flags
putFloat flyingSpeed
putFloat walkingSpeed
put (ServerBoundTabComplete text) = do
putWord8 0x14
putText text
put (ServerBoundSettings locale viewDistance chatFlags chatColors difficulty showCape) = do
putWord8 0x15
putText locale
putInt8 viewDistance
putInt8 chatFlags
putBool chatColors
putWord8 difficulty
putBool showCape
put (ServerBoundClientCommand payload) = do
putWord8 0x16
putInt8 payload
put (ServerBoundCustomPayload channel pData) = do
putWord8 0x17
putText channel
putBuffer pData
get = do
packetId <- getWord8
case packetId of
0x00 -> do
keepAliveId <- getInt32
return $ ServerBoundKeepAlive keepAliveId
0x01 -> do
message <- getText
return $ ServerBoundChat message
0x02 -> do
target <- getInt32
mouse <- getInt8
let x =
case mouse of
2 ->
_ ->
let y =
case mouse of
2 ->
_ ->
let z =
case mouse of
2 ->
_ ->
return $ ServerBoundUseEntity target mouse x y z
0x03 -> do
onGround <- getBool
return $ ServerBoundFlying onGround
0x04 -> do
x <- getDouble
stance <- getDouble
y <- getDouble
z <- getDouble
onGround <- getBool
return $ ServerBoundPosition x stance y z onGround
0x05 -> do
yaw <- getFloat
pitch <- getFloat
onGround <- getBool
return $ ServerBoundLook yaw pitch onGround
0x06 -> do
x <- getDouble
stance <- getDouble
y <- getDouble
z <- getDouble
yaw <- getFloat
pitch <- getFloat
onGround <- getBool
return $ ServerBoundPositionLook x stance y z yaw pitch onGround
0x07 -> do
status <- getInt8
location <- getPositionIBI
face <- getInt8
return $ ServerBoundBlockDig status location face
0x08 -> do
location <- getPositionIBI
direction <- getInt8
heldItem <- getSlot
cursorX <- getInt8
cursorY <- getInt8
cursorZ <- getInt8
return $ ServerBoundBlockPlace location direction heldItem cursorX cursorY cursorZ
0x09 -> do
slotId <- getInt16
return $ ServerBoundHeldItemSlot slotId
0x0a -> do
entityId <- getInt32
animation <- getInt8
return $ ServerBoundArmAnimation entityId animation
0x0b -> do
entityId <- getInt32
actionId <- getInt8
jumpBoost <- getInt32
return $ ServerBoundEntityAction entityId actionId jumpBoost
0x0c -> do
sideways <- getFloat
forward <- getFloat
jump <- getBool
unmount <- getBool
return $ ServerBoundSteerVehicle sideways forward jump unmount
0x0d -> do
windowId <- getWord8
return $ ServerBoundCloseWindow windowId
0x0e -> do
windowId <- getInt8
slot <- getInt16
mouseButton <- getInt8
action <- getInt16
mode <- getInt8
item <- getSlot
return $ ServerBoundWindowClick windowId slot mouseButton action mode item
0x0f -> do
windowId <- getInt8
action <- getInt16
accepted <- getBool
return $ ServerBoundTransaction windowId action accepted
0x10 -> do
slot <- getInt16
item <- getSlot
return $ ServerBoundSetCreativeSlot slot item
0x11 -> do
windowId <- getInt8
enchantment <- getInt8
return $ ServerBoundEnchantItem windowId enchantment
0x12 -> do
location <- getPositionISI
text1 <- getText
text2 <- getText
text3 <- getText
text4 <- getText
return $ ServerBoundUpdateSign location text1 text2 text3 text4
0x13 -> do
flags <- getInt8
flyingSpeed <- getFloat
walkingSpeed <- getFloat
return $ ServerBoundAbilities flags flyingSpeed walkingSpeed
0x14 -> do
text <- getText
return $ ServerBoundTabComplete text
0x15 -> do
locale <- getText
viewDistance <- getInt8
chatFlags <- getInt8
chatColors <- getBool
difficulty <- getWord8
showCape <- getBool
return $ ServerBoundSettings locale viewDistance chatFlags chatColors difficulty showCape
0x16 -> do
payload <- getInt8
return $ ServerBoundClientCommand payload
0x17 -> do
channel <- getText
pData <- getBuffer
return $ ServerBoundCustomPayload channel pData
| oldmanmike/hs-minecraft-protocol | src/Data/Minecraft/Release17/Protocol.hs | bsd-3-clause | 41,010 | 25 | 17 | 11,442 | 10,707 | 4,748 | 5,959 | -1 | -1 |
module Queue (
Queue ,
queue ,
mqueue,
push,
pop,
popWhile,
runFold,
size,
) where
import Data.Foldable
-- A double ended queue which keeps track of a front and a back, as well as
-- an accumulation function. Inspired by https://people.cs.uct.ac.za/~ksmith/articles/sliding_window_minimum.html#sliding-window-minimum-algorithm
--
-- It uses Okasaki's two-stack implementation. The core idea is two maintain
-- a front and a back stack. At any point, each stack contains all its
-- elements as well as the partial accumulations up to that point. For
-- instance, if the accumulation function is (+), the stack might look like
-- [3,2,1] -> [(3,6), (2,3), (1,1)]
-- Holding all the partial sums alongside the elements of the stack.
-- That makes a perfectly good stack with partial sums, but how do we get a
-- FIFO queue with rolling sums?
-- The trick is two maintain two stacks, one is the front with elements
-- 'on the way in', and the other is the back with elements 'on the way out'.
-- That way, we have partial sums for both stacks and to calculate
-- the partial (or 'rolling') sum for the whole queue we just add the
-- top partial sums together.
-- Consider the list [1,2,3,4,2,1] (which is currently split in the middle)
-- [3,2,1] [1,2,4] -> [(3,6), (2,3), (1,1)] [(1,7), (2,6), (4,4)]
-- To grab the sum for the whole queue we just add 6 and 7 resulting in 13.
-- This property that the front and back partial sums sum to the final result
-- is invariant with pushes and pops. To convince yourself, try a pop:
-- [3,2,1] [2,4] -> [(3,6), (2,3), (1,1)] [(2,6), (4,4)]
-- Adding the partial sums gives 12.
--
-- The last key to the implementation is that pushes only affect the front
-- queue, and pops only affect the back queue. Except, if the back queue is
-- empty, we pop all the elements of the front queue and push them onto the
-- back queue, recalculating all the partial sums in between.
-- [(3,6), (2,3), (1,1)] []
-- -> [] [(1,6), (2,5), (3,3)]
-- This keeps the invariant that both stacks have their partial sums
-- calculated correctly!
--
-- This scheme happens to work for any commutative accumulation function!
-- So I have extended it to accept a user-provided function.
-- IMPORTANT: The accumulation function MUST be commutative or the whole
-- thing fails, since the algorithm rests on being able to combine the two
-- partial sums 'somewhere in the middle'. I am not aware of this algorithm
-- extending to arbitrary associative functions.
data Queue a = Queue
{ acc :: (a -> a -> a)
, sz :: Int
, front :: [(a, a)]
, back :: [(a, a)]
}
push :: a -> Queue a -> Queue a
push a (Queue f sz [] back) = Queue f (succ sz) [(a, a)] back
push a (Queue f sz ((x, y) : xs) back) = Queue f (succ sz) front back
where
front = (a, f a y) : (x, y) : xs
queue :: (a -> a -> a) -> Queue a
queue f = Queue f 0 [] []
-- queue implementation for a monoid
mqueue :: Monoid m => Queue m
mqueue = queue mappend
size :: Queue a -> Int
size = sz
pop :: Queue a -> Maybe (a, Queue a)
pop (Queue f sz [] []) = Nothing
pop (Queue f sz xs (y:ys)) = Just (fst y, Queue f (pred sz) xs ys)
-- When the back is empty, fill it with elements from the front.
-- This does two things, it reverses the elements (so the queue is FIFO)
-- and it recalculates the fold over the back end of the queue.
-- While this is an O(n) operation it is amortized O(1) since it only
-- happens once per element.
pop (Queue f sz xs []) = pop (Queue f sz [] (foldl' go [] xs))
where
go [] (a, _) = [(a, a)]
go ((y, b):ys) (a, _) = (a, f a b) : (y, b) : ys
popWhile :: (a -> Bool) -> Queue a -> Queue a
popWhile pred d@(Queue f sz _ _) = case pop d of
Nothing -> d
Just (a, d') -> if pred a
then popWhile pred d'
else d
-- Simulate running a foldl1 over the queue. Note that while it is
-- semantically the same as running a foldl1, performance-wise it is O(1)
-- since the partial updates have been being calculated all along.
runFold :: Queue a -> Maybe a
runFold (Queue _ _ [] []) = Nothing
runFold (Queue _ _ ((x,b):xs) []) = Just b
runFold (Queue _ _ [] ((y,c):ys)) = Just c
runFold (Queue f _ ((x,b):xs) ((y,c):ys)) = Just (f b c)
| charles-cooper/hroll | src/Queue.hs | bsd-3-clause | 4,255 | 0 | 11 | 946 | 883 | 494 | 389 | 42 | 3 |
module GPipeFPSMaterial where
import Graphics.GPipe
import qualified Data.ByteString.Char8 as SB
identityLight :: Float
identityLight = 1
data Entity
= Entity
{ eAmbientLight :: Vec4 (Vertex Float)
, eDirectedLight :: Vec4 (Vertex Float)
, eLightDir :: Vec3 (Vertex Float)
, eShaderRGBA :: Vec4 (Vertex Float)
}
data WaveType
= WT_Sin
| WT_Triangle
| WT_Square
| WT_Sawtooth
| WT_InverseSawtooth
| WT_Noise
data Wave = Wave WaveType Float Float Float Float
data Deform
= D_AutoSprite
| D_AutoSprite2
| D_Bulge Float Float Float
| D_Move (Vec3 Float) Wave
| D_Normal Float Float
| D_ProjectionShadow
| D_Text0
| D_Text1
| D_Text2
| D_Text3
| D_Text4
| D_Text5
| D_Text6
| D_Text7
| D_Wave Float Wave
data CommonAttrs
= CommonAttrs
{ caSkyParms :: () -- TODO
, caFogParms :: () -- TODO
, caPortal :: Bool
, caSort :: Int -- default: 3 or 6 depends on blend function
, caEntityMergable :: Bool
, caFogOnly :: Bool
, caCull :: () -- TODO, default = front
, caDeformVertexes :: [Deform]
, caNoMipMaps :: Bool
, caPolygonOffset :: Maybe Float
, caStages :: [StageAttrs]
}
defaultCommonAttrs :: CommonAttrs
defaultCommonAttrs = CommonAttrs
{ caSkyParms = ()
, caFogParms = ()
, caPortal = False
, caSort = 3
, caEntityMergable = False
, caFogOnly = False
, caCull = ()
, caDeformVertexes = []
, caNoMipMaps = False
, caPolygonOffset = Nothing
, caStages = []
}
data RGBGen
= RGB_Wave Wave
| RGB_Const Float Float Float
| RGB_Identity
| RGB_IdentityLighting
| RGB_Entity
| RGB_OneMinusEntity
| RGB_ExactVertex
| RGB_Vertex
| RGB_LightingDiffuse
| RGB_OneMinusVertex
data AlphaGen
= A_Wave Wave
| A_Const Float
| A_Portal
| A_Identity
| A_Entity
| A_OneMinusEntity
| A_Vertex
| A_LightingSpecular
| A_OneMinusVertex
data TCGen
= TG_Base
| TG_Lightmap
| TG_Environment -- TODO, check: RB_CalcEnvironmentTexCoords
| TG_Vector (Vec3 Float) (Vec3 Float)
data TCMod
= TM_EntityTranslate
| TM_Rotate Float
| TM_Scroll Float Float
| TM_Scale Float Float
| TM_Stretch Wave
| TM_Transform Float Float Float Float Float Float
| TM_Turb Float Float Float Float
data StageTexture
= ST_Map SB.ByteString
| ST_ClampMap SB.ByteString
| ST_AnimMap Float [SB.ByteString]
| ST_Lightmap
| ST_WhiteImage
data StageAttrs
= StageAttrs
{ saBlend :: Maybe (BlendingFactor,BlendingFactor)
, saRGBGen :: RGBGen
, saAlphaGen :: AlphaGen
, saTCGen :: TCGen
, saTCMod :: [TCMod]
, saTexture :: StageTexture
, saDepthWrite :: Bool
, saDepthFunc :: ComparisonFunction
, saAlphaFunc :: ()
}
defaultStageAttrs :: StageAttrs
defaultStageAttrs = StageAttrs
{ saBlend = Nothing
, saRGBGen = RGB_Identity
, saAlphaGen = A_Identity
, saTCGen = TG_Base
, saTCMod = []
, saTexture = ST_WhiteImage
, saDepthWrite = False
, saDepthFunc = Lequal
, saAlphaFunc = ()
}
fixAttribOrder ca = ca
{ caDeformVertexes = reverse $ caDeformVertexes ca
, caStages = reverse $ map fixStage $ caStages ca
}
where
fixStage sa = sa
{ saTCMod = reverse $ saTCMod sa
}
| csabahruska/GFXDemo | GPipeFPSMaterial.hs | bsd-3-clause | 3,629 | 0 | 11 | 1,193 | 809 | 489 | 320 | 128 | 1 |
module UI.Geometry where
import Control.Applicative (liftA, liftA2)
import Data.Functor.Classes
import Data.Functor.Listable
import Data.Semigroup
data Rect a = Rect { origin :: !(Point a), size :: !(Size a) }
deriving (Eq, Foldable, Functor, Ord, Traversable)
containsPoint :: Real a => Rect a -> Point a -> Bool
containsPoint r p = and (liftA2 (<=) (origin r) p) && and (liftA2 (<=) p (rectExtent r))
rectExtent :: Num a => Rect a -> Point a
rectExtent r = liftA2 (+) (origin r) (sizeExtent (size r))
data Point a = Point { x :: !a, y :: !a }
deriving (Eq, Foldable, Functor, Ord, Traversable)
pointSize :: Point a -> Size a
pointSize (Point x y) = Size x y
data Size a = Size { width :: !a, height :: !a }
deriving (Eq, Foldable, Functor, Ord, Traversable)
encloses :: Ord a => Size a -> Size a -> Bool
encloses a b = and ((>=) <$> a <*> b)
sizeExtent :: Size a -> Point a
sizeExtent (Size w h) = Point w h
-- Instances
instance Show1 Rect where
liftShowsPrec sp sl d (Rect origin size) = showsBinaryWith (liftShowsPrec sp sl) (liftShowsPrec sp sl) "Rect" d origin size
instance Show a => Show (Rect a) where
showsPrec = liftShowsPrec showsPrec showList
instance Eq1 Rect where
liftEq eq (Rect o1 s1) (Rect o2 s2) = liftEq eq o1 o2 && liftEq eq s1 s2
instance Listable1 Rect where
liftTiers t = liftCons2 (liftTiers t) (liftTiers t) Rect
instance Listable a => Listable (Rect a) where
tiers = tiers1
instance Applicative Point where
pure a = Point a a
Point f g <*> Point a b = Point (f a) (g b)
instance Show1 Point where
liftShowsPrec sp _ d (Point x y) = showsBinaryWith sp sp "Point" d x y
instance Show a => Show (Point a) where
showsPrec = liftShowsPrec showsPrec showList
instance Eq1 Point where
liftEq eq (Point x1 y1) (Point x2 y2) = eq x1 x2 && eq y1 y2
instance Listable1 Point where
liftTiers t = liftCons2 t t Point
instance Listable a => Listable (Point a) where
tiers = tiers1
instance Applicative Size where
pure a = Size a a
Size f g <*> Size a b = Size (f a) (g b)
instance Num a => Num (Size a) where
fromInteger = pure . fromInteger
abs = liftA abs
signum = liftA signum
negate = liftA negate
(+) = liftA2 (+)
(*) = liftA2 (*)
instance Semigroup a => Semigroup (Size a) where
(<>) = liftA2 (<>)
instance Monoid a => Monoid (Size a) where
mempty = pure mempty
mappend = liftA2 mappend
instance Show1 Size where
liftShowsPrec sp _ d (Size w h) = showsBinaryWith sp sp "Size" d w h
instance Show a => Show (Size a) where
showsPrec = liftShowsPrec showsPrec showList
instance Eq1 Size where
liftEq eq (Size w1 h1) (Size w2 h2) = eq w1 w2 && eq h1 h2
instance Listable1 Size where
liftTiers t = liftCons2 t t Size
instance Listable a => Listable (Size a) where
tiers = tiers1
| robrix/ui-effects | src/UI/Geometry.hs | bsd-3-clause | 2,792 | 0 | 11 | 609 | 1,270 | 638 | 632 | 81 | 1 |
-- | Half-memory implementation of symmetric matrices with
-- null-diagonal.
module Math.VectorSpaces.DistanceMatrix (
DistanceMatrix, RealDistanceMatrix, BooleanDistanceMatrix,
generate, (?), (!), Math.VectorSpaces.DistanceMatrix.map
) where
import qualified Data.Vector.Generic as GV
import qualified Data.Vector.Unboxed as UV
import qualified Math.Algebra.Monoid as M
data DistanceMatrix v a = C Int (v a)
type RealDistanceMatrix = DistanceMatrix UV.Vector Double
type BooleanDistanceMatrix = DistanceMatrix UV.Vector Bool
generate :: (GV.Vector v a, M.AdditiveMonoid a) => Int -> ((Int, Int) -> a) -> DistanceMatrix v a
generate n f = C n (GV.unfoldrN ((n*(n-1)) `quot` 2) helper (0,1))
where
helper (i, j)
| j == n-1 = Just (f (i, j), (i+1, i+2))
| otherwise = Just (f (i, j), (i, j+1))
-- | Indexing as if the matrix were infact square.
{-# INLINE (?) #-}
(?) :: (GV.Vector v a, M.AdditiveMonoid a) => DistanceMatrix v a -> (Int, Int) -> a
(C n x) ? (i,j)
| i == j = M.nil
| j < i = x GV.! (unroll n (j,i))
| otherwise = x GV.! (unroll n (i,j))
-- | Indexing in upper right triangle (off-diagonal) only.
{-# INLINE (!) #-}
(!) :: (GV.Vector v a) => DistanceMatrix v a -> (Int, Int) -> a
(C n x) ! (i,j) = x GV.! (unroll n (i,j))
map :: (GV.Vector v a, GV.Vector v b) => (a -> b) -> DistanceMatrix v a -> DistanceMatrix v b
map f (C n x) = C n (GV.map f x)
-- | Index unrolling.
{-# INLINE unroll #-}
unroll :: Int -> (Int, Int) -> Int
unroll n (i, j) = n*i + j - (((i+1)*(i+2)) `quot` 2)
| michiexile/hplex | pershom/src/Math/VectorSpaces/DistanceMatrix.hs | bsd-3-clause | 1,675 | 0 | 13 | 449 | 718 | 402 | 316 | 28 | 1 |
module Network.MtGoxAPI.DepthStore.Monitor
( monitorDepth
) where
import Control.Applicative
import Control.Concurrent
import Control.Monad
import Data.Maybe
import Text.Printf
import Network.MtGoxAPI.DepthStore
monitorDepth :: DepthStoreHandle -> IO ()
monitorDepth handle = forever $ do
putStrLn ""
putStrLn "-- Fees --"
simulateCircle handle $ 1* 10^(5::Integer)
simulateCircle handle $ 2 * 10^(5::Integer)
simulateCircle handle $ 5 * 10^(5::Integer)
simulateCircle handle $ 10 * 10^(5::Integer)
simulateCircle handle $ 15 * 10^(5::Integer)
simulateCircle handle $ 20 * 10^(5::Integer)
simulateCircle handle $ 100 * 10^(5::Integer)
simulateCircle handle $ 500 * 10^(5::Integer)
simulateCircle handle $ 1000 * 10^(5::Integer)
simulateCircle handle $ 2000 * 10^(5::Integer)
simulateCircle handle $ 5000 * 10^(5::Integer)
threadDelay $ 10 * 10^(6::Integer)
mtgoxFee :: Double
mtgoxFee = 0.006
afterMtgoxFee :: Integer -> Integer
afterMtgoxFee = round . (* (1 - mtgoxFee)) . fromIntegral
simulateCircle :: DepthStoreHandle -> Integer -> IO ()
simulateCircle handle usdAmount = do
btc <- fromMaybe 0 <$> simulateUSDSell handle usdAmount
let btc' = afterMtgoxFee btc
usd <- fromMaybe 0 <$> simulateBTCSell handle btc'
let usd' = afterMtgoxFee usd
cost = usdAmount - usd'
inPercent = if usdAmount > 0
then (fromIntegral cost * 100) / fromIntegral usdAmount
else 0
putStrLn $ formatUSD usdAmount ++ ": " ++ formatPercent (inPercent / 2)
++ " per transaction fee"
putStrLn $ "\tSell " ++ formatUSD usdAmount ++ " --> "
++ formatBTC btc ++ " --> after fees --> "
++ formatBTC btc' ++ " --> sell again\n\t --> "
++ formatUSD usd ++ " --> after fees --> "
++ formatUSD usd' ++ " --> fees in percent: "
++ formatPercent inPercent
formatUSD :: Integer -> String
formatUSD a =
let a' = fromIntegral a / 10 ^ (5 :: Integer) :: Double
in printf "%.5f EUR" a'
formatBTC :: Integer -> String
formatBTC a =
let a' = fromIntegral a / 10 ^ (8 :: Integer) :: Double
in printf "%.8f BTC" a'
formatPercent :: Double -> String
formatPercent = printf "%.2f %%"
| javgh/mtgoxapi | Network/MtGoxAPI/DepthStore/Monitor.hs | bsd-3-clause | 2,311 | 0 | 18 | 594 | 767 | 385 | 382 | 56 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeOperators #-}
module Serv.Server.Core.Runtime
( runCore
) where
import Control.Lens
import Control.Monad.Except
import Control.Monad.Reader (ReaderT, runReaderT)
import Control.Monad.Reader.Class
import Data.Aeson.Encode.Pretty (encodePretty)
import qualified Data.ByteString.Lazy.Char8 as BL8
import Data.Text.Encoding (encodeUtf8)
import Network.Wai (Application)
import Network.Wai.Handler.Warp (run)
import qualified Network.Wai.Handler.Warp as WP
import Network.Wai.Metrics
import qualified Network.Wai.Middleware.Cors as CS
import qualified Network.Wai.Middleware.Gzip as GZ
import Network.Wai.Middleware.RequestLogger
import qualified Network.Wai.Middleware.StripHeaders as SH
import Serv.Api
import Serv.Api.Types
import Serv.Server.Core.Config
import qualified Serv.Server.Core.Config as Cfg
import Serv.Server.Core.HealthApi
import Serv.Server.Core.HealthHandler
import Serv.Server.Core.InfoApi
import Serv.Server.Core.ManagmentAuth
import Serv.Server.Core.Metrics
import Serv.Server.Core.MetricsApi
import Serv.Server.Core.MetricsHandler
import Serv.Server.Features.EntityHandler
import Serv.Server.ServerEnv
import Servant
import Servant.Extentions.Server
import System.Log.FastLogger
-- | System API: info, health, metrics
type SysApi = InfoApi :<|> HealthApi :<|> MetricsApi
coreServer :: ServerEnv -> Server SysApi
coreServer serverEnv = handleInfo serverEnv :<|> handleHealth serverEnv :<|> handleMetrics serverEnv
coreApp :: ServerEnv -> Application
coreApp serverEnv@ServerEnv{..} = serveWithContextEx (Proxy :: Proxy SysApi) (managementAuthContext (managementConf serverConfig)) (coreServer serverEnv)
runCore :: ServerEnv -> IO ()
runCore serverEnv@ServerEnv{..} = do
putStrLn ("[Sys] Listening on " ++ show port)
WP.runSettings settings $ middleware $ coreApp serverEnv
where
middleware = GZ.gzip GZ.def . CS.simpleCors
settings = WP.setServerName (encodeUtf8(serverName (serverConf serverConfig))) . WP.setPort port $ WP.defaultSettings
port = Cfg.port (managementConf serverConfig)
| orangefiredragon/bear | src/Serv/Server/Core/Runtime.hs | bsd-3-clause | 2,550 | 0 | 15 | 639 | 519 | 313 | 206 | 49 | 1 |
{-# LINE 1 "GHC.Conc.Signal.hs" #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}
module GHC.Conc.Signal
( Signal
, HandlerFun
, setHandler
, runHandlers
, runHandlersPtr
) where
import Control.Concurrent.MVar (MVar, newMVar, withMVar)
import Data.Dynamic (Dynamic)
import Foreign.C.Types (CInt)
import Foreign.ForeignPtr (ForeignPtr, newForeignPtr)
import Foreign.StablePtr (castPtrToStablePtr, castStablePtrToPtr,
deRefStablePtr, freeStablePtr, newStablePtr)
import Foreign.Ptr (Ptr, castPtr)
import Foreign.Marshal.Alloc (finalizerFree)
import GHC.Arr (inRange)
import GHC.Base
import GHC.Conc.Sync (forkIO)
import GHC.IO (mask_, unsafePerformIO)
import GHC.IOArray (IOArray, boundsIOArray, newIOArray,
unsafeReadIOArray, unsafeWriteIOArray)
import GHC.Real (fromIntegral)
import GHC.Word (Word8)
------------------------------------------------------------------------
-- Signal handling
type Signal = CInt
maxSig :: Int
maxSig = 64
type HandlerFun = ForeignPtr Word8 -> IO ()
-- Lock used to protect concurrent access to signal_handlers. Symptom
-- of this race condition is GHC bug #1922, although that bug was on
-- Windows a similar bug also exists on Unix.
signal_handlers :: MVar (IOArray Int (Maybe (HandlerFun,Dynamic)))
signal_handlers = unsafePerformIO $ do
arr <- newIOArray (0, maxSig) Nothing
m <- newMVar arr
sharedCAF m getOrSetGHCConcSignalSignalHandlerStore
{-# NOINLINE signal_handlers #-}
foreign import ccall unsafe "getOrSetGHCConcSignalSignalHandlerStore"
getOrSetGHCConcSignalSignalHandlerStore :: Ptr a -> IO (Ptr a)
setHandler :: Signal -> Maybe (HandlerFun, Dynamic)
-> IO (Maybe (HandlerFun, Dynamic))
setHandler sig handler = do
let int = fromIntegral sig
withMVar signal_handlers $ \arr ->
if not (inRange (boundsIOArray arr) int)
then errorWithoutStackTrace "GHC.Conc.setHandler: signal out of range"
else do old <- unsafeReadIOArray arr int
unsafeWriteIOArray arr int handler
return old
runHandlers :: ForeignPtr Word8 -> Signal -> IO ()
runHandlers p_info sig = do
let int = fromIntegral sig
withMVar signal_handlers $ \arr ->
if not (inRange (boundsIOArray arr) int)
then return ()
else do handler <- unsafeReadIOArray arr int
case handler of
Nothing -> return ()
Just (f,_) -> do _ <- forkIO (f p_info)
return ()
-- It is our responsibility to free the memory buffer, so we create a
-- foreignPtr.
runHandlersPtr :: Ptr Word8 -> Signal -> IO ()
runHandlersPtr p s = do
fp <- newForeignPtr finalizerFree p
runHandlers fp s
-- Machinery needed to ensure that we only have one copy of certain
-- CAFs in this module even when the base package is present twice, as
-- it is when base is dynamically loaded into GHCi. The RTS keeps
-- track of the single true value of the CAF, so even when the CAFs in
-- the dynamically-loaded base package are reverted, nothing bad
-- happens.
--
sharedCAF :: a -> (Ptr a -> IO (Ptr a)) -> IO a
sharedCAF a get_or_set =
mask_ $ do
stable_ref <- newStablePtr a
let ref = castPtr (castStablePtrToPtr stable_ref)
ref2 <- get_or_set ref
if ref == ref2
then return a
else do freeStablePtr stable_ref
deRefStablePtr (castPtrToStablePtr (castPtr ref2))
| phischu/fragnix | builtins/base/GHC.Conc.Signal.hs | bsd-3-clause | 3,458 | 0 | 20 | 769 | 824 | 432 | 392 | 71 | 3 |
module Main where
import System.Environment
import Arion.Runner
main :: IO ()
main = getArgs >>= run
| saturday06/arion | src/Main.hs | mit | 103 | 0 | 6 | 18 | 33 | 19 | 14 | 5 | 1 |
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
import Data.Foldable (for_)
import Test.Hspec (Spec, describe, it, shouldBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)
import Triangle
( TriangleType ( Equilateral
, Illegal
, Isosceles
, Scalene
)
, triangleType
)
main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs
specs :: Spec
specs = describe "triangle" $
describe "triangleType" $ for_ cases test
where
test (description, (a, b, c), expected) = it description assertion
where
assertion = triangleType a b c `shouldBe` expected
-- Test cases adapted from `exercism/x-common/triangle.json` on 2016-08-03.
cases = [ ( "equilateral triangle has all sides equal"
, (2, 2, 2)
, Equilateral
)
, ( "larger equilateral triangle"
, (10, 10, 10)
, Equilateral
)
, ( "isosceles triangle with last two sides equal"
, (3, 4, 4)
, Isosceles
)
, ( "isosceles triangle with first two sides equal"
, (4, 4, 3)
, Isosceles
)
, ( "isosceles triangle with first and last sides equal"
, (4, 3, 4)
, Isosceles
)
, ( "isosceles triangle with unequal side larger than equal sides"
, (4, 7, 4)
, Isosceles
)
, ( "scalene triangle has no equal sides"
, (3, 4, 5)
, Scalene
)
, ( "larger scalene triangle"
, (10, 11, 12)
, Scalene
)
, ( "scalene triangle with sides in descending order"
, (5, 4, 2)
, Scalene
)
, ( "small scalene triangle with floating point values"
, (0.4, 0.6, 0.3)
, Scalene
)
, ( "a triangle violating the triangle inequality is illegal"
, (7, 3, 2)
, Illegal
)
, ( "two sides equal, but still violates triangle inequality"
, (1, 1, 3)
, Illegal
)
, ( "triangles with all sides zero are illegal"
, (0, 0, 0)
, Illegal
)
]
| xTVaser/Exercism-Solutions | haskell/triangle/test/Tests.hs | mit | 2,496 | 0 | 8 | 1,126 | 465 | 291 | 174 | 56 | 1 |
module Main where
import HTrees
import Control.Monad.IO.Class
import Data.CSV.Conduit
import Data.List
import qualified Data.Map.Lazy as Map
import Data.Maybe
import Data.Vector (Vector, fromList, toList, (!))
import System.Environment (getArgs)
-- Main
main :: IO ()
main = do
args <- getArgs
let filename = head args
-- Read and parse the data set
putStr $ "Reading " ++ filename ++ "... "
dataset <- readDataset filename
putStrLn $ (show . length . examples $ dataset) ++ " samples."
-- Construct a tree
putStr "Builing tree..."
let config = Config {
maxDepth = 30,
minNodeSize = 20,
leafModel = meanModel,
stat = Stat { aggregator = toMoment, summary = variance } }
let tree = buildWith config dataset
putStrLn "Done!"
putStrLn $ show tree
-- Evaluation the tree on the training set
putStrLn "Evaluating ..."
let evaluation = evaluate squareLoss tree (examples dataset)
putStrLn $ "MSE = " ++ show evaluation
-- Reads in the "SSV" (semi-colon separated) file and turn it into data
readDataset :: MonadIO m => FilePath -> m (DataSet Double)
readDataset filename = do
csv <- readCSVFile defCSVSettings { csvSep = ';' } filename
let (names, instances) = parseInstances (toList csv)
let keys = delete "quality" names
let attrs = [ Attr k (! (fromJust . elemIndex k $ names)) | k <- keys ]
let target = (! (fromJust . elemIndex "quality" $ names))
return $ DS attrs (makeExamplesWith target instances)
makeExamplesWith :: (Instance -> l) -> [Instance] -> [Example l]
makeExamplesWith f is = [ Ex i (f i) | i <- is ]
--------------------------------------------------------------------------------
-- Data IO and other wrangling
parseInstances :: [MapRow String] -> ([String], [Vector Double])
parseInstances rows = (names, instances)
where
names = Map.keys . head $ rows
instances = map (makeInstance names) rows
makeInstance :: [String] -> MapRow String -> Instance
makeInstance names row = fromList . map (makeValue . fromJust . flip Map.lookup row) $ names
makeValue :: String -> Double
makeValue s = case reads s :: [(Double, String)] of
[(v, "")] -> v
_ -> error $ "Could not parse '" ++ s ++ "' as Double"
-- Wine data set columns:
-- "fixed acidity";
-- "volatile acidity";
-- "citric acid";
-- "residual sugar";
-- "chlorides";
-- "free sulfur dioxide";
-- "total sulfur dioxide";
-- "density";
-- "pH";
-- "sulphates";
-- "alcohol";
-- "quality"
| mreid/HTrees | src/run.hs | mit | 2,545 | 0 | 16 | 576 | 749 | 399 | 350 | 48 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-
Copyright (C) 2006-2014 John MacFarlane <jgm@berkeley.edu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.Writers.RST
Copyright : Copyright (C) 2006-2014 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley.edu>
Stability : alpha
Portability : portable
Conversion of 'Pandoc' documents to reStructuredText.
reStructuredText: <http://docutils.sourceforge.net/rst.html>
-}
module Text.Pandoc.Writers.RST ( writeRST ) where
import Text.Pandoc.Definition
import Text.Pandoc.Options
import Text.Pandoc.Shared
import Text.Pandoc.Writers.Shared
import Text.Pandoc.Templates (renderTemplate')
import Text.Pandoc.Builder (deleteMeta)
import Data.Maybe (fromMaybe)
import Data.List ( isPrefixOf, stripPrefix, intersperse, transpose )
import Network.URI (isURI)
import Text.Pandoc.Pretty
import Control.Monad.State
import Control.Applicative ( (<$>) )
import Data.Char (isSpace, toLower)
type Refs = [([Inline], Target)]
data WriterState =
WriterState { stNotes :: [[Block]]
, stLinks :: Refs
, stImages :: [([Inline], (String, String, Maybe String))]
, stHasMath :: Bool
, stOptions :: WriterOptions
}
-- | Convert Pandoc to RST.
writeRST :: WriterOptions -> Pandoc -> String
writeRST opts document =
let st = WriterState { stNotes = [], stLinks = [],
stImages = [], stHasMath = False,
stOptions = opts }
in evalState (pandocToRST document) st
-- | Return RST representation of document.
pandocToRST :: Pandoc -> State WriterState String
pandocToRST (Pandoc meta blocks) = do
opts <- liftM stOptions get
let colwidth = if writerWrapText opts
then Just $ writerColumns opts
else Nothing
let subtit = case lookupMeta "subtitle" meta of
Just (MetaBlocks [Plain xs]) -> xs
_ -> []
title <- titleToRST (docTitle meta) subtit
metadata <- metaToJSON opts
(fmap (render colwidth) . blockListToRST)
(fmap (trimr . render colwidth) . inlineListToRST)
$ deleteMeta "title" $ deleteMeta "subtitle" meta
body <- blockListToRST blocks
notes <- liftM (reverse . stNotes) get >>= notesToRST
-- note that the notes may contain refs, so we do them first
refs <- liftM (reverse . stLinks) get >>= refsToRST
pics <- liftM (reverse . stImages) get >>= pictRefsToRST
hasMath <- liftM stHasMath get
let main = render colwidth $ foldl ($+$) empty $ [body, notes, refs, pics]
let context = defField "body" main
$ defField "toc" (writerTableOfContents opts)
$ defField "toc-depth" (writerTOCDepth opts)
$ defField "math" hasMath
$ defField "title" (render Nothing title :: String)
$ defField "math" hasMath
$ metadata
if writerStandalone opts
then return $ renderTemplate' (writerTemplate opts) context
else return main
-- | Return RST representation of reference key table.
refsToRST :: Refs -> State WriterState Doc
refsToRST refs = mapM keyToRST refs >>= return . vcat
-- | Return RST representation of a reference key.
keyToRST :: ([Inline], (String, String))
-> State WriterState Doc
keyToRST (label, (src, _)) = do
label' <- inlineListToRST label
let label'' = if ':' `elem` (render Nothing label')
then char '`' <> label' <> char '`'
else label'
return $ nowrap $ ".. _" <> label'' <> ": " <> text src
-- | Return RST representation of notes.
notesToRST :: [[Block]] -> State WriterState Doc
notesToRST notes =
mapM (\(num, note) -> noteToRST num note) (zip [1..] notes) >>=
return . vsep
-- | Return RST representation of a note.
noteToRST :: Int -> [Block] -> State WriterState Doc
noteToRST num note = do
contents <- blockListToRST note
let marker = ".. [" <> text (show num) <> "]"
return $ nowrap $ marker $$ nest 3 contents
-- | Return RST representation of picture reference table.
pictRefsToRST :: [([Inline], (String, String, Maybe String))]
-> State WriterState Doc
pictRefsToRST refs = mapM pictToRST refs >>= return . vcat
-- | Return RST representation of a picture substitution reference.
pictToRST :: ([Inline], (String, String,Maybe String))
-> State WriterState Doc
pictToRST (label, (src, _, mbtarget)) = do
label' <- inlineListToRST label
return $ nowrap
$ ".. |" <> label' <> "| image:: " <> text src
$$ case mbtarget of
Nothing -> empty
Just t -> " :target: " <> text t
-- | Escape special characters for RST.
escapeString :: String -> String
escapeString = escapeStringUsing (backslashEscapes "`\\|*_")
titleToRST :: [Inline] -> [Inline] -> State WriterState Doc
titleToRST [] _ = return empty
titleToRST tit subtit = do
title <- inlineListToRST tit
subtitle <- inlineListToRST subtit
return $ bordered title '=' $$ bordered subtitle '-'
bordered :: Doc -> Char -> Doc
bordered contents c =
if len > 0
then border $$ contents $$ border
else empty
where len = offset contents
border = text (replicate len c)
-- | Convert Pandoc block element to RST.
blockToRST :: Block -- ^ Block element
-> State WriterState Doc
blockToRST Null = return empty
blockToRST (Div attr bs) = do
contents <- blockListToRST bs
let startTag = ".. raw:: html" $+$ nest 3 (tagWithAttrs "div" attr)
let endTag = ".. raw:: html" $+$ nest 3 "</div>"
return $ blankline <> startTag $+$ contents $+$ endTag $$ blankline
blockToRST (Plain inlines) = inlineListToRST inlines
-- title beginning with fig: indicates that the image is a figure
blockToRST (Para [Image txt (src,'f':'i':'g':':':tit)]) = do
capt <- inlineListToRST txt
let fig = "figure:: " <> text src
let alt = ":alt: " <> if null tit then capt else text tit
return $ hang 3 ".. " (fig $$ alt $+$ capt) $$ blankline
blockToRST (Para inlines)
| LineBreak `elem` inlines = do -- use line block if LineBreaks
lns <- mapM inlineListToRST $ splitBy (==LineBreak) inlines
return $ (vcat $ map (hang 2 (text "| ")) lns) <> blankline
| otherwise = do
contents <- inlineListToRST inlines
return $ contents <> blankline
blockToRST (RawBlock f@(Format f') str)
| f == "rst" = return $ text str
| otherwise = return $ blankline <> ".. raw:: " <>
text (map toLower f') $+$
(nest 3 $ text str) $$ blankline
blockToRST HorizontalRule =
return $ blankline $$ "--------------" $$ blankline
blockToRST (Header level _ inlines) = do
contents <- inlineListToRST inlines
let headerChar = if level > 5 then ' ' else "=-~^'" !! (level - 1)
let border = text $ replicate (offset contents) headerChar
return $ nowrap $ contents $$ border $$ blankline
blockToRST (CodeBlock (_,classes,kvs) str) = do
opts <- stOptions <$> get
let tabstop = writerTabStop opts
let startnum = maybe "" (\x -> " " <> text x) $ lookup "startFrom" kvs
let numberlines = if "numberLines" `elem` classes
then " :number-lines:" <> startnum
else empty
if "haskell" `elem` classes && "literate" `elem` classes &&
isEnabled Ext_literate_haskell opts
then return $ prefixed "> " (text str) $$ blankline
else return $
(case [c | c <- classes,
c `notElem` ["sourceCode","literate","numberLines"]] of
[] -> "::"
(lang:_) -> (".. code:: " <> text lang) $$ numberlines)
$+$ nest tabstop (text str) $$ blankline
blockToRST (BlockQuote blocks) = do
tabstop <- get >>= (return . writerTabStop . stOptions)
contents <- blockListToRST blocks
return $ (nest tabstop contents) <> blankline
blockToRST (Table caption _ widths headers rows) = do
caption' <- inlineListToRST caption
let caption'' = if null caption
then empty
else blankline <> text "Table: " <> caption'
headers' <- mapM blockListToRST headers
rawRows <- mapM (mapM blockListToRST) rows
-- let isSimpleCell [Plain _] = True
-- isSimpleCell [Para _] = True
-- isSimpleCell [] = True
-- isSimpleCell _ = False
-- let isSimple = all (==0) widths && all (all isSimpleCell) rows
let numChars = maximum . map offset
opts <- get >>= return . stOptions
let widthsInChars =
if all (== 0) widths
then map ((+2) . numChars) $ transpose (headers' : rawRows)
else map (floor . (fromIntegral (writerColumns opts) *)) widths
let hpipeBlocks blocks = hcat [beg, middle, end]
where h = maximum (map height blocks)
sep' = lblock 3 $ vcat (map text $ replicate h " | ")
beg = lblock 2 $ vcat (map text $ replicate h "| ")
end = lblock 2 $ vcat (map text $ replicate h " |")
middle = hcat $ intersperse sep' blocks
let makeRow = hpipeBlocks . zipWith lblock widthsInChars
let head' = makeRow headers'
let rows' = map makeRow rawRows
let border ch = char '+' <> char ch <>
(hcat $ intersperse (char ch <> char '+' <> char ch) $
map (\l -> text $ replicate l ch) widthsInChars) <>
char ch <> char '+'
let body = vcat $ intersperse (border '-') rows'
let head'' = if all null headers
then empty
else head' $$ border '='
return $ border '-' $$ head'' $$ body $$ border '-' $$ caption'' $$ blankline
blockToRST (BulletList items) = do
contents <- mapM bulletListItemToRST items
-- ensure that sublists have preceding blank line
return $ blankline $$ chomp (vcat contents) $$ blankline
blockToRST (OrderedList (start, style', delim) items) = do
let markers = if start == 1 && style' == DefaultStyle && delim == DefaultDelim
then take (length items) $ repeat "#."
else take (length items) $ orderedListMarkers
(start, style', delim)
let maxMarkerLength = maximum $ map length markers
let markers' = map (\m -> let s = maxMarkerLength - length m
in m ++ replicate s ' ') markers
contents <- mapM (\(item, num) -> orderedListItemToRST item num) $
zip markers' items
-- ensure that sublists have preceding blank line
return $ blankline $$ chomp (vcat contents) $$ blankline
blockToRST (DefinitionList items) = do
contents <- mapM definitionListItemToRST items
-- ensure that sublists have preceding blank line
return $ blankline $$ chomp (vcat contents) $$ blankline
-- | Convert bullet list item (list of blocks) to RST.
bulletListItemToRST :: [Block] -> State WriterState Doc
bulletListItemToRST items = do
contents <- blockListToRST items
return $ hang 3 "- " $ contents <> cr
-- | Convert ordered list item (a list of blocks) to RST.
orderedListItemToRST :: String -- ^ marker for list item
-> [Block] -- ^ list item (list of blocks)
-> State WriterState Doc
orderedListItemToRST marker items = do
contents <- blockListToRST items
let marker' = marker ++ " "
return $ hang (length marker') (text marker') $ contents <> cr
-- | Convert defintion list item (label, list of blocks) to RST.
definitionListItemToRST :: ([Inline], [[Block]]) -> State WriterState Doc
definitionListItemToRST (label, defs) = do
label' <- inlineListToRST label
contents <- liftM vcat $ mapM blockListToRST defs
tabstop <- get >>= (return . writerTabStop . stOptions)
return $ label' $$ nest tabstop (nestle contents <> cr)
-- | Convert list of Pandoc block elements to RST.
blockListToRST :: [Block] -- ^ List of block elements
-> State WriterState Doc
blockListToRST blocks = mapM blockToRST blocks >>= return . vcat
-- | Convert list of Pandoc inline elements to RST.
inlineListToRST :: [Inline] -> State WriterState Doc
inlineListToRST lst =
mapM inlineToRST (removeSpaceAfterDisplayMath $ insertBS lst) >>= return . hcat
where -- remove spaces after displaymath, as they screw up indentation:
removeSpaceAfterDisplayMath (Math DisplayMath x : zs) =
Math DisplayMath x : dropWhile (==Space) zs
removeSpaceAfterDisplayMath (x:xs) = x : removeSpaceAfterDisplayMath xs
removeSpaceAfterDisplayMath [] = []
insertBS :: [Inline] -> [Inline] -- insert '\ ' where needed
insertBS (x:y:z:zs)
| isComplex y && surroundComplex x z =
x : y : RawInline "rst" "\\ " : insertBS (z:zs)
insertBS (x:y:zs)
| isComplex x && not (okAfterComplex y) =
x : RawInline "rst" "\\ " : insertBS (y : zs)
| isComplex y && not (okBeforeComplex x) =
x : RawInline "rst" "\\ " : insertBS (y : zs)
| otherwise =
x : insertBS (y : zs)
insertBS (x:ys) = x : insertBS ys
insertBS [] = []
surroundComplex :: Inline -> Inline -> Bool
surroundComplex (Str s@(_:_)) (Str s'@(_:_)) =
case (last s, head s') of
('\'','\'') -> True
('"','"') -> True
('<','>') -> True
('[',']') -> True
('{','}') -> True
_ -> False
surroundComplex _ _ = False
okAfterComplex :: Inline -> Bool
okAfterComplex Space = True
okAfterComplex LineBreak = True
okAfterComplex (Str (c:_)) = isSpace c || c `elem` "-.,:;!?\\/'\")]}>–—"
okAfterComplex _ = False
okBeforeComplex :: Inline -> Bool
okBeforeComplex Space = True
okBeforeComplex LineBreak = True
okBeforeComplex (Str (c:_)) = isSpace c || c `elem` "-:/'\"<([{–—"
okBeforeComplex _ = False
isComplex :: Inline -> Bool
isComplex (Emph _) = True
isComplex (Strong _) = True
isComplex (SmallCaps _) = True
isComplex (Strikeout _) = True
isComplex (Superscript _) = True
isComplex (Subscript _) = True
isComplex (Link _ _) = True
isComplex (Image _ _) = True
isComplex (Code _ _) = True
isComplex (Math _ _) = True
isComplex _ = False
-- | Convert Pandoc inline element to RST.
inlineToRST :: Inline -> State WriterState Doc
inlineToRST (Span _ ils) = inlineListToRST ils
inlineToRST (Emph lst) = do
contents <- inlineListToRST lst
return $ "*" <> contents <> "*"
inlineToRST (Strong lst) = do
contents <- inlineListToRST lst
return $ "**" <> contents <> "**"
inlineToRST (Strikeout lst) = do
contents <- inlineListToRST lst
return $ "[STRIKEOUT:" <> contents <> "]"
inlineToRST (Superscript lst) = do
contents <- inlineListToRST lst
return $ ":sup:`" <> contents <> "`"
inlineToRST (Subscript lst) = do
contents <- inlineListToRST lst
return $ ":sub:`" <> contents <> "`"
inlineToRST (SmallCaps lst) = inlineListToRST lst
inlineToRST (Quoted SingleQuote lst) = do
contents <- inlineListToRST lst
return $ "‘" <> contents <> "’"
inlineToRST (Quoted DoubleQuote lst) = do
contents <- inlineListToRST lst
return $ "“" <> contents <> "”"
inlineToRST (Cite _ lst) =
inlineListToRST lst
inlineToRST (Code _ str) = return $ "``" <> text str <> "``"
inlineToRST (Str str) = return $ text $ escapeString str
inlineToRST (Math t str) = do
modify $ \st -> st{ stHasMath = True }
return $ if t == InlineMath
then ":math:`" <> text str <> "`"
else if '\n' `elem` str
then blankline $$ ".. math::" $$
blankline $$ nest 3 (text str) $$ blankline
else blankline $$ (".. math:: " <> text str) $$ blankline
inlineToRST (RawInline f x)
| f == "rst" = return $ text x
| otherwise = return empty
inlineToRST (LineBreak) = return cr -- there's no line break in RST (see Para)
inlineToRST Space = return space
-- autolink
inlineToRST (Link [Str str] (src, _))
| isURI src &&
if "mailto:" `isPrefixOf` src
then src == escapeURI ("mailto:" ++ str)
else src == escapeURI str = do
let srcSuffix = fromMaybe src (stripPrefix "mailto:" src)
return $ text srcSuffix
inlineToRST (Link [Image alt (imgsrc,imgtit)] (src, _tit)) = do
label <- registerImage alt (imgsrc,imgtit) (Just src)
return $ "|" <> label <> "|"
inlineToRST (Link txt (src, tit)) = do
useReferenceLinks <- get >>= return . writerReferenceLinks . stOptions
linktext <- inlineListToRST $ normalizeSpaces txt
if useReferenceLinks
then do refs <- get >>= return . stLinks
case lookup txt refs of
Just (src',tit') ->
if src == src' && tit == tit'
then return $ "`" <> linktext <> "`_"
else do -- duplicate label, use non-reference link
return $ "`" <> linktext <> " <" <> text src <> ">`__"
Nothing -> do
modify $ \st -> st { stLinks = (txt,(src,tit)):refs }
return $ "`" <> linktext <> "`_"
else return $ "`" <> linktext <> " <" <> text src <> ">`__"
inlineToRST (Image alternate (source, tit)) = do
label <- registerImage alternate (source,tit) Nothing
return $ "|" <> label <> "|"
inlineToRST (Note contents) = do
-- add to notes in state
notes <- gets stNotes
modify $ \st -> st { stNotes = contents:notes }
let ref = show $ (length notes) + 1
return $ " [" <> text ref <> "]_"
registerImage :: [Inline] -> Target -> Maybe String -> State WriterState Doc
registerImage alt (src,tit) mbtarget = do
pics <- get >>= return . stImages
txt <- case lookup alt pics of
Just (s,t,mbt) | (s,t,mbt) == (src,tit,mbtarget) -> return alt
_ -> do
let alt' = if null alt || alt == [Str ""]
then [Str $ "image" ++ show (length pics)]
else alt
modify $ \st -> st { stImages =
(alt', (src,tit, mbtarget)):stImages st }
return alt'
inlineListToRST txt
| rgaiacs/pandoc | src/Text/Pandoc/Writers/RST.hs | gpl-2.0 | 18,955 | 0 | 21 | 5,217 | 5,842 | 2,933 | 2,909 | 364 | 28 |
-- Voting algorithm example from chapter 7 of Programming in Haskell,
-- Graham Hutton, Cambridge University Press, 2016.
import Data.List
-- First past the post
votes :: [String]
votes = ["Red", "Blue", "Green", "Blue", "Blue", "Red"]
count :: Eq a => a -> [a] -> Int
count x = length . filter (== x)
rmdups :: Eq a => [a] -> [a]
rmdups [] = []
rmdups (x:xs) = x : filter (/= x) (rmdups xs)
result :: Ord a => [a] -> [(Int, a)]
result vs = sort [(count v vs, v) | v <- rmdups vs]
winner :: Ord a => [a] -> a
winner = snd . last . result
-- Alternative vote
ballots :: [[String]]
ballots = [["Red","Green"],
["Blue"],
["Green","Red","Blue"],
["Blue","Green","Red"],
["Green"]]
rmempty :: Eq a => [[a]] -> [[a]]
rmempty = filter (/= [])
elim :: Eq a => a -> [[a]] -> [[a]]
elim x = map (filter (/= x))
rank :: Ord a => [[a]] -> [a]
rank = map snd . result . map head
winner' :: Ord a => [[a]] -> a
winner' bs = case rank (rmempty bs) of
[c] -> c
(c:cs) -> winner' (elim c bs)
| thalerjonathan/phd | coding/learning/haskell/grahambook/Code_Solutions/voting.hs | gpl-3.0 | 1,071 | 0 | 10 | 294 | 523 | 291 | 232 | 28 | 2 |
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE CPP #-}
module Foundation.Collection.Copy
( Copy(..)
) where
import GHC.ST (runST)
import Basement.Compat.Base ((>>=))
import Basement.Nat
import Basement.Types.OffsetSize
import qualified Basement.Block as BLK
import qualified Basement.UArray as UA
import qualified Basement.BoxedArray as BA
import qualified Basement.String as S
#if MIN_VERSION_base(4,9,0)
import qualified Basement.Sized.Block as BLKN
import qualified Basement.Sized.List as LN
#endif
class Copy a where
copy :: a -> a
instance Copy [ty] where
copy a = a
instance UA.PrimType ty => Copy (BLK.Block ty) where
copy blk = runST (BLK.thaw blk >>= BLK.unsafeFreeze)
instance UA.PrimType ty => Copy (UA.UArray ty) where
copy = UA.copy
instance Copy (BA.Array ty) where
copy = BA.copy
instance Copy S.String where
copy = S.copy
#if MIN_VERSION_base(4,9,0)
instance Copy (LN.ListN n ty) where
copy a = a
instance (Countable ty n, UA.PrimType ty, KnownNat n) => Copy (BLKN.BlockN n ty) where
copy blk = runST (BLKN.thaw blk >>= BLKN.freeze)
#endif
| vincenthz/hs-foundation | foundation/Foundation/Collection/Copy.hs | bsd-3-clause | 1,146 | 0 | 10 | 237 | 359 | 204 | 155 | 24 | 0 |
{-# OPTIONS_GHC -Wall #-}
module Optimize.Case (optimize) where
import Control.Arrow (second)
import qualified Data.Map as Map
import Data.Map ((!))
import qualified Data.Maybe as Maybe
import qualified AST.Expression.Optimized as Opt
import qualified AST.Pattern as P
import qualified Optimize.DecisionTree as DT
-- OPTIMIZE A CASE EXPRESSION
optimize :: DT.VariantDict -> String -> [(P.Canonical, Opt.Expr)] -> Opt.Expr
optimize variantDict exprName optBranches =
let
(patterns, indexedBranches) =
unzip (zipWith indexify [0..] optBranches)
decisionTree =
DT.compile variantDict patterns
in
treeToExpr exprName decisionTree indexedBranches
indexify :: Int -> (a,b) -> ((a,Int), (Int,b))
indexify index (pattern, branch) =
( (pattern, index)
, (index, branch)
)
-- CONVERT A TREE TO AN EXPRESSION
treeToExpr :: String -> DT.DecisionTree -> [(Int, Opt.Expr)] -> Opt.Expr
treeToExpr name decisionTree allJumps =
let
decider =
treeToDecider decisionTree
targetCounts =
countTargets decider
(choices, maybeJumps) =
unzip (map (createChoices targetCounts) allJumps)
in
Opt.Case
name
(insertChoices (Map.fromList choices) decider)
(Maybe.catMaybes maybeJumps)
-- TREE TO DECIDER
--
-- Decision trees may have some redundancies, so we convert them to a Decider
-- which has special constructs to avoid code duplication when possible.
treeToDecider :: DT.DecisionTree -> Opt.Decider Int
treeToDecider tree =
case tree of
DT.Match target ->
Opt.Leaf target
-- zero options
DT.Decision _ [] Nothing ->
error "compiler bug, somehow created an empty decision tree"
-- one option
DT.Decision _ [(_, subTree)] Nothing ->
treeToDecider subTree
DT.Decision _ [] (Just subTree) ->
treeToDecider subTree
-- two options
DT.Decision path [(test, successTree)] (Just failureTree) ->
toChain path test successTree failureTree
DT.Decision path [(test, successTree), (_, failureTree)] Nothing ->
toChain path test successTree failureTree
-- many options
DT.Decision path edges Nothing ->
let
(necessaryTests, fallback) =
(init edges, snd (last edges))
in
Opt.FanOut
path
(map (second treeToDecider) necessaryTests)
(treeToDecider fallback)
DT.Decision path edges (Just fallback) ->
Opt.FanOut path (map (second treeToDecider) edges) (treeToDecider fallback)
toChain :: DT.Path -> DT.Test -> DT.DecisionTree -> DT.DecisionTree -> Opt.Decider Int
toChain path test successTree failureTree =
let
failure =
treeToDecider failureTree
in
case treeToDecider successTree of
Opt.Chain testChain success subFailure | failure == subFailure ->
Opt.Chain ((path, test) : testChain) success failure
success ->
Opt.Chain [(path, test)] success failure
-- INSERT CHOICES
--
-- If a target appears exactly once in a Decider, the corresponding expression
-- can be inlined. Whether things are inlined or jumps is called a "choice".
countTargets :: Opt.Decider Int -> Map.Map Int Int
countTargets decisionTree =
case decisionTree of
Opt.Leaf target ->
Map.singleton target 1
Opt.Chain _ success failure ->
Map.unionWith (+) (countTargets success) (countTargets failure)
Opt.FanOut _ tests fallback ->
Map.unionsWith (+) (map countTargets (fallback : map snd tests))
createChoices
:: Map.Map Int Int
-> (Int, Opt.Expr)
-> ( (Int, Opt.Choice), Maybe (Int, Opt.Expr) )
createChoices targetCounts (target, branch) =
if targetCounts ! target == 1 then
( (target, Opt.Inline branch)
, Nothing
)
else
( (target, Opt.Jump target)
, Just (target, branch)
)
insertChoices
:: Map.Map Int Opt.Choice
-> Opt.Decider Int
-> Opt.Decider Opt.Choice
insertChoices choiceDict decider =
let
go =
insertChoices choiceDict
in
case decider of
Opt.Leaf target ->
Opt.Leaf (choiceDict ! target)
Opt.Chain testChain success failure ->
Opt.Chain testChain (go success) (go failure)
Opt.FanOut path tests fallback ->
Opt.FanOut path (map (second go) tests) (go fallback)
| mgold/Elm | src/Optimize/Case.hs | bsd-3-clause | 4,385 | 0 | 15 | 1,107 | 1,281 | 674 | 607 | 103 | 8 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.Ratio
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : stable
-- Portability : portable
--
-- Standard functions on rational numbers
--
-----------------------------------------------------------------------------
module Data.Ratio
( Ratio
, Rational
, (%) -- :: (Integral a) => a -> a -> Ratio a
, numerator -- :: (Integral a) => Ratio a -> a
, denominator -- :: (Integral a) => Ratio a -> a
, approxRational -- :: (RealFrac a) => a -> a -> Rational
-- Ratio instances:
-- (Integral a) => Eq (Ratio a)
-- (Integral a) => Ord (Ratio a)
-- (Integral a) => Num (Ratio a)
-- (Integral a) => Real (Ratio a)
-- (Integral a) => Fractional (Ratio a)
-- (Integral a) => RealFrac (Ratio a)
-- (Integral a) => Enum (Ratio a)
-- (Read a, Integral a) => Read (Ratio a)
-- (Integral a) => Show (Ratio a)
) where
import Prelude
#ifdef __GLASGOW_HASKELL__
import GHC.Real -- The basic defns for Ratio
#endif
#ifdef __HUGS__
import Hugs.Prelude(Ratio(..), (%), numerator, denominator)
#endif
#ifdef __NHC__
import Ratio (Ratio(..), (%), numerator, denominator, approxRational)
#else
-- -----------------------------------------------------------------------------
-- approxRational
-- | 'approxRational', applied to two real fractional numbers @x@ and @epsilon@,
-- returns the simplest rational number within @epsilon@ of @x@.
-- A rational number @y@ is said to be /simpler/ than another @y'@ if
--
-- * @'abs' ('numerator' y) <= 'abs' ('numerator' y')@, and
--
-- * @'denominator' y <= 'denominator' y'@.
--
-- Any real interval contains a unique simplest rational;
-- in particular, note that @0\/1@ is the simplest rational of all.
-- Implementation details: Here, for simplicity, we assume a closed rational
-- interval. If such an interval includes at least one whole number, then
-- the simplest rational is the absolutely least whole number. Otherwise,
-- the bounds are of the form q%1 + r%d and q%1 + r'%d', where abs r < d
-- and abs r' < d', and the simplest rational is q%1 + the reciprocal of
-- the simplest rational between d'%r' and d%r.
approxRational :: (RealFrac a) => a -> a -> Rational
approxRational rat eps = simplest (rat-eps) (rat+eps)
where simplest x y | y < x = simplest y x
| x == y = xr
| x > 0 = simplest' n d n' d'
| y < 0 = - simplest' (-n') d' (-n) d
| otherwise = 0 :% 1
where xr = toRational x
n = numerator xr
d = denominator xr
nd' = toRational y
n' = numerator nd'
d' = denominator nd'
simplest' n d n' d' -- assumes 0 < n%d < n'%d'
| r == 0 = q :% 1
| q /= q' = (q+1) :% 1
| otherwise = (q*n''+d'') :% n''
where (q,r) = quotRem n d
(q',r') = quotRem n' d'
nd'' = simplest' d' r' d r
n'' = numerator nd''
d'' = denominator nd''
#endif
| alekar/hugs | packages/base/Data/Ratio.hs | bsd-3-clause | 3,206 | 0 | 6 | 835 | 122 | 94 | 28 | 30 | 1 |
{-# LANGUAGE BangPatterns, CPP, GADTs #-}
module MkGraph
( CmmAGraph, CmmAGraphScoped, CgStmt(..)
, (<*>), catAGraphs
, mkLabel, mkMiddle, mkLast, outOfLine
, lgraphOfAGraph, labelAGraph
, stackStubExpr
, mkNop, mkAssign, mkStore
, mkUnsafeCall, mkFinalCall, mkCallReturnsTo
, mkJumpReturnsTo
, mkJump, mkJumpExtra
, mkRawJump
, mkCbranch, mkSwitch
, mkReturn, mkComment, mkCallEntry, mkBranch
, mkUnwind
, copyInOflow, copyOutOflow
, noExtraStack
, toCall, Transfer(..)
)
where
import GhcPrelude (($),Int,Bool,Eq(..)) -- avoid importing (<*>)
import BlockId
import Cmm
import CmmCallConv
import CmmSwitch (SwitchTargets)
import Hoopl.Block
import Hoopl.Graph
import Hoopl.Label
import DynFlags
import FastString
import ForeignCall
import OrdList
import SMRep (ByteOff)
import UniqSupply
import Control.Monad
import Data.List
import Data.Maybe
#include "HsVersions.h"
-----------------------------------------------------------------------------
-- Building Graphs
-- | CmmAGraph is a chunk of code consisting of:
--
-- * ordinary statements (assignments, stores etc.)
-- * jumps
-- * labels
-- * out-of-line labelled blocks
--
-- The semantics is that control falls through labels and out-of-line
-- blocks. Everything after a jump up to the next label is by
-- definition unreachable code, and will be discarded.
--
-- Two CmmAGraphs can be stuck together with <*>, with the meaning that
-- control flows from the first to the second.
--
-- A 'CmmAGraph' can be turned into a 'CmmGraph' (closed at both ends)
-- by providing a label for the entry point and a tick scope; see
-- 'labelAGraph'.
type CmmAGraph = OrdList CgStmt
-- | Unlabeled graph with tick scope
type CmmAGraphScoped = (CmmAGraph, CmmTickScope)
data CgStmt
= CgLabel BlockId CmmTickScope
| CgStmt (CmmNode O O)
| CgLast (CmmNode O C)
| CgFork BlockId CmmAGraph CmmTickScope
flattenCmmAGraph :: BlockId -> CmmAGraphScoped -> CmmGraph
flattenCmmAGraph id (stmts_t, tscope) =
CmmGraph { g_entry = id,
g_graph = GMany NothingO body NothingO }
where
body = foldr addBlock emptyBody $ flatten id stmts_t tscope []
--
-- flatten: given an entry label and a CmmAGraph, make a list of blocks.
--
-- NB. avoid the quadratic-append trap by passing in the tail of the
-- list. This is important for Very Long Functions (e.g. in T783).
--
flatten :: Label -> CmmAGraph -> CmmTickScope -> [Block CmmNode C C]
-> [Block CmmNode C C]
flatten id g tscope blocks
= flatten1 (fromOL g) block' blocks
where !block' = blockJoinHead (CmmEntry id tscope) emptyBlock
--
-- flatten0: we are outside a block at this point: any code before
-- the first label is unreachable, so just drop it.
--
flatten0 :: [CgStmt] -> [Block CmmNode C C] -> [Block CmmNode C C]
flatten0 [] blocks = blocks
flatten0 (CgLabel id tscope : stmts) blocks
= flatten1 stmts block blocks
where !block = blockJoinHead (CmmEntry id tscope) emptyBlock
flatten0 (CgFork fork_id stmts_t tscope : rest) blocks
= flatten fork_id stmts_t tscope $ flatten0 rest blocks
flatten0 (CgLast _ : stmts) blocks = flatten0 stmts blocks
flatten0 (CgStmt _ : stmts) blocks = flatten0 stmts blocks
--
-- flatten1: we have a partial block, collect statements until the
-- next last node to make a block, then call flatten0 to get the rest
-- of the blocks
--
flatten1 :: [CgStmt] -> Block CmmNode C O
-> [Block CmmNode C C] -> [Block CmmNode C C]
-- The current block falls through to the end of a function or fork:
-- this code should not be reachable, but it may be referenced by
-- other code that is not reachable. We'll remove it later with
-- dead-code analysis, but for now we have to keep the graph
-- well-formed, so we terminate the block with a branch to the
-- beginning of the current block.
flatten1 [] block blocks
= blockJoinTail block (CmmBranch (entryLabel block)) : blocks
flatten1 (CgLast stmt : stmts) block blocks
= block' : flatten0 stmts blocks
where !block' = blockJoinTail block stmt
flatten1 (CgStmt stmt : stmts) block blocks
= flatten1 stmts block' blocks
where !block' = blockSnoc block stmt
flatten1 (CgFork fork_id stmts_t tscope : rest) block blocks
= flatten fork_id stmts_t tscope $ flatten1 rest block blocks
-- a label here means that we should start a new block, and the
-- current block should fall through to the new block.
flatten1 (CgLabel id tscp : stmts) block blocks
= blockJoinTail block (CmmBranch id) :
flatten1 stmts (blockJoinHead (CmmEntry id tscp) emptyBlock) blocks
---------- AGraph manipulation
(<*>) :: CmmAGraph -> CmmAGraph -> CmmAGraph
(<*>) = appOL
catAGraphs :: [CmmAGraph] -> CmmAGraph
catAGraphs = concatOL
-- | created a sequence "goto id; id:" as an AGraph
mkLabel :: BlockId -> CmmTickScope -> CmmAGraph
mkLabel bid scp = unitOL (CgLabel bid scp)
-- | creates an open AGraph from a given node
mkMiddle :: CmmNode O O -> CmmAGraph
mkMiddle middle = unitOL (CgStmt middle)
-- | created a closed AGraph from a given node
mkLast :: CmmNode O C -> CmmAGraph
mkLast last = unitOL (CgLast last)
-- | A labelled code block; should end in a last node
outOfLine :: BlockId -> CmmAGraphScoped -> CmmAGraph
outOfLine l (c,s) = unitOL (CgFork l c s)
-- | allocate a fresh label for the entry point
lgraphOfAGraph :: CmmAGraphScoped -> UniqSM CmmGraph
lgraphOfAGraph g = do
u <- getUniqueM
return (labelAGraph (mkBlockId u) g)
-- | use the given BlockId as the label of the entry point
labelAGraph :: BlockId -> CmmAGraphScoped -> CmmGraph
labelAGraph lbl ag = flattenCmmAGraph lbl ag
---------- No-ops
mkNop :: CmmAGraph
mkNop = nilOL
mkComment :: FastString -> CmmAGraph
#if defined(DEBUG)
-- SDM: generating all those comments takes time, this saved about 4% for me
mkComment fs = mkMiddle $ CmmComment fs
#else
mkComment _ = nilOL
#endif
---------- Assignment and store
mkAssign :: CmmReg -> CmmExpr -> CmmAGraph
mkAssign l (CmmReg r) | l == r = mkNop
mkAssign l r = mkMiddle $ CmmAssign l r
mkStore :: CmmExpr -> CmmExpr -> CmmAGraph
mkStore l r = mkMiddle $ CmmStore l r
---------- Control transfer
mkJump :: DynFlags -> Convention -> CmmExpr
-> [CmmExpr]
-> UpdFrameOffset
-> CmmAGraph
mkJump dflags conv e actuals updfr_off =
lastWithArgs dflags Jump Old conv actuals updfr_off $
toCall e Nothing updfr_off 0
-- | A jump where the caller says what the live GlobalRegs are. Used
-- for low-level hand-written Cmm.
mkRawJump :: DynFlags -> CmmExpr -> UpdFrameOffset -> [GlobalReg]
-> CmmAGraph
mkRawJump dflags e updfr_off vols =
lastWithArgs dflags Jump Old NativeNodeCall [] updfr_off $
\arg_space _ -> toCall e Nothing updfr_off 0 arg_space vols
mkJumpExtra :: DynFlags -> Convention -> CmmExpr -> [CmmExpr]
-> UpdFrameOffset -> [CmmExpr]
-> CmmAGraph
mkJumpExtra dflags conv e actuals updfr_off extra_stack =
lastWithArgsAndExtraStack dflags Jump Old conv actuals updfr_off extra_stack $
toCall e Nothing updfr_off 0
mkCbranch :: CmmExpr -> BlockId -> BlockId -> Maybe Bool -> CmmAGraph
mkCbranch pred ifso ifnot likely =
mkLast (CmmCondBranch pred ifso ifnot likely)
mkSwitch :: CmmExpr -> SwitchTargets -> CmmAGraph
mkSwitch e tbl = mkLast $ CmmSwitch e tbl
mkReturn :: DynFlags -> CmmExpr -> [CmmExpr] -> UpdFrameOffset
-> CmmAGraph
mkReturn dflags e actuals updfr_off =
lastWithArgs dflags Ret Old NativeReturn actuals updfr_off $
toCall e Nothing updfr_off 0
mkBranch :: BlockId -> CmmAGraph
mkBranch bid = mkLast (CmmBranch bid)
mkFinalCall :: DynFlags
-> CmmExpr -> CCallConv -> [CmmExpr] -> UpdFrameOffset
-> CmmAGraph
mkFinalCall dflags f _ actuals updfr_off =
lastWithArgs dflags Call Old NativeDirectCall actuals updfr_off $
toCall f Nothing updfr_off 0
mkCallReturnsTo :: DynFlags -> CmmExpr -> Convention -> [CmmExpr]
-> BlockId
-> ByteOff
-> UpdFrameOffset
-> [CmmExpr]
-> CmmAGraph
mkCallReturnsTo dflags f callConv actuals ret_lbl ret_off updfr_off extra_stack = do
lastWithArgsAndExtraStack dflags Call (Young ret_lbl) callConv actuals
updfr_off extra_stack $
toCall f (Just ret_lbl) updfr_off ret_off
-- Like mkCallReturnsTo, but does not push the return address (it is assumed to be
-- already on the stack).
mkJumpReturnsTo :: DynFlags -> CmmExpr -> Convention -> [CmmExpr]
-> BlockId
-> ByteOff
-> UpdFrameOffset
-> CmmAGraph
mkJumpReturnsTo dflags f callConv actuals ret_lbl ret_off updfr_off = do
lastWithArgs dflags JumpRet (Young ret_lbl) callConv actuals updfr_off $
toCall f (Just ret_lbl) updfr_off ret_off
mkUnsafeCall :: ForeignTarget -> [CmmFormal] -> [CmmActual] -> CmmAGraph
mkUnsafeCall t fs as = mkMiddle $ CmmUnsafeForeignCall t fs as
-- | Construct a 'CmmUnwind' node for the given register and unwinding
-- expression.
mkUnwind :: GlobalReg -> CmmExpr -> CmmAGraph
mkUnwind r e = mkMiddle $ CmmUnwind [(r, Just e)]
--------------------------------------------------------------------------
-- Why are we inserting extra blocks that simply branch to the successors?
-- Because in addition to the branch instruction, @mkBranch@ will insert
-- a necessary adjustment to the stack pointer.
-- For debugging purposes, we can stub out dead stack slots:
stackStubExpr :: Width -> CmmExpr
stackStubExpr w = CmmLit (CmmInt 0 w)
-- When we copy in parameters, we usually want to put overflow
-- parameters on the stack, but sometimes we want to pass the
-- variables in their spill slots. Therefore, for copying arguments
-- and results, we provide different functions to pass the arguments
-- in an overflow area and to pass them in spill slots.
copyInOflow :: DynFlags -> Convention -> Area
-> [CmmFormal]
-> [CmmFormal]
-> (Int, [GlobalReg], CmmAGraph)
copyInOflow dflags conv area formals extra_stk
= (offset, gregs, catAGraphs $ map mkMiddle nodes)
where (offset, gregs, nodes) = copyIn dflags conv area formals extra_stk
-- Return the number of bytes used for copying arguments, as well as the
-- instructions to copy the arguments.
copyIn :: DynFlags -> Convention -> Area
-> [CmmFormal]
-> [CmmFormal]
-> (ByteOff, [GlobalReg], [CmmNode O O])
copyIn dflags conv area formals extra_stk
= (stk_size, [r | (_, RegisterParam r) <- args], map ci (stk_args ++ args))
where
ci (reg, RegisterParam r) =
CmmAssign (CmmLocal reg) (CmmReg (CmmGlobal r))
ci (reg, StackParam off) =
CmmAssign (CmmLocal reg) (CmmLoad (CmmStackSlot area off) ty)
where ty = localRegType reg
init_offset = widthInBytes (wordWidth dflags) -- infotable
(stk_off, stk_args) = assignStack dflags init_offset localRegType extra_stk
(stk_size, args) = assignArgumentsPos dflags stk_off conv
localRegType formals
-- Factoring out the common parts of the copyout functions yielded something
-- more complicated:
data Transfer = Call | JumpRet | Jump | Ret deriving Eq
copyOutOflow :: DynFlags -> Convention -> Transfer -> Area -> [CmmExpr]
-> UpdFrameOffset
-> [CmmExpr] -- extra stack args
-> (Int, [GlobalReg], CmmAGraph)
-- Generate code to move the actual parameters into the locations
-- required by the calling convention. This includes a store for the
-- return address.
--
-- The argument layout function ignores the pointer to the info table,
-- so we slot that in here. When copying-out to a young area, we set
-- the info table for return and adjust the offsets of the other
-- parameters. If this is a call instruction, we adjust the offsets
-- of the other parameters.
copyOutOflow dflags conv transfer area actuals updfr_off extra_stack_stuff
= (stk_size, regs, graph)
where
(regs, graph) = foldr co ([], mkNop) (setRA ++ args ++ stack_params)
co (v, RegisterParam r) (rs, ms)
= (r:rs, mkAssign (CmmGlobal r) v <*> ms)
co (v, StackParam off) (rs, ms)
= (rs, mkStore (CmmStackSlot area off) v <*> ms)
(setRA, init_offset) =
case area of
Young id -> -- Generate a store instruction for
-- the return address if making a call
case transfer of
Call ->
([(CmmLit (CmmBlock id), StackParam init_offset)],
widthInBytes (wordWidth dflags))
JumpRet ->
([],
widthInBytes (wordWidth dflags))
_other ->
([], 0)
Old -> ([], updfr_off)
(extra_stack_off, stack_params) =
assignStack dflags init_offset (cmmExprType dflags) extra_stack_stuff
args :: [(CmmExpr, ParamLocation)] -- The argument and where to put it
(stk_size, args) = assignArgumentsPos dflags extra_stack_off conv
(cmmExprType dflags) actuals
mkCallEntry :: DynFlags -> Convention -> [CmmFormal] -> [CmmFormal]
-> (Int, [GlobalReg], CmmAGraph)
mkCallEntry dflags conv formals extra_stk
= copyInOflow dflags conv Old formals extra_stk
lastWithArgs :: DynFlags -> Transfer -> Area -> Convention -> [CmmExpr]
-> UpdFrameOffset
-> (ByteOff -> [GlobalReg] -> CmmAGraph)
-> CmmAGraph
lastWithArgs dflags transfer area conv actuals updfr_off last =
lastWithArgsAndExtraStack dflags transfer area conv actuals
updfr_off noExtraStack last
lastWithArgsAndExtraStack :: DynFlags
-> Transfer -> Area -> Convention -> [CmmExpr]
-> UpdFrameOffset -> [CmmExpr]
-> (ByteOff -> [GlobalReg] -> CmmAGraph)
-> CmmAGraph
lastWithArgsAndExtraStack dflags transfer area conv actuals updfr_off
extra_stack last =
copies <*> last outArgs regs
where
(outArgs, regs, copies) = copyOutOflow dflags conv transfer area actuals
updfr_off extra_stack
noExtraStack :: [CmmExpr]
noExtraStack = []
toCall :: CmmExpr -> Maybe BlockId -> UpdFrameOffset -> ByteOff
-> ByteOff -> [GlobalReg]
-> CmmAGraph
toCall e cont updfr_off res_space arg_space regs =
mkLast $ CmmCall e cont regs arg_space res_space updfr_off
| shlevy/ghc | compiler/cmm/MkGraph.hs | bsd-3-clause | 14,778 | 0 | 18 | 3,643 | 3,326 | 1,790 | 1,536 | 243 | 9 |
-- | A CPS IR.
module Ivory.Compile.ACL2.CPS
( Proc (..)
, Value (..)
, Literal (..)
, Cont (..)
, Var
, variables
, contFreeVars
, explicitStack
, replaceCont
, commonSubExprElim
, removeAsserts
, removeNullEffect
) where
import Data.List
import Text.Printf
import Ivory.Compile.ACL2.Expr hiding (Expr (..))
import qualified Ivory.Compile.ACL2.Expr as E
-- | A procedure is a name, a list of arguments, an optional measure, and its continuation (body).
data Proc = Proc Var [Var] (Maybe E.Expr) Cont deriving Eq
instance Show Proc where
show (Proc name args Nothing body) = printf "%s(%s)\n%s\n" name (intercalate ", " args) (indent $ show body)
show (Proc name args (Just m) body) = printf "%s(%s)\n\tmeasure %s\n%s\n" name (intercalate ", " args) (show m) (indent $ show body)
-- | Values used in let bindings.
data Value
= Var Var -- ^ A variable reference.
| Literal Literal -- ^ A constant.
| Pop -- ^ Pop a value off the stack.
| Deref Var -- ^ Dereference a ref.
| Alloc -- ^ Allocate one word from the heap.
| Array [Var] -- ^ Array construction.
| Struct [(String, Var)] -- ^ Struct construction.
| ArrayIndex Var Var -- ^ Array indexing.
| StructIndex Var String -- ^ Structure indexing.
| Intrinsic Intrinsic [Var] -- ^ An application of an intrinsic to a list of arguments.
deriving Eq
instance Show Value where
show a = case a of
Var a -> a
Literal a -> show a
Pop -> "pop"
Deref a -> "deref " ++ a
Alloc -> printf "alloc"
Array a -> printf "array [%s]" $ intercalate ", " a
Struct a -> printf "struct {%s}" $ intercalate ", " [ printf "%s: %s" n v | (n, v) <- a ]
ArrayIndex a b -> printf "%s[%s]" a b
StructIndex a b -> printf "%s.%s" a b
Intrinsic a args -> printf "%s(%s)" (show a) (intercalate ", " args)
instance Num Value where
(+) = error "Method not supported for Num Value."
(-) = error "Method not supported for Num Value."
(*) = error "Method not supported for Num Value."
negate = error "Method not supported for Num Value."
abs = error "Method not supported for Num Value."
signum = error "Method not supported for Num Value."
fromInteger = Literal . fromInteger
-- | Continuations.
data Cont
= Halt -- ^ End the program or loop.
| Call Var [Var] (Maybe Cont) -- ^ Push the continuation onto the stack (if one exists) and call a function with arguments.
| Return (Maybe Var) -- ^ Pop a continuation off the stack and execute it. Saves the return value to the ReturnValue register.
| Push Var Cont -- ^ Push a value onto the stack.
| Let Var Value Cont -- ^ Brings a new variable into scope and assigns it a value.
| Store Var Var Cont -- ^ Store a value to a ref.
| If Var Cont Cont -- ^ Conditionally follow one continuation or another.
| Assert Var Cont -- ^ Assert a value and continue.
| Assume Var Cont -- ^ State an assumption and continue.
deriving Eq
instance Show Cont where
show a = case a of
Halt -> "halt\n"
Call a b Nothing -> printf "%s(%s)\n" a (intercalate ", " b)
Call a b (Just c) -> printf "%s(%s)\n%s" a (intercalate ", " b) (show c)
Return (Just a) -> printf "return %s\n" a
Return Nothing -> "return\n"
Push a b -> printf "push %s\n" a ++ show b
If a b c -> printf "if (%s)\n" a ++ indent (show b) ++ "\nelse\n" ++ indent (show c)
Assert a b -> printf "assert %s\n%s" a (show b)
Assume a b -> printf "assume %s\n%s" a (show b)
Let a b c -> printf "let %s = %s\n%s" a (show b) (show c)
Store a b c -> printf "store %s = %s\n%s" a b (show c)
indent :: String -> String
indent = intercalate "\n" . map ("\t" ++) . lines
-- | All the variables in a CPS program.
variables :: [Proc] -> [Var]
variables = nub . ("retval" :) . concatMap proc
where
proc :: Proc -> [Var]
proc (Proc _ args _ body) = args ++ cont body
cont :: Cont -> [Var]
cont a = case a of
Halt -> []
Call _ a b -> a ++ case b of { Nothing -> []; Just b -> cont b }
Return (Just a) -> [a]
Return Nothing -> []
Push a b -> a : cont b
If a b c -> a : cont b ++ cont c
Assert a b -> a : cont b
Assume a b -> a : cont b
Let a b c -> a : value b ++ cont c
Store a b c -> [a, b] ++ cont c
value :: Value -> [Var]
value a = case a of
Var a -> [a]
Literal _ -> []
Pop -> []
Deref a -> [a]
Alloc -> []
Array a -> a
Struct a -> snd $ unzip a
ArrayIndex a b -> [a, b]
StructIndex a _ -> [a]
Intrinsic _ a -> a
-- | All free (unbound) variables in a continuation.
contFreeVars :: Cont -> [Var]
contFreeVars = nub . cont ["retval"]
where
cont :: [Var] -> Cont -> [Var]
cont i a = case a of
Call _ a b -> concatMap var a ++ case b of { Nothing -> []; Just a -> cont i a }
Return Nothing -> []
Return (Just a) -> var a
Push a b -> var a ++ cont i b
Let a b c -> value b ++ cont (a : i) c
Store a b c -> var a ++ var b ++ cont i c
Halt -> []
If a b c -> var a ++ cont i b ++ cont i c
Assert a b -> var a ++ cont i b
Assume a b -> var a ++ cont i b
where
var :: Var -> [Var]
var a = if elem a i then [] else [a]
value :: Value -> [Var]
value a = case a of
Var a -> var a
Literal _ -> []
Pop -> []
Deref a -> var a
Alloc -> []
Array a -> concatMap var a
Struct a -> concatMap var $ snd $ unzip a
ArrayIndex a b -> var a ++ var b
StructIndex a _ -> var a
Intrinsic _ a -> concatMap var a
-- | Convert a procedure to make explicit use of the stack to save and restore variables across procedure calls.
explicitStack :: Proc -> Proc
explicitStack (Proc name args measure body) = Proc name args measure $ cont body
where
cont :: Cont -> Cont
cont a = case a of
Call a b (Just c) -> f1 freeVars
where
freeVars = contFreeVars c
f1 vars = case vars of
[] -> Call a b $ Just $ f2 $ reverse freeVars
a : b -> Push a $ f1 b
f2 vars = case vars of
[] -> cont c
a : b -> Let a Pop $ f2 b
Call a b Nothing -> Call a b Nothing
Halt -> Halt
Return a -> Return a
Push a b -> Push a $ cont b
If a b c -> If a (cont b) (cont c)
Assert a b -> Assert a $ cont b
Assume a b -> Assume a $ cont b
Let a b c -> Let a b $ cont c
Store a b c -> Store a b $ cont c
-- | Replace a continuation given a pattern to match.
replaceCont :: (Cont -> Maybe Cont) -> Cont -> Cont
replaceCont replacement a = case replacement a of
Just a -> a
Nothing -> case a of
Halt -> Halt
Call a b c -> Call a b c
Return a -> Return a
Push a b -> Push a $ rep b
Let a b c -> Let a b $ rep c
Store a b c -> Store a b $ rep c
If a b c -> If a (rep b) (rep c)
Assert a b -> Assert a $ rep b
Assume a b -> Assume a $ rep b
where
rep = replaceCont replacement
-- | Common sub expression elim.
commonSubExprElim :: Proc -> Proc
commonSubExprElim (Proc name args measure body) = Proc name args measure $ elim [] [] body
where
elim :: [(Value, Var)] -> [(Var, Var)] -> Cont -> Cont
elim env vars a = case a of
Halt -> Halt
Call a b Nothing -> Call a (map var b) Nothing
Call a b (Just c) -> Call a (map var b) $ Just $ elim' c
Return Nothing -> Return Nothing
Return (Just a) -> Return $ Just $ var a
Push a b -> Push (var a) $ elim' b
Let a b c -> case b' of
Var b -> elim env ((a, b) : vars) c
_ -> case lookup b' env of
Nothing -> Let a b' $ elim env' vars c
Just a' -> elim env ((a, a') : vars) c
where
b' = value b
env' = if stateful then env else (b', a) : env
stateful :: Bool
stateful = case b' of
Pop -> True
Alloc -> True
_ -> False
Store a b c -> Store (var a) (var b) $ elim' c
If a b c -> If (var a) (elim' b) (elim' c)
Assert a b -> Assert (var a) $ elim' b
Assume a b -> Assume (var a) $ elim' b
where
elim' = elim env vars
var :: Var -> Var
var a = case lookup a vars of
Nothing -> a
Just b -> b
value :: Value -> Value
value a = case a of
Var a -> Var $ var a
Literal a -> Literal a
Pop -> Pop
Deref a -> Deref $ var a
Alloc -> Alloc
Array a -> Array $ map var a
Struct a -> Struct [ (n, var v) | (n, v) <- a ]
ArrayIndex a b -> ArrayIndex (var a) (var b)
StructIndex a b -> StructIndex (var a) b
Intrinsic a args -> Intrinsic a $ map var args
-- | Remove assertions.
removeAsserts :: Proc -> Proc
removeAsserts (Proc name args measure body) = Proc name args measure $ r body
where
r :: Cont -> Cont
r a = case a of
Halt -> Halt
Call a b Nothing -> Call a b Nothing
Call a b (Just c) -> Call a b $ Just $ r c
Return a -> Return a
Push a b -> Push a $ r b
Let a b c -> Let a b $ r c
Store a b c -> Store a b $ r c
If a b c -> If a (r b) (r c)
Assert _ b -> r b
Assume _ b -> r b
-- | Remove unused lets.
removeNullEffect :: Proc -> Proc
removeNullEffect (Proc name args measure body) = Proc name args measure $ r body
where
r :: Cont -> Cont
r a = case a of
Halt -> Halt
Call a b Nothing -> Call a b Nothing
Call a b (Just c) -> Call a b $ Just $ r c
Return a -> Return a
Push a b -> Push a $ r b
Let a b c'
| elem a $ contFreeVars c -> Let a b c
| otherwise -> c
where
c = r c'
Store a b c -> Store a b $ r c
If a b c -> If a (r b) (r c)
Assert a b -> Assert a $ r b
Assume a b -> Assume a $ r b
| GaloisInc/ivory-backend-acl2 | src/Ivory/Compile/ACL2/CPS.hs | bsd-3-clause | 10,661 | 0 | 19 | 4,010 | 4,057 | 1,982 | 2,075 | 244 | 26 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | A wrapper around hoogle.
module Stack.Hoogle
( hoogleCmd
) where
import Stack.Prelude
import qualified Data.ByteString.Lazy.Char8 as BL8
import Data.Char (isSpace)
import qualified Data.Text as T
import Distribution.PackageDescription (packageDescription, package)
import Distribution.Types.PackageName (mkPackageName)
import Distribution.Version (mkVersion)
import Lens.Micro ((?~))
import Path (parseAbsFile)
import Path.IO hiding (findExecutable)
import qualified Stack.Build
import Stack.Build.Target (NeedTargets(NeedTargets))
import Stack.Runners
import Stack.Types.Config
import Stack.Types.SourceMap
import qualified RIO.Map as Map
import RIO.Process
-- | Helper type to duplicate log messages
data Muted = Muted | NotMuted
-- | Hoogle command.
hoogleCmd :: ([String],Bool,Bool,Bool) -> RIO Runner ()
hoogleCmd (args,setup,rebuild,startServer) =
local (over globalOptsL modifyGO) $
withConfig YesReexec $
withDefaultEnvConfig $ do
hooglePath <- ensureHoogleInPath
generateDbIfNeeded hooglePath
runHoogle hooglePath args'
where
modifyGO :: GlobalOpts -> GlobalOpts
modifyGO = globalOptsBuildOptsMonoidL . buildOptsMonoidHaddockL ?~ True
args' :: [String]
args' = if startServer
then ["server", "--local", "--port", "8080"]
else []
++ args
generateDbIfNeeded :: Path Abs File -> RIO EnvConfig ()
generateDbIfNeeded hooglePath = do
databaseExists <- checkDatabaseExists
if databaseExists && not rebuild
then return ()
else if setup || rebuild
then do
logWarn
(if rebuild
then "Rebuilding database ..."
else "No Hoogle database yet. Automatically building haddocks and hoogle database (use --no-setup to disable) ...")
buildHaddocks
logInfo "Built docs."
generateDb hooglePath
logInfo "Generated DB."
else do
logError
"No Hoogle database. Not building one due to --no-setup"
bail
generateDb :: Path Abs File -> RIO EnvConfig ()
generateDb hooglePath = do
do dir <- hoogleRoot
createDirIfMissing True dir
runHoogle hooglePath ["generate", "--local"]
buildHaddocks :: RIO EnvConfig ()
buildHaddocks = do
config <- view configL
runRIO config $ -- a bit weird that we have to drop down like this
catch (withDefaultEnvConfig $ Stack.Build.build Nothing)
(\(_ :: ExitCode) -> return ())
hooglePackageName = mkPackageName "hoogle"
hoogleMinVersion = mkVersion [5, 0]
hoogleMinIdent =
PackageIdentifier hooglePackageName hoogleMinVersion
installHoogle :: RIO EnvConfig (Path Abs File)
installHoogle = requiringHoogle Muted $ do
Stack.Build.build Nothing
mhooglePath' <- findExecutable "hoogle"
case mhooglePath' of
Right hooglePath -> parseAbsFile hooglePath
Left _ -> do
logWarn "Couldn't find hoogle in path after installing. This shouldn't happen, may be a bug."
bail
requiringHoogle :: Muted -> RIO EnvConfig x -> RIO EnvConfig x
requiringHoogle muted f = do
hoogleTarget <- do
sourceMap <- view $ sourceMapL . to smDeps
case Map.lookup hooglePackageName sourceMap of
Just hoogleDep ->
case dpLocation hoogleDep of
PLImmutable pli ->
T.pack . packageIdentifierString <$>
restrictMinHoogleVersion muted (packageLocationIdent pli)
plm@(PLMutable _) -> do
T.pack . packageIdentifierString . package . packageDescription
<$> loadCabalFile plm
Nothing -> do
-- not muted because this should happen only once
logWarn "No hoogle version was found, trying to install the latest version"
mpir <- getLatestHackageVersion YesRequireHackageIndex hooglePackageName UsePreferredVersions
let hoogleIdent = case mpir of
Nothing -> hoogleMinIdent
Just (PackageIdentifierRevision _ ver _) ->
PackageIdentifier hooglePackageName ver
T.pack . packageIdentifierString <$>
restrictMinHoogleVersion muted hoogleIdent
config <- view configL
let boptsCLI = defaultBuildOptsCLI
{ boptsCLITargets = [hoogleTarget]
}
runRIO config $ withEnvConfig NeedTargets boptsCLI f
restrictMinHoogleVersion
:: HasLogFunc env
=> Muted -> PackageIdentifier -> RIO env PackageIdentifier
restrictMinHoogleVersion muted ident = do
if ident < hoogleMinIdent
then do
muteableLog LevelWarn muted $
"Minimum " <>
fromString (packageIdentifierString hoogleMinIdent) <>
" is not in your index. Installing the minimum version."
pure hoogleMinIdent
else do
muteableLog LevelInfo muted $
"Minimum version is " <>
fromString (packageIdentifierString hoogleMinIdent) <>
". Found acceptable " <>
fromString (packageIdentifierString ident) <>
" in your index, requiring its installation."
pure ident
muteableLog :: HasLogFunc env => LogLevel -> Muted -> Utf8Builder -> RIO env ()
muteableLog logLevel muted msg =
case muted of
Muted -> pure ()
NotMuted -> logGeneric "" logLevel msg
runHoogle :: Path Abs File -> [String] -> RIO EnvConfig ()
runHoogle hooglePath hoogleArgs = do
config <- view configL
menv <- liftIO $ configProcessContextSettings config envSettings
dbpath <- hoogleDatabasePath
let databaseArg = ["--database=" ++ toFilePath dbpath]
withProcessContext menv $ proc
(toFilePath hooglePath)
(hoogleArgs ++ databaseArg)
runProcess_
bail :: RIO EnvConfig a
bail = exitWith (ExitFailure (-1))
checkDatabaseExists = do
path <- hoogleDatabasePath
liftIO (doesFileExist path)
ensureHoogleInPath :: RIO EnvConfig (Path Abs File)
ensureHoogleInPath = do
config <- view configL
menv <- liftIO $ configProcessContextSettings config envSettings
mhooglePath <- runRIO menv (findExecutable "hoogle") <>
requiringHoogle NotMuted (findExecutable "hoogle")
eres <- case mhooglePath of
Left _ -> return $ Left "Hoogle isn't installed."
Right hooglePath -> do
result <- withProcessContext menv
$ proc hooglePath ["--numeric-version"]
$ tryAny . fmap fst . readProcess_
let unexpectedResult got = Left $ T.concat
[ "'"
, T.pack hooglePath
, " --numeric-version' did not respond with expected value. Got: "
, got
]
return $ case result of
Left err -> unexpectedResult $ T.pack (show err)
Right bs -> case parseVersion (takeWhile (not . isSpace) (BL8.unpack bs)) of
Nothing -> unexpectedResult $ T.pack (BL8.unpack bs)
Just ver
| ver >= hoogleMinVersion -> Right hooglePath
| otherwise -> Left $ T.concat
[ "Installed Hoogle is too old, "
, T.pack hooglePath
, " is version "
, T.pack $ versionString ver
, " but >= 5.0 is required."
]
case eres of
Right hooglePath -> parseAbsFile hooglePath
Left err
| setup -> do
logWarn $ display err <> " Automatically installing (use --no-setup to disable) ..."
installHoogle
| otherwise -> do
logWarn $ display err <> " Not installing it due to --no-setup."
bail
envSettings =
EnvSettings
{ esIncludeLocals = True
, esIncludeGhcPackagePath = True
, esStackExe = True
, esLocaleUtf8 = False
, esKeepGhcRts = False
}
| juhp/stack | src/Stack/Hoogle.hs | bsd-3-clause | 8,978 | 0 | 27 | 3,279 | 1,856 | 918 | 938 | -1 | -1 |
{-# LANGUAGE DataKinds, TypeOperators, TypeFamilies #-}
{-# OPTIONS_GHC -fwarn-redundant-constraints #-}
module TcTypeNatSimple where
import GHC.TypeLits
import Data.Proxy
type family SomeFun (n :: Nat)
-- See the ticket; whether this succeeds or fails is distinctly random
-- upon creation, commit f861fc6ad8e5504a4fecfc9bb0945fe2d313687c, this failed
-- with Simon's optimization to the flattening algorithm, commit
-- 37b3646c9da4da62ae95aa3a9152335e485b261e, this succeeded
-- with the change to stop Deriveds from rewriting Deriveds (around Dec. 12, 2014),
-- this failed again
-- 2016-01-23: it just started passing again, when
-- -fwarn-redundant-constraints was removed from the default warning set.
-- Turning the warning back on for this module, ghc reports (and probably has
-- for some time):
-- Redundant constraints: (x <= y, y <= x)
-- In the type signature for:
-- ti7 :: (x <= y, y <= x) => Proxy (SomeFun x) -> Proxy y -> ()
ti7 :: (x <= y, y <= x) => Proxy (SomeFun x) -> Proxy y -> ()
ti7 _ _ = ()
| sdiehl/ghc | testsuite/tests/typecheck/should_compile/T9708.hs | bsd-3-clause | 1,047 | 0 | 9 | 192 | 99 | 61 | 38 | 8 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
module HsTypeStruct where
import Data.Generics
-------- Types -----------------------------------------------------------------
data TI i t
= HsTyFun t t
-- | HsTyTuple [t]
| HsTyApp t t
| HsTyVar i
| HsTyCon i
| HsTyForall [i] [t] t -- forall is . Ps => t
deriving (Ord,Eq,Show,Read, Data, Typeable)
| kmate/HaRe | old/tools/base/AST/HsTypeStruct.hs | bsd-3-clause | 369 | 0 | 7 | 82 | 85 | 51 | 34 | 10 | 0 |
{-# OPTIONS_GHC -cpp #-}
{-# OPTIONS -fglasgow-exts #-}
{-# LANGUAGE MultiParamTypeClasses, OverlappingInstances, UndecidableInstances, FunctionalDependencies, NoMonomorphismRestriction #-}
{-+
Type environments.
For efficiency, a type environment is represented as a pair of an environment
and the set of (nongeneric) type variables that occur free in the environment.
The type checker needs this information when it generalizes a type,
and traversing the whole environment every time is too costly.
-}
module TiTEnv(TEnv,extenv1,extenv,empty,TiTEnv.lookup,domain,range) where
import HsIdent(HsIdentI)
import TiTypes(Scheme,Types(..))
import TiNames(TypeVar)
import qualified TiEnvFM as E
import Set60204
#if __GLASGOW_HASKELL__ >= 604
import qualified Data.Set as S (Set)
#else
import qualified Sets as S (Set)
#endif
type TEnv' i = E.Env (HsIdentI i) (Scheme i) -- types of value identifiers
data TEnv i = TEnv (TEnv' i) (S.Set i)
extenv1 x t (TEnv env vs) = TEnv (E.extenv1 x t env) (vs `unionS` fromListS (tv t))
extenv bs1 (TEnv bs2 vs) = TEnv (E.extenv bs1 bs2) (vs `unionS` fromListS (tv (map snd bs1)))
empty = TEnv E.empty emptyS
lookup (TEnv env _) x = E.lookup env x
domain (TEnv env _) = E.domain env
range (TEnv env _) = E.range env
--instance Functor TEnv where ...
instance TypeVar i => Types i (TEnv i) where
tv (TEnv env vs) = elemsS vs
-- tmap -- of questionable use...
| kmate/HaRe | old/tools/base/TI/TiTEnv.hs | bsd-3-clause | 1,402 | 0 | 12 | 226 | 379 | 209 | 170 | 20 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- This is a non-exposed internal module.
--
-- This code contains utility function and data structures that are used
-- to improve the efficiency of several instances in the Data.* namespace.
-----------------------------------------------------------------------------
module Data.Functor.Utils where
import Data.Coerce (Coercible, coerce)
import GHC.Base ( Applicative(..), Functor(..), Maybe(..), Monoid(..), Ord(..)
, Semigroup(..), ($), otherwise )
-- We don't expose Max and Min because, as Edward Kmett pointed out to me,
-- there are two reasonable ways to define them. One way is to use Maybe, as we
-- do here; the other way is to impose a Bounded constraint on the Monoid
-- instance. We may eventually want to add both versions, but we don't want to
-- trample on anyone's toes by imposing Max = MaxMaybe.
newtype Max a = Max {getMax :: Maybe a}
newtype Min a = Min {getMin :: Maybe a}
-- | @since 4.11.0.0
instance Ord a => Semigroup (Max a) where
{-# INLINE (<>) #-}
m <> Max Nothing = m
Max Nothing <> n = n
(Max m@(Just x)) <> (Max n@(Just y))
| x >= y = Max m
| otherwise = Max n
-- | @since 4.8.0.0
instance Ord a => Monoid (Max a) where
mempty = Max Nothing
-- | @since 4.11.0.0
instance Ord a => Semigroup (Min a) where
{-# INLINE (<>) #-}
m <> Min Nothing = m
Min Nothing <> n = n
(Min m@(Just x)) <> (Min n@(Just y))
| x <= y = Min m
| otherwise = Min n
-- | @since 4.8.0.0
instance Ord a => Monoid (Min a) where
mempty = Min Nothing
-- left-to-right state transformer
newtype StateL s a = StateL { runStateL :: s -> (s, a) }
-- | @since 4.0
instance Functor (StateL s) where
fmap f (StateL k) = StateL $ \ s -> let (s', v) = k s in (s', f v)
-- | @since 4.0
instance Applicative (StateL s) where
pure x = StateL (\ s -> (s, x))
StateL kf <*> StateL kv = StateL $ \ s ->
let (s', f) = kf s
(s'', v) = kv s'
in (s'', f v)
liftA2 f (StateL kx) (StateL ky) = StateL $ \s ->
let (s', x) = kx s
(s'', y) = ky s'
in (s'', f x y)
-- right-to-left state transformer
newtype StateR s a = StateR { runStateR :: s -> (s, a) }
-- | @since 4.0
instance Functor (StateR s) where
fmap f (StateR k) = StateR $ \ s -> let (s', v) = k s in (s', f v)
-- | @since 4.0
instance Applicative (StateR s) where
pure x = StateR (\ s -> (s, x))
StateR kf <*> StateR kv = StateR $ \ s ->
let (s', v) = kv s
(s'', f) = kf s'
in (s'', f v)
liftA2 f (StateR kx) (StateR ky) = StateR $ \ s ->
let (s', y) = ky s
(s'', x) = kx s'
in (s'', f x y)
-- See Note [Function coercion]
(#.) :: Coercible b c => (b -> c) -> (a -> b) -> (a -> c)
(#.) _f = coerce
{-# INLINE (#.) #-}
{-
Note [Function coercion]
~~~~~~~~~~~~~~~~~~~~~~~
Several functions here use (#.) instead of (.) to avoid potential efficiency
problems relating to #7542. The problem, in a nutshell:
If N is a newtype constructor, then N x will always have the same
representation as x (something similar applies for a newtype deconstructor).
However, if f is a function,
N . f = \x -> N (f x)
This looks almost the same as f, but the eta expansion lifts it--the lhs could
be _|_, but the rhs never is. This can lead to very inefficient code. Thus we
steal a technique from Shachaf and Edward Kmett and adapt it to the current
(rather clean) setting. Instead of using N . f, we use N #. f, which is
just
coerce f `asTypeOf` (N . f)
That is, we just *pretend* that f has the right type, and thanks to the safety
of coerce, the type checker guarantees that nothing really goes wrong. We still
have to be a bit careful, though: remember that #. completely ignores the
*value* of its left operand.
-}
| ezyang/ghc | libraries/base/Data/Functor/Utils.hs | bsd-3-clause | 3,943 | 0 | 12 | 982 | 1,050 | 566 | 484 | 55 | 1 |
module D2 where
y = 0
f z x = x + z
f_gen = (y + 1)
sumFun xs = sum $ (map (f (y + 1)) xs)
| kmate/HaRe | old/testing/generaliseDef/D2_AstOut.hs | bsd-3-clause | 98 | 0 | 11 | 36 | 68 | 37 | 31 | 5 | 1 |
{-# LANGUAGE RecordWildCards #-}
module T9437 where
data Foo = Foo { x :: Int }
test :: Foo -> Foo
test foo = foo { .. }
| ezyang/ghc | testsuite/tests/rename/should_fail/T9437.hs | bsd-3-clause | 124 | 0 | 8 | 31 | 42 | 25 | 17 | 5 | 1 |
-- Area of a Circle
-- http://www.codewars.com/kata/537baa6f8f4b300b5900106c
module Circle where
circleArea :: Double -> Maybe Double
circleArea r | r > 0 = Just( pi * r^2)
| otherwise = Nothing
| gafiatulin/codewars | src/7 kyu/Circle.hs | mit | 210 | 0 | 9 | 46 | 59 | 30 | 29 | 4 | 1 |
module Main where
import System.Environment(getArgs)
import Scheme(eval)
-- The driver function for the executable parser that simply runs the parser on
-- the first command-line argument and prints the resulting error or Expr.
main :: IO ()
main = do
args <- getArgs
case eval (head args) of
Left err -> print err
Right res -> print res
| mjdwitt/a-scheme | src/Main.hs | mit | 356 | 0 | 10 | 76 | 86 | 44 | 42 | 9 | 2 |
module Main where
addOne :: Num a => a -> a
addOne a = a + 1
addTwo :: Num a => a -> a
addTwo a = a + 2
result :: Num b => [b] -> [b]
result xs = map addOne xs
main :: IO ()
main = do
let ans = result [10]
print ans
| calvinchengx/learnhaskell | functors/functors.hs | mit | 233 | 0 | 11 | 76 | 131 | 66 | 65 | 11 | 1 |
import Control.Monad (replicateM, fmap, forM_)
import Control.Parallel
import Data.IORef
import Data.List ((\\))
import Graphics.UI.GLUT
import System.Random (getStdRandom, randomR,
setStdGen, mkStdGen, getStdGen)
import System.Random.Shuffle (shuffle')
import qualified Data.Map as Map (findMax, findMin, fromList)
initSeed = 997
numCities = 30
popSize = ceiling (fromIntegral numCities * 1.5)
mutRate = 0.03
elitism = ceiling (fromIntegral popSize / 10)
debug = False
type City = (Float, Float)
type Tour = [City]
type Population = [Tour]
type GLPoint = (GLfloat, GLfloat, GLfloat)
randFloat :: Float -> Float -> IO Float
randFloat a b = getStdRandom . randomR $ (a, b)
randInt :: Int -> Int -> IO Int
randInt a b = getStdRandom . randomR $ (a, b)
randomCity :: IO City
randomCity = do
r1 <- randFloat 0 1
r2 <- randFloat 0 1
return (r1, r2)
randomTour :: Int -> IO Tour
randomTour 0 = return []
randomTour n = do
rc <- randomCity
rt <- randomTour (n - 1)
return (rc : rt)
shuffleTour :: Tour -> IO Tour
shuffleTour [] = return []
shuffleTour t = do
g <- getStdGen
return $ shuffle' t (length t) g
randomizedPop :: Int -> Tour -> IO Population
randomizedPop 0 _ = return []
randomizedPop n t = do
t' <- shuffleTour t
ts <- randomizedPop (n - 1) t'
return (t' : ts)
distance :: City -> City -> Float
distance (x1, y1) (x2, y2) = sqrt $ (x2 - x1)^2
+ (y2 - y1)^2
tourDistance :: Tour -> Float
tourDistance t@(x:xs) = sum $ zipWith distance t t'
where t' = xs ++ [x]
fitness :: Tour -> Float
fitness = (1/) . tourDistance
select :: Population -> IO Tour
select [] = return []
select p = do
i <- randInt 0 (length p - 1)
r <- randFloat 0 1
if r < fitness (p !! i) / (maximum . map fitness $ p)
then return (p !! i)
else select p
crossover :: Tour -> Tour -> IO Tour
crossover [] _ = return []
crossover _ [] = return []
crossover m f = do
i <- randInt 0 (length m - 1)
j <- randInt i (length m - 1)
let s = sub i j f
return $ take i (m\\s) ++ s ++ drop i (m\\s)
sub :: Int -> Int -> [a] -> [a]
sub _ _ [] = []
sub i j t
| i > j = sub j i t
| otherwise = drop i . take (j + 1) $ t
mutate :: Tour -> IO Tour
mutate [] = return []
mutate t = do
i <- randInt 0 (length t - 1)
j <- randInt 0 (length t - 1)
c <- randFloat 0 1
if c < mutRate
then return . swap i j $ t
else return t
swap :: Int -> Int -> [a] -> [a]
swap _ _ [] = []
swap i j l = map t $ zip [0..] l
where t (k, v)
| k == i = l !! j
| k == j = l !! i
| otherwise = v
generateNewPop :: Int -> Population -> IO Population
generateNewPop _ [] = return []
generateNewPop 0 _ = return []
generateNewPop n p = do
m <- select p
f <- select p
c' <- crossover m f
c <- fmap last . replicateM numCities $ mutate c'
cs <- generateNewPop (n - 1) p
return (c : cs)
elite :: Int -> Population -> Population
elite _ [] = []
elite 0 _ = []
elite n p = best : elite (n - 1) (p\\[best])
where best = snd . Map.findMax
. Map.fromList
. makeMap $ p
makeMap :: Population -> [(Float, Tour)]
makeMap [] = []
makeMap (t:ts) = (fitness t, t) `par` makeMap ts
`pseq` (fitness t, t) : makeMap ts
evolve :: Population -> IO Population
evolve p = do
let bestTours = elite elitism p
np <- generateNewPop (popSize - elitism) p
return (np ++ bestTours)
nearest :: Tour -> Tour
nearest [] = []
nearest (x:[]) = [x]
nearest (x:xs) = x : nearest (snd best : (xs\\[snd best]) )
where best = Map.findMin (Map.fromList $ zip (map (distance x) xs) xs)
altPop :: Int -> Tour -> Population
altPop 0 _ = []
altPop n t = k : altPop (n - 1) t
where k = nearest (take numCities . drop n . cycle $ t)
main :: IO ()
main = do
(_progName, _args) <- getArgsAndInitialize
_window <- createWindow "TSP"
if debug == True
then setStdGen (mkStdGen initSeed)
else return ()
destinationCities <- randomTour numCities
let p1 = altPop numCities destinationCities
p2 <- randomizedPop (popSize - numCities) destinationCities
let p = p1 ++ p2
pv <- newIORef p
gen <- newIORef 0
idleCallback $= Just (idle pv gen)
displayCallback $= (display pv gen)
mainLoop
idle :: IORef Population -> IORef Int -> IdleCallback
idle pv gen = do
p <- get pv
pn <- evolve p
pv $= pn
gen $~! (+1)
postRedisplay Nothing
display :: IORef Population -> IORef Int -> DisplayCallback
display pv gen = do
clear [ColorBuffer]
loadIdentity
p <- get pv
g <- get gen
let bestT = Map.findMax . Map.fromList . makeMap $ p
let points = map cityToGLPoint (snd bestT)
color $ Color3 0.6 0.6 (0.6 :: GLfloat)
scale 0.9 0.9 (0.9 :: GLfloat)
renderPrimitive LineLoop $
mapM_ (\(x,y,z) -> vertex $ Vertex3 x y z) points
forM_ points $ \(x, y, z) ->
preservingMatrix $ do
color $ Color3 0.4 0.8 (0.4 :: GLfloat)
translate $ Vector3 x y z
square 0.02
translate $ Vector3 (- 1) 0.95 (0 :: GLfloat)
scale 0.0005 0.0005 (0.0005 :: GLfloat)
renderString MonoRoman ("Generation:" ++ show g
++ " Distance:"
++ show (1 / fst bestT))
flush
cityToGLPoint :: City -> GLPoint
cityToGLPoint (a, b) = (x, y, 0)
where x = (realToFrac a) * 2 - 1
y = (realToFrac b) * 2 - 1
square :: GLfloat -> IO ()
square w = renderPrimitive Quads $ mapM_ vertex3f
[ (-l, -l, 0), (l, -l, 0),
( l, l, 0), (-l, l, 0) ]
where l = w/2
vertex3f :: (GLfloat, GLfloat, GLfloat) -> IO ()
vertex3f (x, y, z) = vertex $ Vertex3 x y z
| 7lb/tsp-haskell | nn.hs | mit | 5,837 | 0 | 14 | 1,738 | 2,726 | 1,371 | 1,355 | 182 | 2 |
-----------------------------------------------------------------------------
--
-- Module : Parcial2.App
-- Copyright :
-- License : MIT
--
-- Maintainer : -
-- Stability :
-- Portability :
--
-- |
--
module Parcial2.App where
import Data.Maybe
import Data.Typeable
import GeneticAlgorithm
import Parcial2.Labyrinth
import CArgs
-----------------------------------------------------------------------------
appDescr = [ "Searches the shortest path in a labyrinth with Genetic Algorithm." ]
-----------------------------------------------------------------------------
---- Arguments
appArgs = CArgs {
positionalArguments = Positional "Labyrinth File" text ["path to labyrinth file"]
:. Positional "Population Size" int []
:. Nil
, optionalArguments = [
Opt optChromGenMaxChains
, Opt optChromGenMaxChainLen
, Opt optMutateMaxChainsGen
, Opt optMutateMaxChainLen
, Opt optMaxUnchangedIter
, Opt optMaxIters
, Opt optSelIntactFrac
, Opt optSelCrossoverFrac
, Opt optSelMutateFrac
, Opt optSelFracs
, Opt helpArg
]
}
-----------------------------------------------------------------------------
---- Options
optChromGenMaxChains :: Optional1 Int
optChromGenMaxChains = optional "" ["gen-max-chains"]
["Chromosome Generation: maximum chain number."]
[]
optChromGenMaxChainLen :: Optional1 Int
optChromGenMaxChainLen = optional "" ["gen-max-chain-len"]
["Chromosome Generation: maximum chain length."]
[]
optMutateMaxChainsGen :: Optional1 Int
optMutateMaxChainsGen = optional "" ["mut-max-chains"]
["Chromosome Mutation: maximum chains to insert."]
[]
optMutateMaxChainLen :: Optional1 Int
optMutateMaxChainLen = optional "" ["mut-max-chain-len"]
["Chromosome Mutation: maximum insert chain length."]
[]
optMaxUnchangedIter :: Optional1 Int
optMaxUnchangedIter = optional "U" ["max-unchanged"]
["Maximum number of iterations without best fitness change before stopping."]
[]
optMaxIters :: Optional1 Int
optMaxIters = optional "I" ["max-iter"]
["Maximum number of iterations."]
[]
optSelIntactFrac :: Optional1 Float
optSelIntactFrac = optional "" ["frac-intact"]
["Fraction of population left intact."]
[]
optSelCrossoverFrac :: Optional1 Float
optSelCrossoverFrac = optional "" ["frac-crossover"]
["Fraction of population used for crossover."]
[]
optSelMutateFrac :: Optional1 Float
optSelMutateFrac = optional "" ["frac-mutation"]
["Fraction of population used for mutation."]
[]
optSelFracs :: OptionalT3 Float Float Float
optSelFracs = optional3' "f" ["fracs"] ["Set all the fractions at once."]
"intact" ["intact fraction"]
"crossover" ["crossover fraction"]
"mutation" ["mutation fraction"]
-----------------------------------------------------------------------------
---- Defaults
readParams opts =
let orElse :: (Typeable a) => Optional vs a -> a -> a
opt `orElse` def = fromMaybe def $ opts `get` opt
intact' = optSelIntactFrac `orElse` 0.4
crossover' = optSelCrossoverFrac `orElse` 0.3
mutation' = optSelMutateFrac `orElse` 0.3
(intact, crossover, mutation) = optSelFracs `orElse` (intact', crossover', mutation')
in GAParams { gaChromGenMaxChainLen = optChromGenMaxChainLen `orElse` 5
, gaChromGenMaxChains = optChromGenMaxChains `orElse` 3
, gaMutateMaxChainsGen = optMutateMaxChainsGen `orElse` 2
, gaMutateMaxChainLen = optMutateMaxChainLen `orElse` 3
, gaMaxUnchangedIter = optMaxUnchangedIter `orElse` 5
, gaMaxIters = optMaxIters `orElse` (10*1000)
, gaSelIntactFrac = toRational intact
, gaSelCrossoverFrac = toRational crossover
, gaSelMutateFrac = toRational mutation
}
-----------------------------------------------------------------------------
---- Assert
assertPos name x | x < 1 = error $ "'" ++ name ++ "' cannot be less than 1."
assertPos _ _ = return ()
assertUnit name x | x > 1 || x < 0 = error $ "'" ++ name ++ "' must be in [0,1]."
| otherwise = return ()
assertSumOne precision msg vs | abs (1 - sum vs) > precision = error msg
| otherwise = return ()
assertParams p = do assertPos "gen-max-chain-len" $ gaChromGenMaxChainLen p
assertPos "gen-max-chais" $ gaChromGenMaxChains p
assertPos "mut-max-chain-len" $ gaMutateMaxChainLen p
assertPos "mut-max-chains" $ gaMutateMaxChainsGen p
assertPos "max-unchanged" $ gaMaxUnchangedIter p
assertPos "max-iter" $ gaMaxIters p
assertUnit "frac-intact" $ gaSelIntactFrac p
assertUnit "frac-crossover" $ gaSelCrossoverFrac p
assertUnit "frac-mutation" $ gaSelMutateFrac p
assertSumOne 0.0001 "The sum of fractions must be 1." $
($p) <$> [ gaSelIntactFrac, gaSelCrossoverFrac, gaSelMutateFrac]
-----------------------------------------------------------------------------
---- Main
appMain appName args = do
let cargs = parseArgs appArgs args
params = readParams (optionalValues cargs)
(file, pop) = case positionalValues cargs of
Right (file' :. pop' :. Nil) -> (text2str $ posValue file', posValue pop')
labyrinth' <- readLabyrinth2D file
let l = case labyrinth' of Left err -> error $ unlines err
Right l -> l
execGA = printAppResult =<< runApp l params pop
withHelp appName appDescr appArgs cargs execGA
runApp labyrinth params pop = do
assertPos "population size" pop
assertParams params
ga <- newGA (labyrinth, params) :: IO GA
runGA ga pop
printAppResult (res, debug) = do
putStrLn "DEBUG\n=====\n"
print debug
putStrLn "RESULT\n======\n"
print res
| fehu/itesm-ga | src/Parcial2/App.hs | mit | 6,832 | 0 | 16 | 2,254 | 1,301 | 673 | 628 | 117 | 2 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, InstanceSigs #-}
module CompilerUtility (compilerSettings) where
import Control.Applicative
import Data.List.Utils
import System.FilePath.Posix
import System.IO
import Data.ConfigFile
import CompilationUtility
import qualified ConfigFile
import Printer
import Utility
data COMPILER_SETTINGS = COMPILER_SETTINGS {
cs_executable :: FilePath,
cs_options :: String,
cs_compiler :: FilePath,
cs_externs :: [FilePath],
cs_readable :: String,
cs_debug :: String,
cs_flags :: String,
cs_quick :: String,
cs_standard :: String,
cs_extended :: String,
cs_js :: [FilePath],
cs_js_output_file :: FilePath,
cs_create_source_map :: FilePath,
cs_property_renaming_report :: FilePath,
cs_verbose :: Bool
}
instance UtilitySettings COMPILER_SETTINGS where
executable = cs_executable
toStringList cs = concat [
words $ cs_options cs,
["-jar", cs_compiler cs,
"--js_output_file=" ++ (cs_js_output_file cs),
"--create_source_map=" ++ (cs_create_source_map cs),
"--property_renaming_report=" ++ (cs_property_renaming_report cs)],
fmap ("--externs=" ++) $ cs_externs cs,
words $ cs_readable cs,
words $ cs_debug cs,
words $ cs_flags cs,
words $ cs_quick cs,
words $ cs_standard cs,
words $ cs_extended cs,
fmap ("--js=" ++) $ cs_js cs]
utitle _ = Just "Closure Compiler"
verbose = cs_verbose
compilerSettings :: ConfigParser -> [FilePath] -> EitherT String IO COMPILER_SETTINGS
compilerSettings cp files = do
readable <- hoistEither $ ConfigFile.getBool cp "DEFAULT" "readable"
production <- hoistEither $ ConfigFile.getBool cp "DEFAULT" "production"
quick <- hoistEither $ ConfigFile.getBool cp "DEFAULT" "quick"
extended <- hoistEither $ ConfigFile.getBool cp "DEFAULT" "extended"
COMPILER_SETTINGS
<$> ConfigFile.getFile cp "DEFAULT" "utility.compiler.executable"
<*> getString "utility.compiler.options"
<*> ConfigFile.getFile cp "DEFAULT" "utility.compiler.compiler"
<*> ConfigFile.getFiles cp "DEFAULT" "utility.compiler.externs"
<*> (if readable then do getString "utility.compiler.readable" else return "")
<*> (if not production then do getString "utility.compiler.debug" else return "")
<*> getString "utility.compiler.flags"
<*> getString "utility.compiler.quick"
<*> (if not quick then do getString "utility.compiler.standard" else return "")
<*> (if not quick && extended then do getString "utility.compiler.extended" else return "")
<*> pure files
<*> getString "utility.compiler.js_output_file"
<*> getString "utility.compiler.create_source_map"
<*> getString "utility.compiler.property_renaming_report"
<*> (hoistEither $ ConfigFile.getBool cp "DEFAULT" "verbose")
where
getString :: String -> EitherT String IO String
getString = hoistEither . ConfigFile.get cp "DEFAULT"
instance CompilationUtility COMPILER_SETTINGS () where
defaultValue :: COMPILER_SETTINGS -> ()
defaultValue _ = ()
failure :: UtilityResult COMPILER_SETTINGS -> EitherT String IO ()
failure r = do
errors <- catchIO $ hGetContents $ ur_stderr r
dPut [Failure, Str errors, Ln $ "Exit code: " ++ (show $ ur_exit_code r)]
throwT "CompilerUtility failure"
success :: UtilityResult COMPILER_SETTINGS -> EitherT String IO ()
success _ = dPut [Success]
| Prinhotels/goog-closure | src/CompilerUtility.hs | mit | 3,421 | 0 | 23 | 594 | 875 | 453 | 422 | 80 | 5 |
{- DOC: Paste all the following commented lines in the file importing this module (don’t forget to update constant ‘filename’).
import qualified SRC.Log as Log
-- write code here
-- boilerplate for logging
filename = "-.hs"
fatal :: Show a => String -> a -> b
fatal msg line = Log.reportFatal filename msg line
fixme, bug, err :: Show a => a -> b
fixme = fatal L.fixMe
bug = fatal L.bug
err = fatal L.err
-}
module SRC.Log
( reportFatal
, fixMe
, bug
, err
) where
reportFatal :: Show a => String -> String -> a -> b
reportFatal filename msg line = let message = filename ++ ":" ++ (show line) ++ ": " ++ msg
in error message
fixMe = "FixMe"
bug = "BUG"
err = "error"
| Fornost461/drafts-and-stuff | Haskell/samples/Template/SRC/Log.hs | cc0-1.0 | 716 | 0 | 13 | 174 | 108 | 58 | 50 | 11 | 1 |
{-
This is my xmonad configuration file.
There are many like it, but this one is mine.
-}
import Prelude hiding (mod)
import XMonad
import XMonad.Config.Azerty
import XMonad.Hooks.DynamicLog
import XMonad.Hooks.ManageDocks
import XMonad.Hooks.SetWMName
import XMonad.Hooks.UrgencyHook
import XMonad.Layout.Fullscreen
import qualified XMonad.StackSet as W
import XMonad.Util.Run (hPutStrLn, spawnPipe)
import Actions
import Constants
import Keys
import Layout
import Workspaces
-- | Startup
myStartupHook :: X ()
myStartupHook = do
-- Make Java GUI's work
setWMName "LG3D"
-- Set the current workspace to the startup workspace
windows $ W.greedyView startupWorkspace
myManageHook :: ManageHook
myManageHook = manageHook azertyConfig <+> composeAll myManagementHooks <+> manageDocks
myManagementHooks :: [ManageHook]
myManagementHooks =
[ className =? m --> move_to_mail | m <- mailClasses ] ++
[ className =? i --> move_to_web | i <- internet_classes ] ++
[
(title =? "Workflow") --> move_to_workflow
]
where
move_to_mail = doF $ W.shift mail_ws
move_to_web = doF $ W.shift web_ws
move_to_workflow = doF $ W.shift workflow_ws
myTitleColor = colorMain -- color of window title
myTitleLength = 80 -- truncate window title to this length
myCurrentWSColor = colorMain -- color of active workspace
myVisibleWSColor = colorSecondary -- color of inactive workspace
myUrgentWSColor = "#0000ff" -- color of workspace with 'urgent' window
myCurrentWSLeft = "[" -- wrap active workspace with these
myCurrentWSRight = "]"
myVisibleWSLeft = "(" -- wrap inactive workspace with these
myVisibleWSRight = ")"
myUrgentWSLeft = "{" -- wrap urgent workspace with these
myUrgentWSRight = "}"
myLogHook xmproc = dynamicLogWithPP $ xmobarPP {
ppOutput = hPutStrLn xmproc
, ppTitle = xmobarColor myTitleColor "" . shorten myTitleLength
, ppCurrent = xmobarColor myCurrentWSColor "" . wrap myCurrentWSLeft myCurrentWSRight
, ppVisible = xmobarColor myVisibleWSColor "" . wrap myVisibleWSLeft myVisibleWSRight
, ppUrgent = xmobarColor myUrgentWSColor "" . wrap myUrgentWSLeft myUrgentWSRight
}
-- Stiching together all the settings
main :: IO ()
main = do
xmproc <- spawnPipe "xmobar"
launch $ withUrgencyHook NoUrgencyHook $ azertyConfig {
focusedBorderColor = colorMain
, normalBorderColor = colorSecondary
, borderWidth = myBorderWidth
, terminal = myTerminal
, workspaces = myWorkspaces
, modMask = mod
, keys = myKeys
, mouseBindings = myMouse
, handleEventHook = fullscreenEventHook
, startupHook = myStartupHook
, manageHook = myManageHook
, layoutHook = myLayoutHook
, logHook = myLogHook xmproc
}
| NorfairKing/sus-depot | shared/shared/xmonad/xmonad.hs | gpl-2.0 | 3,361 | 0 | 10 | 1,141 | 551 | 315 | 236 | 64 | 1 |
-- Copyright (C) 2007 David Roundy
--
-- 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, 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; see the file COPYING. If not, write to
-- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-- Boston, MA 02110-1301, USA.
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-deprecations -fno-warn-orphans #-}
module Darcs.Test.Patch.Properties.Generic
( invertSymmetry, inverseComposition, invertRollback,
recommute, commuteInverses, effectPreserving,
permutivity, partialPermutivity,
patchAndInverseCommute, mergeEitherWay,
show_read,
mergeCommute, mergeConsistent, mergeArgumentsConsistent,
coalesceEffectPreserving, coalesceCommute, propIsMergeable
) where
import Darcs.Test.Util.TestResult ( TestResult, succeeded, failed, rejected,
(<&&>), fromMaybe )
import Darcs.Test.Patch.RepoModel ( RepoModel, RepoState, repoApply, eqModel, showModel
, maybeFail )
import Darcs.Test.Patch.WithState ( WithState(..), WithStartState(..) )
import Darcs.Test.Patch.Arbitrary.Generic ( Tree, flattenOne, MightBeEmptyHunk(..), MightHaveDuplicate(..) )
import Control.Monad ( msum )
import Darcs.Patch.Witnesses.Show ( Show2(..), show2 )
import Darcs.Patch.Patchy ( Patchy, showPatch, commute, invert )
import Darcs.Patch.Read ( ReadPatch )
import Darcs.Patch.Show ( ShowPatchBasic )
import Darcs.Patch.Prim.Class ( PrimPatch, PrimOf, FromPrim )
import Darcs.Patch ()
import Darcs.Patch.Apply ( ApplyState )
import Darcs.Patch.Commute ( commuteFLorComplain )
import Darcs.Patch.Merge ( Merge(merge) )
import Darcs.Patch.Read ( readPatch )
import Darcs.Patch.Invert ( invertFL )
import Darcs.Patch.Witnesses.Eq ( MyEq(..), EqCheck(..) )
import Darcs.Patch.Witnesses.Ordered ( FL(..), (:>)(..), (:\/:)(..), (:/\:)(..), lengthFL, eqFL, reverseRL )
import Darcs.Patch.Witnesses.Sealed ( Sealed(Sealed), seal2, Sealed2 )
import Darcs.Util.Printer ( Doc, renderPS, redText, greenText, ($$), text, RenderMode(..) )
--import Darcs.ColorPrinter ( traceDoc )
propIsMergeable :: forall model p wX . (FromPrim p, Merge p, RepoModel model)
=> Sealed (WithStartState model (Tree (PrimOf p)))
-> Maybe (Tree p wX)
propIsMergeable (Sealed (WithStartState _ t))
= case flattenOne t of
Sealed ps -> let _ = seal2 ps :: Sealed2 (FL p)
in case lengthFL ps of
_ -> Nothing
-- | invert symmetry inv(inv(p)) = p
invertSymmetry :: (Patchy p, MyEq p) => p wA wB -> TestResult
invertSymmetry p = case invert (invert p) =\/= p of
IsEq -> succeeded
NotEq -> failed $ redText "p /= inv(inv(p))"
inverseComposition :: (Patchy p, MyEq p) => (p :> p) wX wY -> TestResult
inverseComposition (a :> b) =
case eqFL (reverseRL (invertFL (a:>:b:>:NilFL))) (invert b:>:invert a:>:NilFL) of
IsEq -> succeeded
NotEq -> failed $ redText "inv(a :>: b :>: NilFL) /= inv(b) :>: inv(a) :>: NilFL"
-- | invert rollback if b = A(a) then a = A'(b)
invertRollback :: (ApplyState p ~ RepoState model, Patchy p, ShowPatchBasic p, RepoModel model)
=> WithState model p wA wB -> TestResult
invertRollback (WithState a x b)
= case maybeFail $ repoApply b (invert x) of
Nothing -> failed $ redText "x' not applicable to b."
Just a1 -> if a1 `eqModel` a
then succeeded
else failed $ redText "a1: " $$ text (showModel a1)
$$ redText " ---- is not equals to a:" $$ text (showModel a)
$$ redText "where a was" $$ text (showModel b)
$$ redText "with (invert x) on top:" $$ showPatch (invert x)
-- | recommute AB ↔ B′A′ if and only if B′A′ ↔ AB
recommute :: (Patchy p, ShowPatchBasic p, MyEq p, MightHaveDuplicate p)
=> (forall wX wY . ((p :> p) wX wY -> Maybe ((p :> p) wX wY)))
-> (p :> p) wA wB -> TestResult
recommute c (x :> y) =
case c (x :> y) of
Nothing -> rejected
Just (y' :> x')
-- this test unfortunately fails on some V2 patches that contain duplicates
-- after the commute. While in theory the underlying bug should be fixed,
-- we don't know how to and even if we did, it would probably involve a repository
-- migration to a new patch type.
| hasDuplicate y' || hasDuplicate x' -> rejected
| otherwise ->
case c (y' :> x') of
Nothing -> failed (redText "failed" $$ showPatch y' $$ redText ":>" $$ showPatch x')
Just (x'' :> y'') ->
case y'' =/\= y of
NotEq -> failed (redText "y'' =/\\= y failed, where x" $$ showPatch x $$
redText ":> y" $$ showPatch y $$
redText "y'" $$ showPatch y' $$
redText ":> x'" $$ showPatch x' $$
redText "x''" $$ showPatch x'' $$
redText ":> y''" $$ showPatch y'')
IsEq -> case x'' =/\= x of
NotEq -> failed (redText "x'' /= x" $$ showPatch x'' $$ redText ":>" $$ showPatch y'')
IsEq -> succeeded
-- | commuteInverses AB ↔ B′A′ if and only if B⁻¹A⁻¹ ↔ A′⁻¹B′⁻¹
commuteInverses :: (Patchy p, ShowPatchBasic p, MyEq p) => (forall wX wY . (p :> p) wX wY -> Maybe ((p :> p) wX wY))
-> (p :> p) wA wB -> TestResult
commuteInverses c (x :> y) =
case c (x :> y) of
Nothing -> rejected
Just (y' :> x') ->
case c (invert y :> invert x) of
Nothing -> failed $ redText "second commute failed" $$
redText "x" $$ showPatch x $$ redText "y" $$ showPatch y $$
redText "y'" $$ showPatch y' $$ redText "x'" $$ showPatch x'
Just (ix' :> iy') ->
case invert ix' =/\= x' of
NotEq -> failed $ redText "invert ix' /= x'" $$
redText "x" $$ showPatch x $$
redText "y" $$ showPatch y $$
redText "y'" $$ showPatch y' $$
redText "x'" $$ showPatch x' $$
redText "ix'" $$ showPatch ix' $$
redText "iy'" $$ showPatch iy' $$
redText "invert ix'" $$ showPatch (invert ix') $$
redText "invert iy'" $$ showPatch (invert iy')
IsEq -> case y' =\/= invert iy' of
NotEq -> failed $ redText "y' /= invert iy'" $$ showPatch iy' $$ showPatch y'
IsEq -> succeeded
-- | effect preserving AB <--> B'A' then effect(AB) = effect(B'A')
effectPreserving :: (Patchy p, MightBeEmptyHunk p, RepoModel model, ApplyState p ~ RepoState model) =>
(forall wX wY . (p :> p) wX wY -> Maybe ((p :> p) wX wY))
-> WithState model (p :> p) wA wB -> TestResult
effectPreserving _ (WithState _ (x :> _) _) | isEmptyHunk x = rejected
effectPreserving c (WithState r (x :> y) r')
= case c (x :> y) of
Nothing -> rejected
Just (y' :> x') ->
case maybeFail $ repoApply r y' of
Nothing -> failed $ redText "y' is not applicable to r."
Just r_y' ->
case maybeFail $ repoApply r_y' x' of
Nothing -> failed $ redText "x' is not applicable to r_y'."
Just r_y'x' -> if r_y'x' `eqModel` r'
then succeeded
else failed $ redText "r_y'x' is not equal to r'."
-- | patchAndInverseCommute If AB ↔ B′A′ then A⁻¹B′ ↔ BA′⁻¹
patchAndInverseCommute :: (Patchy p, ShowPatchBasic p, MyEq p) =>
(forall wX wY . (p :> p) wX wY -> Maybe ((p :> p) wX wY))
-> (p :> p) wA wB -> TestResult
patchAndInverseCommute c (x :> y) =
case c (x :> y) of
Nothing -> rejected
Just (y' :> x') ->
case c (invert x :> y') of
Nothing -> failed (redText ""
$$ redText "-------- original commute (x :> y):"
$$ showPatch x $$ redText ":>" $$ showPatch y
$$ redText "-------- result (y' :> x'):"
$$ showPatch y' $$ redText ":>" $$ showPatch x'
$$ redText "-------- bad commute (invert x :> y'):"
$$ showPatch (invert x) $$ redText ":>" $$ showPatch y')
Just (y'' :> ix') ->
case y'' =\/= y of
NotEq -> failed (redText "y'' /= y" $$
redText "x" $$ showPatch x $$
redText "y" $$ showPatch y $$
redText "x'" $$ showPatch x' $$
redText "y'" $$ showPatch y' $$
redText "y''" $$ showPatch y'' $$
redText ":> x'" $$ showPatch x')
IsEq -> case x' =\/= invert ix' of
NotEq -> failed (redText "x' /= invert ix'" $$
redText "y''" $$ showPatch y'' $$
redText ":> x'" $$ showPatch x' $$
redText "invert x" $$ showPatch (invert x) $$
redText ":> y" $$ showPatch y $$
redText "y'" $$ showPatch y' $$
redText "ix'" $$ showPatch ix')
IsEq -> succeeded
permutivity :: (Patchy p, ShowPatchBasic p, MyEq p) => (forall wX wY . (p :> p) wX wY -> Maybe ((p :> p) wX wY))
-> (p :> p :> p) wA wB -> TestResult
permutivity c (x:>y:>z) =
case c (x :> y) of
Nothing -> rejected
Just (y1 :> x1) ->
case c (y :> z) of
Nothing -> rejected
Just (z2 :> y2) ->
case c (x :> z2) of
Nothing -> rejected
Just (z3 :> x3) ->
case c (x1 :> z) of
Nothing -> failed $ redText "permutivity1"
Just (z4 :> x4) ->
--traceDoc (greenText "third commuted" $$
-- greenText "about to commute" $$
-- greenText "y1" $$ showPatch y1 $$
-- greenText "z4" $$ showPatch z4) $
case c (y1 :> z4) of
Nothing -> failed $ redText "permutivity2"
Just (z3_ :> y4)
| IsEq <- z3_ =\/= z3 ->
--traceDoc (greenText "passed z3") $ error "foobar test" $
case c (y4 :> x4) of
Nothing -> failed $ redText "permutivity5: input was" $$
redText "x" $$ showPatch x $$
redText "y" $$ showPatch y $$
redText "z" $$ showPatch z $$
redText "z3" $$ showPatch z3 $$
redText "failed commute of" $$
redText "y4" $$ showPatch y4 $$
redText "x4" $$ showPatch x4 $$
redText "whereas commute of x and y give" $$
redText "y1" $$ showPatch y1 $$
redText "x1" $$ showPatch x1
Just (x3_ :> y2_)
| NotEq <- x3_ =\/= x3 -> failed $ redText "permutivity6"
| NotEq <- y2_ =/\= y2 -> failed $ redText "permutivity7"
| otherwise -> succeeded
| otherwise ->
failed $ redText "permutivity failed" $$
redText "z3" $$ showPatch z3 $$
redText "z3_" $$ showPatch z3_
partialPermutivity :: (Patchy p, ShowPatchBasic p) => (forall wX wY . (p :> p) wX wY -> Maybe ((p :> p) wX wY))
-> (p :> p :> p) wA wB -> TestResult
partialPermutivity c (xx:>yy:>zz) = pp (xx:>yy:>zz) <&&> pp (invert zz:>invert yy:>invert xx)
where pp (x:>y:>z) =
case c (y :> z) of
Nothing -> rejected
Just (z1 :> y1) ->
case c (x :> z1) of
Nothing -> rejected
Just (_ :> x1) ->
case c (x :> y) of
Just _ -> rejected -- this is covered by full permutivity test above
Nothing ->
case c (x1 :> y1) of
Nothing -> succeeded
Just _ -> failed $ greenText "partialPermutivity error" $$
greenText "x" $$ showPatch x $$
greenText "y" $$ showPatch y $$
greenText "z" $$ showPatch z
mergeArgumentsConsistent :: (Patchy p, ShowPatchBasic p) =>
(forall wX wY . p wX wY -> Maybe Doc)
-> (p :\/: p) wA wB -> TestResult
mergeArgumentsConsistent isConsistent (x :\/: y) =
fromMaybe $
msum [(\z -> redText "mergeArgumentsConsistent x" $$ showPatch x $$ z) `fmap` isConsistent x,
(\z -> redText "mergeArgumentsConsistent y" $$ showPatch y $$ z) `fmap` isConsistent y]
mergeConsistent :: (Patchy p, ShowPatchBasic p, Merge p) =>
(forall wX wY . p wX wY -> Maybe Doc)
-> (p :\/: p) wA wB -> TestResult
mergeConsistent isConsistent (x :\/: y) =
case merge (x :\/: y) of
y' :/\: x' ->
fromMaybe $
msum [(\z -> redText "mergeConsistent x" $$ showPatch x $$ z) `fmap` isConsistent x,
(\z -> redText "mergeConsistent y" $$ showPatch y $$ z) `fmap` isConsistent y,
(\z -> redText "mergeConsistent x'" $$ showPatch x' $$ z $$
redText "where x' comes from x" $$ showPatch x $$
redText "and y" $$ showPatch y) `fmap` isConsistent x',
(\z -> redText "mergeConsistent y'" $$ showPatch y' $$ z) `fmap` isConsistent y']
mergeEitherWay :: (Patchy p, MyEq p, Merge p) => (p :\/: p) wX wY -> TestResult
mergeEitherWay (x :\/: y) =
case merge (x :\/: y) of
y' :/\: x' -> case merge (y :\/: x) of
x'' :/\: y'' | IsEq <- x'' =\/= x',
IsEq <- y'' =\/= y' -> succeeded
| otherwise -> failed $ redText "mergeEitherWay bug"
mergeCommute :: (Patchy p, MyEq p, ShowPatchBasic p, Merge p, MightHaveDuplicate p)
=> (p :\/: p) wX wY -> TestResult
mergeCommute (x :\/: y) =
case merge (x :\/: y) of
y' :/\: x'
-- this test unfortunately fails on some V2 patches that contain duplicates
-- after the merge. While in theory the underlying bug should be fixed,
-- we don't know how to and even if we did, it would probably involve a repository
-- migration to a new patch type.
| hasDuplicate x' || hasDuplicate y' -> rejected
| otherwise ->
case commute (x :> y') of
Nothing -> failed $ redText "mergeCommute 1" $$
redText "x" $$ showPatch x $$
redText "y" $$ showPatch y $$
redText "x'" $$ showPatch x' $$
redText "y'" $$ showPatch y'
Just (y_ :> x'_)
| IsEq <- y_ =\/= y,
IsEq <- x'_ =\/= x' ->
case commute (y :> x') of
Nothing -> failed $ redText "mergeCommute 2 failed" $$
redText "x" $$ showPatch x $$
redText "y" $$ showPatch y $$
redText "x'" $$ showPatch x' $$
redText "y'" $$ showPatch y'
Just (x_ :> y'_)
| IsEq <- x_ =\/= x,
IsEq <- y'_ =\/= y' -> succeeded
| otherwise -> failed $ redText "mergeCommute 3" $$
redText "x" $$ showPatch x $$
redText "y" $$ showPatch y $$
redText "x'" $$ showPatch x' $$
redText "y'" $$ showPatch y' $$
redText "x_" $$ showPatch x_ $$
redText "y'_" $$ showPatch y'_
| otherwise -> failed $ redText "mergeCommute 4" $$
redText "x" $$ showPatch x $$
redText "y" $$ showPatch y $$
redText "x'" $$ showPatch x' $$
redText "y'" $$ showPatch y' $$
redText "x'_" $$ showPatch x'_ $$
redText "y_" $$ showPatch y_
-- | coalesce effect preserving
coalesceEffectPreserving
:: (PrimPatch prim, RepoModel model, ApplyState prim ~ RepoState model )
=> (forall wX wY . (prim :> prim) wX wY -> Maybe (FL prim wX wY))
-> WithState model (prim :> prim) wA wB -> TestResult
coalesceEffectPreserving j (WithState r (a :> b) r') =
case j (a :> b) of
Nothing -> rejected
Just x -> case maybeFail $ repoApply r x of
Nothing -> failed $ redText "x is not applicable to r."
Just r_x -> if r_x `eqModel` r'
then succeeded
else failed $ redText "r_x /= r'"
coalesceCommute
:: (PrimPatch prim, MightBeEmptyHunk prim)
=> (forall wX wY . (prim :> prim) wX wY -> Maybe (FL prim wX wY))
-> (prim :> prim :> prim) wA wB -> TestResult
coalesceCommute _ (a :> _ :> _) | isEmptyHunk a = rejected
coalesceCommute j (a :> b :> c) =
case j (b :> c) of
Nothing -> rejected
Just x ->
case commuteFLorComplain (a :> b :>: c :>: NilFL) of
Right (b' :>: c' :>: NilFL :> a') ->
case commute (a:>:NilFL :> x) of
Just (x' :> a'':>:NilFL) ->
case a'' =/\= a' of
NotEq -> failed $ greenText "coalesceCommute 3"
IsEq -> case j (b' :> c') of
Nothing -> failed $ greenText "coalesceCommute 4"
Just x'' -> case x' =\/= x'' of
NotEq -> failed $ greenText "coalesceCommute 5"
IsEq -> succeeded
_ -> failed $ greenText "coalesceCommute 1"
_ -> rejected
show_read :: (Show2 p, MyEq p, ReadPatch p, ShowPatchBasic p, Patchy p) => p wA wB -> TestResult
show_read p = let ps = renderPS Standard (showPatch p)
in case readPatch ps of
Nothing -> failed (redText "unable to read " $$ showPatch p)
Just (Sealed p' ) | IsEq <- p' =\/= p -> succeeded
| otherwise -> failed $ redText "trouble reading patch p" $$
showPatch p $$
redText "reads as p'" $$
showPatch p' $$
redText "aka" $$
greenText (show2 p) $$
redText "and" $$
greenText (show2 p')
-- vim: fileencoding=utf-8 :
| DavidAlphaFox/darcs | harness/Darcs/Test/Patch/Properties/Generic.hs | gpl-2.0 | 20,474 | 0 | 43 | 8,318 | 5,562 | 2,792 | 2,770 | -1 | -1 |
module Language.UHIM.Dictionary.Transform.Tcvime where
import Control.Lens
import Data.Maybe
import qualified Data.Map as M
import Language.UHIM.Japanese.Prim
import qualified Language.UHIM.Dictionary.Keybind.Vim as Vim
import Language.UHIM.Dictionary.Yaml
data Config = Config { name :: String
, layoutName :: String
, extractConfig :: ExtractConfig
}
data ExtractConfig = ExtractConfig { kanjiExtractor :: KanjiShapes -> Maybe Kanji
}
defaultConfig :: Config
defaultConfig = Config { name = ""
, layoutName = "TUT"
, extractConfig = ExtractConfig { kanjiExtractor = extractKyuKanji
}
}
type KeyEntry = (String, String, String)
extractConvEntry :: ExtractConfig -> String -> (Position, DictEntry) -> [Vim.Mapping]
extractConvEntry c layout (pos, Entry字 decl) = maybeToList $ do
m <- decl^.decl鍵
kanji <- kanjiExtractor c $ decl^.decl體
k <- M.lookup layout m
return $ Vim.Mapping k kanji $ show pos
extractConvEntry _ _ _ = []
extract :: Config -> Dictionary -> [(FilePath, String)]
extract c dict = [(name c ++ ".vim", Vim.emit keyMap)]
where
keyMap = Vim.KeyMap { Vim.name = name c
, Vim.mappings = tuts
}
tuts = concatMap (extractConvEntry ec $ layoutName c) dict
ec = extractConfig c
| na4zagin3/uhim-dict | src/Language/UHIM/Dictionary/Transform/Tcvime.hs | gpl-3.0 | 1,493 | 6 | 11 | 472 | 405 | 229 | 176 | 29 | 1 |
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE CPP #-}
{-|
Module : Data.List.NonEmpty
Description : Extra helper function for 'Data.List.NonEmpty' from "base".
Copyright : (c) Evgenii Kotelnikov, 2019
License : GPL-3
Maintainer : evgeny.kotelnikov@gmail.com
Stability : provisional
-}
module Data.List.NonEmpty (
module Data.List.NonEmpty
) where
#if MIN_VERSION_base(4, 9, 0)
import "base" Data.List.NonEmpty
import qualified "base" Data.List.NonEmpty as NE (zipWith)
#else
import "semigroups" Data.List.NonEmpty
import qualified "semigroups" Data.List.NonEmpty as NE (zipWith)
#endif
zipWithM :: Applicative m
=> (a -> b -> m c) -> NonEmpty a -> NonEmpty b -> m (NonEmpty c)
zipWithM f xs ys = sequenceA (NE.zipWith f xs ys)
one :: a -> NonEmpty a
one a = a :| []
two :: a -> a -> NonEmpty a
two a b = a :| [b]
three :: a -> a -> a -> NonEmpty a
three a b c = a :| [b, c]
four :: a -> a -> a -> a -> NonEmpty a
four a b c d = a :| [b, c, d]
| aztek/voogie | src/Data/List/NonEmpty.hs | gpl-3.0 | 981 | 0 | 11 | 209 | 276 | 150 | 126 | 17 | 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.GamesManagement.Achievements.ResetAllForAllPlayers
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Resets all draft achievements for all players. This method is only
-- available to user accounts for your developer console.
--
-- /See:/ <https://developers.google.com/games/services Google Play Game Services Management API Reference> for @gamesManagement.achievements.resetAllForAllPlayers@.
module Network.Google.Resource.GamesManagement.Achievements.ResetAllForAllPlayers
(
-- * REST Resource
AchievementsResetAllForAllPlayersResource
-- * Creating a Request
, achievementsResetAllForAllPlayers
, AchievementsResetAllForAllPlayers
) where
import Network.Google.GamesManagement.Types
import Network.Google.Prelude
-- | A resource alias for @gamesManagement.achievements.resetAllForAllPlayers@ method which the
-- 'AchievementsResetAllForAllPlayers' request conforms to.
type AchievementsResetAllForAllPlayersResource =
"games" :>
"v1management" :>
"achievements" :>
"resetAllForAllPlayers" :>
QueryParam "alt" AltJSON :> Post '[JSON] ()
-- | Resets all draft achievements for all players. This method is only
-- available to user accounts for your developer console.
--
-- /See:/ 'achievementsResetAllForAllPlayers' smart constructor.
data AchievementsResetAllForAllPlayers =
AchievementsResetAllForAllPlayers'
deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'AchievementsResetAllForAllPlayers' with the minimum fields required to make a request.
--
achievementsResetAllForAllPlayers
:: AchievementsResetAllForAllPlayers
achievementsResetAllForAllPlayers = AchievementsResetAllForAllPlayers'
instance GoogleRequest
AchievementsResetAllForAllPlayers where
type Rs AchievementsResetAllForAllPlayers = ()
type Scopes AchievementsResetAllForAllPlayers =
'["https://www.googleapis.com/auth/games",
"https://www.googleapis.com/auth/plus.login"]
requestClient AchievementsResetAllForAllPlayers'{}
= go (Just AltJSON) gamesManagementService
where go
= buildClient
(Proxy ::
Proxy AchievementsResetAllForAllPlayersResource)
mempty
| rueshyna/gogol | gogol-games-management/gen/Network/Google/Resource/GamesManagement/Achievements/ResetAllForAllPlayers.hs | mpl-2.0 | 3,023 | 0 | 12 | 601 | 231 | 144 | 87 | 44 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.IAM.Types
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.AWS.IAM.Types
(
-- * Service Configuration
iAM
-- * Errors
, _CredentialReportNotPresentException
, _CredentialReportNotReadyException
, _MalformedPolicyDocumentException
, _EntityAlreadyExistsException
, _MalformedCertificateException
, _CredentialReportExpiredException
, _DuplicateCertificateException
, _DeleteConflictException
, _NoSuchEntityException
, _InvalidCertificateException
, _UnrecognizedPublicKeyEncodingException
, _InvalidUserTypeException
, _ServiceFailureException
, _InvalidInputException
, _InvalidPublicKeyException
, _InvalidAuthenticationCodeException
, _EntityTemporarilyUnmodifiableException
, _DuplicateSSHPublicKeyException
, _KeyPairMismatchException
, _PasswordPolicyViolationException
, _LimitExceededException
-- * AssignmentStatusType
, AssignmentStatusType (..)
-- * EncodingType
, EncodingType (..)
-- * EntityType
, EntityType (..)
-- * PolicyScopeType
, PolicyScopeType (..)
-- * ReportFormatType
, ReportFormatType (..)
-- * ReportStateType
, ReportStateType (..)
-- * StatusType
, StatusType (..)
-- * SummaryKeyType
, SummaryKeyType (..)
-- * AccessKey
, AccessKey
, accessKey
, akCreateDate
, akUserName
, akAccessKeyId
, akStatus
, akSecretAccessKey
-- * AccessKeyLastUsed
, AccessKeyLastUsed
, accessKeyLastUsed
, akluLastUsedDate
, akluServiceName
, akluRegion
-- * AccessKeyMetadata
, AccessKeyMetadata
, accessKeyMetadata
, akmStatus
, akmCreateDate
, akmUserName
, akmAccessKeyId
-- * AttachedPolicy
, AttachedPolicy
, attachedPolicy
, apPolicyName
, apPolicyARN
-- * Group
, Group
, group'
, gPath
, gGroupName
, gGroupId
, gARN
, gCreateDate
-- * GroupDetail
, GroupDetail
, groupDetail
, gdARN
, gdPath
, gdCreateDate
, gdGroupId
, gdGroupPolicyList
, gdGroupName
, gdAttachedManagedPolicies
-- * InstanceProfile
, InstanceProfile
, instanceProfile
, ipPath
, ipInstanceProfileName
, ipInstanceProfileId
, ipARN
, ipCreateDate
, ipRoles
-- * LoginProfile
, LoginProfile
, loginProfile
, lpPasswordResetRequired
, lpUserName
, lpCreateDate
-- * MFADevice
, MFADevice
, mfaDevice
, mdUserName
, mdSerialNumber
, mdEnableDate
-- * ManagedPolicyDetail
, ManagedPolicyDetail
, managedPolicyDetail
, mpdPolicyName
, mpdARN
, mpdUpdateDate
, mpdPolicyId
, mpdPath
, mpdPolicyVersionList
, mpdCreateDate
, mpdIsAttachable
, mpdDefaultVersionId
, mpdAttachmentCount
, mpdDescription
-- * OpenIdConnectProviderListEntry
, OpenIdConnectProviderListEntry
, openIdConnectProviderListEntry
, oicpleARN
-- * PasswordPolicy
, PasswordPolicy
, passwordPolicy
, ppExpirePasswords
, ppMinimumPasswordLength
, ppRequireNumbers
, ppPasswordReusePrevention
, ppRequireLowercaseCharacters
, ppMaxPasswordAge
, ppHardExpiry
, ppRequireSymbols
, ppRequireUppercaseCharacters
, ppAllowUsersToChangePassword
-- * Policy
, Policy
, policy
, pPolicyName
, pARN
, pUpdateDate
, pPolicyId
, pPath
, pCreateDate
, pIsAttachable
, pDefaultVersionId
, pAttachmentCount
, pDescription
-- * PolicyDetail
, PolicyDetail
, policyDetail
, pdPolicyDocument
, pdPolicyName
-- * PolicyGroup
, PolicyGroup
, policyGroup
, pgGroupName
-- * PolicyRole
, PolicyRole
, policyRole
, prRoleName
-- * PolicyUser
, PolicyUser
, policyUser
, puUserName
-- * PolicyVersion
, PolicyVersion
, policyVersion
, pvVersionId
, pvCreateDate
, pvDocument
, pvIsDefaultVersion
-- * Role
, Role
, role
, rAssumeRolePolicyDocument
, rPath
, rRoleName
, rRoleId
, rARN
, rCreateDate
-- * RoleDetail
, RoleDetail
, roleDetail
, rdAssumeRolePolicyDocument
, rdARN
, rdPath
, rdInstanceProfileList
, rdCreateDate
, rdRoleName
, rdRoleId
, rdRolePolicyList
, rdAttachedManagedPolicies
-- * SAMLProviderListEntry
, SAMLProviderListEntry
, sAMLProviderListEntry
, samlpleARN
, samlpleCreateDate
, samlpleValidUntil
-- * SSHPublicKey
, SSHPublicKey
, sshPublicKey
, spkUploadDate
, spkUserName
, spkSSHPublicKeyId
, spkFingerprint
, spkSSHPublicKeyBody
, spkStatus
-- * SSHPublicKeyMetadata
, SSHPublicKeyMetadata
, sshPublicKeyMetadata
, spkmUserName
, spkmSSHPublicKeyId
, spkmStatus
, spkmUploadDate
-- * ServerCertificate
, ServerCertificate
, serverCertificate
, sCertificateChain
, sServerCertificateMetadata
, sCertificateBody
-- * ServerCertificateMetadata
, ServerCertificateMetadata
, serverCertificateMetadata
, scmUploadDate
, scmExpiration
, scmPath
, scmServerCertificateName
, scmServerCertificateId
, scmARN
-- * SigningCertificate
, SigningCertificate
, signingCertificate
, scUploadDate
, scUserName
, scCertificateId
, scCertificateBody
, scStatus
-- * User
, User
, user
, uPasswordLastUsed
, uPath
, uUserName
, uUserId
, uARN
, uCreateDate
-- * UserDetail
, UserDetail
, userDetail
, udGroupList
, udARN
, udPath
, udCreateDate
, udUserName
, udUserId
, udUserPolicyList
, udAttachedManagedPolicies
-- * VirtualMFADevice
, VirtualMFADevice
, virtualMFADevice
, vmdQRCodePNG
, vmdBase32StringSeed
, vmdUser
, vmdEnableDate
, vmdSerialNumber
) where
import Network.AWS.IAM.Types.Product
import Network.AWS.IAM.Types.Sum
import Network.AWS.Prelude
import Network.AWS.Sign.V4
-- | API version '2010-05-08' of the Amazon Identity and Access Management SDK configuration.
iAM :: Service
iAM =
Service
{ _svcAbbrev = "IAM"
, _svcSigner = v4
, _svcPrefix = "iam"
, _svcVersion = "2010-05-08"
, _svcEndpoint = defaultEndpoint iAM
, _svcTimeout = Just 70
, _svcCheck = statusSuccess
, _svcError = parseXMLError
, _svcRetry = retry
}
where
retry =
Exponential
{ _retryBase = 5.0e-2
, _retryGrowth = 2
, _retryAttempts = 5
, _retryCheck = check
}
check e
| has (hasCode "ThrottlingException" . hasStatus 400) e =
Just "throttling_exception"
| has (hasCode "Throttling" . hasStatus 400) e = Just "throttling"
| has (hasStatus 503) e = Just "service_unavailable"
| has (hasStatus 500) e = Just "general_server_error"
| has (hasStatus 509) e = Just "limit_exceeded"
| otherwise = Nothing
-- | The request was rejected because the credential report does not exist.
-- To generate a credential report, use GenerateCredentialReport.
_CredentialReportNotPresentException :: AsError a => Getting (First ServiceError) a ServiceError
_CredentialReportNotPresentException =
_ServiceError . hasStatus 410 . hasCode "ReportNotPresent"
-- | The request was rejected because the credential report is still being
-- generated.
_CredentialReportNotReadyException :: AsError a => Getting (First ServiceError) a ServiceError
_CredentialReportNotReadyException =
_ServiceError . hasStatus 404 . hasCode "ReportInProgress"
-- | The request was rejected because the policy document was malformed. The
-- error message describes the specific error.
_MalformedPolicyDocumentException :: AsError a => Getting (First ServiceError) a ServiceError
_MalformedPolicyDocumentException =
_ServiceError . hasStatus 400 . hasCode "MalformedPolicyDocument"
-- | The request was rejected because it attempted to create a resource that
-- already exists.
_EntityAlreadyExistsException :: AsError a => Getting (First ServiceError) a ServiceError
_EntityAlreadyExistsException =
_ServiceError . hasStatus 409 . hasCode "EntityAlreadyExists"
-- | The request was rejected because the certificate was malformed or
-- expired. The error message describes the specific error.
_MalformedCertificateException :: AsError a => Getting (First ServiceError) a ServiceError
_MalformedCertificateException =
_ServiceError . hasStatus 400 . hasCode "MalformedCertificate"
-- | The request was rejected because the most recent credential report has
-- expired. To generate a new credential report, use
-- GenerateCredentialReport. For more information about credential report
-- expiration, see
-- <http://docs.aws.amazon.com/IAM/latest/UserGuide/credential-reports.html Getting Credential Reports>
-- in the /Using IAM/ guide.
_CredentialReportExpiredException :: AsError a => Getting (First ServiceError) a ServiceError
_CredentialReportExpiredException =
_ServiceError . hasStatus 410 . hasCode "ReportExpired"
-- | The request was rejected because the same certificate is associated with
-- an IAM user in the account.
_DuplicateCertificateException :: AsError a => Getting (First ServiceError) a ServiceError
_DuplicateCertificateException =
_ServiceError . hasStatus 409 . hasCode "DuplicateCertificate"
-- | The request was rejected because it attempted to delete a resource that
-- has attached subordinate entities. The error message describes these
-- entities.
_DeleteConflictException :: AsError a => Getting (First ServiceError) a ServiceError
_DeleteConflictException =
_ServiceError . hasStatus 409 . hasCode "DeleteConflict"
-- | The request was rejected because it referenced an entity that does not
-- exist. The error message describes the entity.
_NoSuchEntityException :: AsError a => Getting (First ServiceError) a ServiceError
_NoSuchEntityException = _ServiceError . hasStatus 404 . hasCode "NoSuchEntity"
-- | The request was rejected because the certificate is invalid.
_InvalidCertificateException :: AsError a => Getting (First ServiceError) a ServiceError
_InvalidCertificateException =
_ServiceError . hasStatus 400 . hasCode "InvalidCertificate"
-- | The request was rejected because the public key encoding format is
-- unsupported or unrecognized.
_UnrecognizedPublicKeyEncodingException :: AsError a => Getting (First ServiceError) a ServiceError
_UnrecognizedPublicKeyEncodingException =
_ServiceError . hasStatus 400 . hasCode "UnrecognizedPublicKeyEncoding"
-- | The request was rejected because the type of user for the transaction
-- was incorrect.
_InvalidUserTypeException :: AsError a => Getting (First ServiceError) a ServiceError
_InvalidUserTypeException =
_ServiceError . hasStatus 400 . hasCode "InvalidUserType"
-- | The request processing has failed because of an unknown error, exception
-- or failure.
_ServiceFailureException :: AsError a => Getting (First ServiceError) a ServiceError
_ServiceFailureException =
_ServiceError . hasStatus 500 . hasCode "ServiceFailure"
-- | The request was rejected because an invalid or out-of-range value was
-- supplied for an input parameter.
_InvalidInputException :: AsError a => Getting (First ServiceError) a ServiceError
_InvalidInputException = _ServiceError . hasStatus 400 . hasCode "InvalidInput"
-- | The request was rejected because the public key is malformed or
-- otherwise invalid.
_InvalidPublicKeyException :: AsError a => Getting (First ServiceError) a ServiceError
_InvalidPublicKeyException =
_ServiceError . hasStatus 400 . hasCode "InvalidPublicKey"
-- | The request was rejected because the authentication code was not
-- recognized. The error message describes the specific error.
_InvalidAuthenticationCodeException :: AsError a => Getting (First ServiceError) a ServiceError
_InvalidAuthenticationCodeException =
_ServiceError . hasStatus 403 . hasCode "InvalidAuthenticationCode"
-- | The request was rejected because it referenced an entity that is
-- temporarily unmodifiable, such as a user name that was deleted and then
-- recreated. The error indicates that the request is likely to succeed if
-- you try again after waiting several minutes. The error message describes
-- the entity.
_EntityTemporarilyUnmodifiableException :: AsError a => Getting (First ServiceError) a ServiceError
_EntityTemporarilyUnmodifiableException =
_ServiceError . hasStatus 409 . hasCode "EntityTemporarilyUnmodifiable"
-- | The request was rejected because the SSH public key is already
-- associated with the specified IAM user.
_DuplicateSSHPublicKeyException :: AsError a => Getting (First ServiceError) a ServiceError
_DuplicateSSHPublicKeyException =
_ServiceError . hasStatus 400 . hasCode "DuplicateSSHPublicKey"
-- | The request was rejected because the public key certificate and the
-- private key do not match.
_KeyPairMismatchException :: AsError a => Getting (First ServiceError) a ServiceError
_KeyPairMismatchException =
_ServiceError . hasStatus 400 . hasCode "KeyPairMismatch"
-- | The request was rejected because the provided password did not meet the
-- requirements imposed by the account password policy.
_PasswordPolicyViolationException :: AsError a => Getting (First ServiceError) a ServiceError
_PasswordPolicyViolationException =
_ServiceError . hasStatus 400 . hasCode "PasswordPolicyViolation"
-- | The request was rejected because it attempted to create resources beyond
-- the current AWS account limits. The error message describes the limit
-- exceeded.
_LimitExceededException :: AsError a => Getting (First ServiceError) a ServiceError
_LimitExceededException =
_ServiceError . hasStatus 409 . hasCode "LimitExceeded"
| fmapfmapfmap/amazonka | amazonka-iam/gen/Network/AWS/IAM/Types.hs | mpl-2.0 | 14,289 | 0 | 13 | 3,061 | 2,027 | 1,177 | 850 | 322 | 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.Content.Regions.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves a region defined in your Merchant Center account.
--
-- /See:/ <https://developers.google.com/shopping-content/v2/ Content API for Shopping Reference> for @content.regions.get@.
module Network.Google.Resource.Content.Regions.Get
(
-- * REST Resource
RegionsGetResource
-- * Creating a Request
, regionsGet
, RegionsGet
-- * Request Lenses
, regXgafv
, regMerchantId
, regUploadProtocol
, regRegionId
, regAccessToken
, regUploadType
, regCallback
) where
import Network.Google.Prelude
import Network.Google.ShoppingContent.Types
-- | A resource alias for @content.regions.get@ method which the
-- 'RegionsGet' request conforms to.
type RegionsGetResource =
"content" :>
"v2.1" :>
Capture "merchantId" (Textual Int64) :>
"regions" :>
Capture "regionId" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Region
-- | Retrieves a region defined in your Merchant Center account.
--
-- /See:/ 'regionsGet' smart constructor.
data RegionsGet =
RegionsGet'
{ _regXgafv :: !(Maybe Xgafv)
, _regMerchantId :: !(Textual Int64)
, _regUploadProtocol :: !(Maybe Text)
, _regRegionId :: !Text
, _regAccessToken :: !(Maybe Text)
, _regUploadType :: !(Maybe Text)
, _regCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RegionsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'regXgafv'
--
-- * 'regMerchantId'
--
-- * 'regUploadProtocol'
--
-- * 'regRegionId'
--
-- * 'regAccessToken'
--
-- * 'regUploadType'
--
-- * 'regCallback'
regionsGet
:: Int64 -- ^ 'regMerchantId'
-> Text -- ^ 'regRegionId'
-> RegionsGet
regionsGet pRegMerchantId_ pRegRegionId_ =
RegionsGet'
{ _regXgafv = Nothing
, _regMerchantId = _Coerce # pRegMerchantId_
, _regUploadProtocol = Nothing
, _regRegionId = pRegRegionId_
, _regAccessToken = Nothing
, _regUploadType = Nothing
, _regCallback = Nothing
}
-- | V1 error format.
regXgafv :: Lens' RegionsGet (Maybe Xgafv)
regXgafv = lens _regXgafv (\ s a -> s{_regXgafv = a})
-- | Required. The id of the merchant for which to retrieve region
-- definition.
regMerchantId :: Lens' RegionsGet Int64
regMerchantId
= lens _regMerchantId
(\ s a -> s{_regMerchantId = a})
. _Coerce
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
regUploadProtocol :: Lens' RegionsGet (Maybe Text)
regUploadProtocol
= lens _regUploadProtocol
(\ s a -> s{_regUploadProtocol = a})
-- | Required. The id of the region to retrieve.
regRegionId :: Lens' RegionsGet Text
regRegionId
= lens _regRegionId (\ s a -> s{_regRegionId = a})
-- | OAuth access token.
regAccessToken :: Lens' RegionsGet (Maybe Text)
regAccessToken
= lens _regAccessToken
(\ s a -> s{_regAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
regUploadType :: Lens' RegionsGet (Maybe Text)
regUploadType
= lens _regUploadType
(\ s a -> s{_regUploadType = a})
-- | JSONP
regCallback :: Lens' RegionsGet (Maybe Text)
regCallback
= lens _regCallback (\ s a -> s{_regCallback = a})
instance GoogleRequest RegionsGet where
type Rs RegionsGet = Region
type Scopes RegionsGet =
'["https://www.googleapis.com/auth/content"]
requestClient RegionsGet'{..}
= go _regMerchantId _regRegionId _regXgafv
_regUploadProtocol
_regAccessToken
_regUploadType
_regCallback
(Just AltJSON)
shoppingContentService
where go
= buildClient (Proxy :: Proxy RegionsGetResource)
mempty
| brendanhay/gogol | gogol-shopping-content/gen/Network/Google/Resource/Content/Regions/Get.hs | mpl-2.0 | 4,879 | 0 | 18 | 1,193 | 798 | 463 | 335 | 115 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Web.Scotty
import Data.Monoid (mconcat)
import Data.Time.Clock
-- monoid
main = scotty 3000 $ do
get "/:word" $ do
beam <- param "word"
html $ mconcat ["<h1>Scotty, ", beam, " me up!</h1>"]
-- mconcat = foldr mappend mempty
-- functor
offsetCurrentTime :: NominalDiffTime -> IO UTCTime
offsetCurrentTime offset =
fmap (addUTCTime (offset * 24 * 3600)) $ getCurrentTime
| prt2121/haskell-practice | ch6-11-17-25/src/Main.hs | apache-2.0 | 445 | 0 | 13 | 81 | 124 | 66 | 58 | 12 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Openshift.V1.ImageStreamTag where
import GHC.Generics
import Data.Text
import Kubernetes.V1.ObjectMeta
import Openshift.V1.Image
import qualified Data.Aeson
-- |
data ImageStreamTag = ImageStreamTag
{ kind :: Maybe Text -- ^ Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds
, apiVersion :: Maybe Text -- ^ APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#resources
, metadata :: Maybe ObjectMeta -- ^
, image :: Image -- ^ the image associated with the ImageStream and tag
} deriving (Show, Eq, Generic)
instance Data.Aeson.FromJSON ImageStreamTag
instance Data.Aeson.ToJSON ImageStreamTag
| minhdoboi/deprecated-openshift-haskell-api | openshift/lib/Openshift/V1/ImageStreamTag.hs | apache-2.0 | 1,216 | 0 | 9 | 177 | 122 | 75 | 47 | 19 | 0 |
{-# LANGUAGE OverloadedStrings #-}
-- Copyright 2014 (c) Diego Souza <dsouza@c0d3.xxx>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
module Leela.Data.EventTree
( Distribution ()
, makeDistribution
, stopDistribution
, startDistribution
, makeStartDistribution
, attach
, detach
, publish
, subscribe
, unsubscribe
) where
import Data.List (delete)
import Data.IORef
import Control.Monad
import Leela.DataHelpers
import Control.Concurrent
import Control.Applicative
data Distribution a b = Distribution { dThread :: MVar ThreadId
, dSource :: MVar a
, dSelect :: a -> Maybe b
, dClients :: IORef [MVar b]
}
makeDistribution :: (a -> Maybe b) -> IO (Distribution a b)
makeDistribution select = Distribution <$> newEmptyMVar <*> newEmptyMVar <*> pure select <*> newIORef []
makeStartDistribution :: (a -> Maybe b) -> IO (Distribution a b)
makeStartDistribution select = do
dist <- makeDistribution select
startDistribution dist
return dist
startDistribution :: Distribution a b -> IO ()
startDistribution d = do
pid <- forkFinally (forever $ do
a <- takeMVar (dSource d)
case (dSelect d a) of
Nothing -> return ()
Just b -> distribute b =<< readIORef (dClients d)) (\_ -> void (tryTakeMVar (dSource d)))
putMVar (dThread d) pid
where
distribute v group = do
let limit = 1000
chunks = chunked limit group
broadcast = mapM_ (flip putMVar v)
if (length group < limit)
then broadcast group
else do
wait <- newQSemN 0
mapM_ (flip forkFinally (\_ -> signalQSemN wait 1) . broadcast) chunks
waitQSemN wait (length chunks)
stopDistribution :: Distribution a b -> IO ()
stopDistribution d = maybe (return ()) killThread =<< tryTakeMVar (dThread d)
attach :: Distribution a b -> Distribution b c -> IO ()
attach src dst = atomicModifyIORef' (dClients src) (\list -> (dSource dst : list, ()))
detach :: Distribution a b -> Distribution b c -> IO ()
detach src dst = atomicModifyIORef' (dClients src) (\list -> (delete (dSource dst) list, ()))
subscribe :: Distribution a b -> IO (MVar b)
subscribe dist = do
mvar <- newEmptyMVar
atomicModifyIORef' (dClients dist) (\list -> (mvar : list, mvar))
unsubscribe :: Distribution a b -> MVar b -> IO ()
unsubscribe dist mvar = atomicModifyIORef' (dClients dist) (\list -> (delete mvar list, ()))
publish :: Distribution a b -> a -> IO ()
publish dist = putMVar (dSource dist)
| locaweb/leela | src/warpdrive/src/Leela/Data/EventTree.hs | apache-2.0 | 3,232 | 0 | 19 | 872 | 927 | 470 | 457 | 64 | 3 |
module External.A143481Spec (main, spec) where
import Test.Hspec
import External.A143481 (a143481)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A143481" $
it "correctly computes the first 20 elements" $
take 20 (map a143481 [1..]) `shouldBe` expectedValue where
expectedValue = [1,2,6,8,20,24,42,48,54,64,110,112,120,132,144,160,192,216,288,320]
| peterokagey/haskellOEIS | test/External/A143481Spec.hs | apache-2.0 | 377 | 0 | 10 | 59 | 160 | 95 | 65 | 10 | 1 |
{-| Module describing an instance.
The instance data type holds very few fields, the algorithm
intelligence is in the "Node" and "Cluster" modules.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.HTools.Instance
( Instance(..)
, Disk(..)
, AssocList
, List
, create
, isRunning
, isOffline
, notOffline
, instanceDown
, usesSecMem
, applyIfOnline
, setIdx
, setName
, setAlias
, setPri
, setSec
, setBoth
, setMovable
, specOf
, getTotalSpindles
, instBelowISpec
, instAboveISpec
, instMatchesPolicy
, shrinkByType
, localStorageTemplates
, hasSecondary
, requiredNodes
, allNodes
, usesLocalStorage
, mirrorType
) where
import Control.Monad (liftM2)
import Ganeti.BasicTypes
import qualified Ganeti.HTools.Types as T
import qualified Ganeti.HTools.Container as Container
import Ganeti.HTools.Nic (Nic)
import Ganeti.Utils
-- * Type declarations
data Disk = Disk
{ dskSize :: Int -- ^ Size in bytes
, dskSpindles :: Maybe Int -- ^ Number of spindles
} deriving (Show, Eq)
-- | The instance type.
data Instance = Instance
{ name :: String -- ^ The instance name
, alias :: String -- ^ The shortened name
, mem :: Int -- ^ Memory of the instance
, dsk :: Int -- ^ Total disk usage of the instance
, disks :: [Disk] -- ^ Sizes of the individual disks
, vcpus :: Int -- ^ Number of VCPUs
, runSt :: T.InstanceStatus -- ^ Original run status
, pNode :: T.Ndx -- ^ Original primary node
, sNode :: T.Ndx -- ^ Original secondary node
, idx :: T.Idx -- ^ Internal index
, util :: T.DynUtil -- ^ Dynamic resource usage
, movable :: Bool -- ^ Can and should the instance be moved?
, autoBalance :: Bool -- ^ Is the instance auto-balanced?
, diskTemplate :: T.DiskTemplate -- ^ The disk template of the instance
, spindleUse :: Int -- ^ The numbers of used spindles
, allTags :: [String] -- ^ List of all instance tags
, exclTags :: [String] -- ^ List of instance exclusion tags
, arPolicy :: T.AutoRepairPolicy -- ^ Instance's auto-repair policy
, nics :: [Nic] -- ^ NICs of the instance
} deriving (Show, Eq)
instance T.Element Instance where
nameOf = name
idxOf = idx
setAlias = setAlias
setIdx = setIdx
allNames n = [name n, alias n]
-- | Check if instance is running.
isRunning :: Instance -> Bool
isRunning (Instance {runSt = T.Running}) = True
isRunning (Instance {runSt = T.ErrorUp}) = True
isRunning _ = False
-- | Check if instance is offline.
isOffline :: Instance -> Bool
isOffline (Instance {runSt = T.StatusOffline}) = True
isOffline _ = False
-- | Helper to check if the instance is not offline.
notOffline :: Instance -> Bool
notOffline = not . isOffline
-- | Check if instance is down.
instanceDown :: Instance -> Bool
instanceDown inst | isRunning inst = False
instanceDown inst | isOffline inst = False
instanceDown _ = True
-- | Apply the function if the instance is online. Otherwise use
-- the initial value
applyIfOnline :: Instance -> (a -> a) -> a -> a
applyIfOnline = applyIf . notOffline
-- | Helper for determining whether an instance's memory needs to be
-- taken into account for secondary memory reservation.
usesSecMem :: Instance -> Bool
usesSecMem inst = notOffline inst && autoBalance inst
-- | Constant holding the local storage templates.
--
-- /Note:/ Currently Ganeti only exports node total/free disk space
-- for LVM-based storage; file-based storage is ignored in this model,
-- so even though file-based storage uses in reality disk space on the
-- node, in our model it won't affect it and we can't compute whether
-- there is enough disk space for a file-based instance. Therefore we
-- will treat this template as \'foreign\' storage.
localStorageTemplates :: [T.DiskTemplate]
localStorageTemplates = [ T.DTDrbd8, T.DTPlain ]
-- | Constant holding the movable disk templates.
--
-- This only determines the initial 'movable' state of the
-- instance. Further the movable state can be restricted more due to
-- user choices, etc.
movableDiskTemplates :: [T.DiskTemplate]
movableDiskTemplates =
[ T.DTDrbd8
, T.DTBlock
, T.DTSharedFile
, T.DTGluster
, T.DTRbd
, T.DTExt
]
-- | A simple name for the int, instance association list.
type AssocList = [(T.Idx, Instance)]
-- | A simple name for an instance map.
type List = Container.Container Instance
-- * Initialization
-- | Create an instance.
--
-- Some parameters are not initialized by function, and must be set
-- later (via 'setIdx' for example).
create :: String -> Int -> Int -> [Disk] -> Int -> T.InstanceStatus
-> [String] -> Bool -> T.Ndx -> T.Ndx -> T.DiskTemplate -> Int
-> [Nic] -> Instance
create name_init mem_init dsk_init disks_init vcpus_init run_init tags_init
auto_balance_init pn sn dt su nics_init =
Instance { name = name_init
, alias = name_init
, mem = mem_init
, dsk = dsk_init
, disks = disks_init
, vcpus = vcpus_init
, runSt = run_init
, pNode = pn
, sNode = sn
, idx = -1
, util = T.baseUtil
, movable = supportsMoves dt
, autoBalance = auto_balance_init
, diskTemplate = dt
, spindleUse = su
, allTags = tags_init
, exclTags = []
, arPolicy = T.ArNotEnabled
, nics = nics_init
}
-- | Changes the index.
--
-- This is used only during the building of the data structures.
setIdx :: Instance -- ^ The original instance
-> T.Idx -- ^ New index
-> Instance -- ^ The modified instance
setIdx t i = t { idx = i }
-- | Changes the name.
--
-- This is used only during the building of the data structures.
setName :: Instance -- ^ The original instance
-> String -- ^ New name
-> Instance -- ^ The modified instance
setName t s = t { name = s, alias = s }
-- | Changes the alias.
--
-- This is used only during the building of the data structures.
setAlias :: Instance -- ^ The original instance
-> String -- ^ New alias
-> Instance -- ^ The modified instance
setAlias t s = t { alias = s }
-- * Update functions
-- | Changes the primary node of the instance.
setPri :: Instance -- ^ the original instance
-> T.Ndx -- ^ the new primary node
-> Instance -- ^ the modified instance
setPri t p = t { pNode = p }
-- | Changes the secondary node of the instance.
setSec :: Instance -- ^ the original instance
-> T.Ndx -- ^ the new secondary node
-> Instance -- ^ the modified instance
setSec t s = t { sNode = s }
-- | Changes both nodes of the instance.
setBoth :: Instance -- ^ the original instance
-> T.Ndx -- ^ new primary node index
-> T.Ndx -- ^ new secondary node index
-> Instance -- ^ the modified instance
setBoth t p s = t { pNode = p, sNode = s }
-- | Sets the movable flag on an instance.
setMovable :: Instance -- ^ The original instance
-> Bool -- ^ New movable flag
-> Instance -- ^ The modified instance
setMovable t m = t { movable = m }
-- | Try to shrink the instance based on the reason why we can't
-- allocate it.
shrinkByType :: Instance -> T.FailMode -> Result Instance
shrinkByType inst T.FailMem = let v = mem inst - T.unitMem
in if v < T.unitMem
then Bad "out of memory"
else Ok inst { mem = v }
shrinkByType inst T.FailDisk =
let newdisks = [d {dskSize = dskSize d - T.unitDsk}| d <- disks inst]
v = dsk inst - (length . disks $ inst) * T.unitDsk
in if any (< T.unitDsk) $ map dskSize newdisks
then Bad "out of disk"
else Ok inst { dsk = v, disks = newdisks }
shrinkByType inst T.FailCPU = let v = vcpus inst - T.unitCpu
in if v < T.unitCpu
then Bad "out of vcpus"
else Ok inst { vcpus = v }
shrinkByType inst T.FailSpindles =
case disks inst of
[Disk ds sp] -> case sp of
Nothing -> Bad "No spindles, shouldn't have happened"
Just sp' -> let v = sp' - T.unitSpindle
in if v < T.unitSpindle
then Bad "out of spindles"
else Ok inst { disks = [Disk ds (Just v)] }
d -> Bad $ "Expected one disk, but found " ++ show d
shrinkByType _ f = Bad $ "Unhandled failure mode " ++ show f
-- | Get the number of disk spindles
getTotalSpindles :: Instance -> Maybe Int
getTotalSpindles inst =
foldr (liftM2 (+) . dskSpindles ) (Just 0) (disks inst)
-- | Return the spec of an instance.
specOf :: Instance -> T.RSpec
specOf Instance { mem = m, dsk = d, vcpus = c, disks = dl } =
let sp = case dl of
[Disk _ (Just sp')] -> sp'
_ -> 0
in T.RSpec { T.rspecCpu = c, T.rspecMem = m,
T.rspecDsk = d, T.rspecSpn = sp }
-- | Checks if an instance is smaller/bigger than a given spec. Returns
-- OpGood for a correct spec, otherwise Bad one of the possible
-- failure modes.
instCompareISpec :: Ordering -> Instance-> T.ISpec -> Bool -> T.OpResult ()
instCompareISpec which inst ispec exclstor
| which == mem inst `compare` T.iSpecMemorySize ispec = Bad T.FailMem
| which `elem` map ((`compare` T.iSpecDiskSize ispec) . dskSize)
(disks inst) = Bad T.FailDisk
| which == vcpus inst `compare` T.iSpecCpuCount ispec = Bad T.FailCPU
| exclstor &&
case getTotalSpindles inst of
Nothing -> True
Just sp_sum -> which == sp_sum `compare` T.iSpecSpindleUse ispec
= Bad T.FailSpindles
| not exclstor && which == spindleUse inst `compare` T.iSpecSpindleUse ispec
= Bad T.FailSpindles
| diskTemplate inst /= T.DTDiskless &&
which == length (disks inst) `compare` T.iSpecDiskCount ispec
= Bad T.FailDiskCount
| otherwise = Ok ()
-- | Checks if an instance is smaller than a given spec.
instBelowISpec :: Instance -> T.ISpec -> Bool -> T.OpResult ()
instBelowISpec = instCompareISpec GT
-- | Checks if an instance is bigger than a given spec.
instAboveISpec :: Instance -> T.ISpec -> Bool -> T.OpResult ()
instAboveISpec = instCompareISpec LT
-- | Checks if an instance matches a min/max specs pair
instMatchesMinMaxSpecs :: Instance -> T.MinMaxISpecs -> Bool -> T.OpResult ()
instMatchesMinMaxSpecs inst minmax exclstor = do
instAboveISpec inst (T.minMaxISpecsMinSpec minmax) exclstor
instBelowISpec inst (T.minMaxISpecsMaxSpec minmax) exclstor
-- | Checks if an instance matches any specs of a policy
instMatchesSpecs :: Instance -> [T.MinMaxISpecs] -> Bool -> T.OpResult ()
-- Return Ok for no constraints, though this should never happen
instMatchesSpecs _ [] _ = Ok ()
instMatchesSpecs inst minmaxes exclstor =
-- The initial "Bad" should be always replaced by a real result
foldr eithermatch (Bad T.FailInternal) minmaxes
where eithermatch mm (Bad _) = instMatchesMinMaxSpecs inst mm exclstor
eithermatch _ y@(Ok ()) = y
-- | Checks if an instance matches a policy.
instMatchesPolicy :: Instance -> T.IPolicy -> Bool -> T.OpResult ()
instMatchesPolicy inst ipol exclstor = do
instMatchesSpecs inst (T.iPolicyMinMaxISpecs ipol) exclstor
if diskTemplate inst `elem` T.iPolicyDiskTemplates ipol
then Ok ()
else Bad T.FailDisk
-- | Checks whether the instance uses a secondary node.
--
-- /Note:/ This should be reconciled with @'sNode' ==
-- 'Node.noSecondary'@.
hasSecondary :: Instance -> Bool
hasSecondary = (== T.DTDrbd8) . diskTemplate
-- | Computed the number of nodes for a given disk template.
requiredNodes :: T.DiskTemplate -> Int
requiredNodes T.DTDrbd8 = 2
requiredNodes _ = 1
-- | Computes all nodes of an instance.
allNodes :: Instance -> [T.Ndx]
allNodes inst = case diskTemplate inst of
T.DTDrbd8 -> [pNode inst, sNode inst]
_ -> [pNode inst]
-- | Checks whether a given disk template uses local storage.
usesLocalStorage :: Instance -> Bool
usesLocalStorage = (`elem` localStorageTemplates) . diskTemplate
-- | Checks whether a given disk template supported moves.
supportsMoves :: T.DiskTemplate -> Bool
supportsMoves = (`elem` movableDiskTemplates)
-- | A simple wrapper over 'T.templateMirrorType'.
mirrorType :: Instance -> T.MirrorType
mirrorType = T.templateMirrorType . diskTemplate
| ganeti-github-testing/ganeti-test-1 | src/Ganeti/HTools/Instance.hs | bsd-2-clause | 13,980 | 0 | 20 | 3,576 | 2,760 | 1,544 | 1,216 | 237 | 7 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Observation schema blocks for Nerf.
module NLP.Nerf.Schema
(
-- * Types
Ox
, Schema
, void
, sequenceS_
-- * Usage
, schematize
-- ** Configuration
, Body (..)
, Entry
, entry
, entryWith
, SchemaConf (..)
, nullConf
, defaultConf
, fromConf
-- ** Schema blocks
, Block
, fromBlock
, orthB
, splitOrthB
, lowPrefixesB
, lowSuffixesB
, lemmaB
, shapeB
, packedB
, shapePairB
, packedPairB
, dictB
) where
import Prelude hiding (Word)
import Control.Applicative ((<$>), (<*>))
import Control.Monad (forM_, join)
import Data.Maybe (maybeToList)
import Data.Binary (Binary, put, get)
import qualified Data.Char as C
import qualified Data.Set as S
import qualified Data.Vector as V
import qualified Data.Text as T
import qualified Data.DAWG.Static as D
import qualified Data.CRF.Chain1 as CRF
import qualified Control.Monad.Ox as Ox
import qualified Control.Monad.Ox.Text as Ox
import NLP.Nerf.Types
import NLP.Nerf.Dict (Dict)
-- | The Ox monad specialized to word token type and text observations.
type Ox a = Ox.Ox Word T.Text a
-- | A schema is a block of the Ox computation performed within the
-- context of the sentence and the absolute sentence position.
type Schema a = V.Vector Word -> Int -> Ox a
-- | A dummy schema block.
void :: a -> Schema a
void x _ _ = return x
-- | Sequence the list of schemas (or blocks) and discard individual values.
sequenceS_ :: [V.Vector Word -> a -> Ox b] -> V.Vector Word -> a -> Ox ()
sequenceS_ xs sent =
let ys = map ($sent) xs
in \k -> sequence_ (map ($k) ys)
-- | Record structure of the basic observation types.
data BaseOb = BaseOb
{ orth :: Int -> Maybe T.Text
, lowOrth :: Int -> Maybe T.Text }
-- | Construct the 'BaseOb' structure given the sentence.
mkBaseOb :: V.Vector Word -> BaseOb
mkBaseOb sent = BaseOb
{ orth = _orth
, lowOrth = _lowOrth }
where
at = Ox.atWith sent
_orth = (id `at`)
_lowOrth i = T.toLower <$> _orth i
-- | A block is a chunk of the Ox computation performed within the
-- context of the sentence and the list of absolute sentence positions.
type Block a = V.Vector Word -> [Int] -> Ox a
-- | Transform the block to the schema depending on the list of
-- relative sentence positions.
fromBlock :: Block a -> [Int] -> Schema a
fromBlock blk xs sent =
let blkSent = blk sent
in \k -> blkSent [x + k | x <- xs]
-- | Orthographic form at the current position.
orthB :: Block ()
orthB sent = \ks ->
let orthOb = Ox.atWith sent id
in mapM_ (Ox.save . orthOb) ks
-- | Orthographic form split into two observations: the lowercased form and
-- the original form (only when different than the lowercased one).
splitOrthB :: Block ()
splitOrthB sent = \ks -> do
mapM_ (Ox.save . lowOrth) ks
mapM_ (Ox.save . upOnlyOrth) ks
where
BaseOb{..} = mkBaseOb sent
upOnlyOrth i = orth i >>= \x -> case T.any C.isUpper x of
True -> Just x
False -> Nothing
-- | List of lowercased prefixes of given lengths.
lowPrefixesB :: [Int] -> Block ()
lowPrefixesB ns sent = \ks ->
forM_ ks $ \i ->
mapM_ (Ox.save . lowPrefix i) ns
where
BaseOb{..} = mkBaseOb sent
lowPrefix i j = Ox.prefix j =<< lowOrth i
-- | List of lowercased suffixes of given lengths.
lowSuffixesB :: [Int] -> Block ()
lowSuffixesB ns sent = \ks ->
forM_ ks $ \i ->
mapM_ (Ox.save . lowSuffix i) ns
where
BaseOb{..} = mkBaseOb sent
lowSuffix i j = Ox.suffix j =<< lowOrth i
-- | Lemma substitute parametrized by the number specifying the span
-- over which lowercased prefixes and suffixes will be 'Ox.save'd.
-- For example, @lemmaB 2@ will take affixes of lengths @0, -1@ and @-2@
-- on account.
lemmaB :: Int -> Block ()
lemmaB n sent = \ks -> do
mapM_ lowLemma ks
where
BaseOb{..} = mkBaseOb sent
lowPrefix i j = Ox.prefix j =<< lowOrth i
lowSuffix i j = Ox.suffix j =<< lowOrth i
lowLemma i = Ox.group $ do
mapM_ (Ox.save . lowPrefix i) [0, -1 .. -n]
mapM_ (Ox.save . lowSuffix i) [0, -1 .. -n]
-- | Shape of the word.
shapeB :: Block ()
shapeB sent = \ks -> do
mapM_ (Ox.save . shape) ks
where
BaseOb{..} = mkBaseOb sent
shape i = Ox.shape <$> orth i
-- | Packed shape of the word.
packedB :: Block ()
packedB sent = \ks -> do
mapM_ (Ox.save . shapeP) ks
where
BaseOb{..} = mkBaseOb sent
shape i = Ox.shape <$> orth i
shapeP i = Ox.pack <$> shape i
-- -- | Shape and packed shape of the word.
-- shapeAndPackedB :: Block ()
-- shapeAndPackedB sent = \ks -> do
-- mapM_ (Ox.save . shape) ks
-- mapM_ (Ox.save . shapeP) ks
-- where
-- BaseOb{..} = mkBaseOb sent
-- shape i = Ox.shape <$> orth i
-- shapeP i = Ox.pack <$> shape i
-- | Combined shapes of two consecutive (at @k-1@ and @k@ positions) words.
shapePairB :: Block ()
shapePairB sent = \ks ->
forM_ ks $ \i -> do
Ox.save $ link <$> shape i <*> shape (i - 1)
where
BaseOb{..} = mkBaseOb sent
shape i = Ox.shape <$> orth i
link x y = T.concat [x, "-", y]
-- | Combined packed shapes of two consecutive (at @k-1@ and @k@ positions)
-- words.
packedPairB :: Block ()
packedPairB sent = \ks ->
forM_ ks $ \i -> do
Ox.save $ link <$> shapeP i <*> shapeP (i - 1)
where
BaseOb{..} = mkBaseOb sent
shape i = Ox.shape <$> orth i
shapeP i = Ox.pack <$> shape i
link x y = T.concat [x, "-", y]
-- | Plain dictionary search determined with respect to the list of
-- relative positions.
dictB :: Dict -> Block ()
dictB dict sent = \ks -> do
mapM_ (Ox.saves . searchDict) ks
where
BaseOb{..} = mkBaseOb sent
searchDict i = join . maybeToList $
S.toList <$> (orth i >>= flip D.lookup dict . T.unpack)
-- | Body of configuration entry.
data Body a = Body {
-- | Range argument for the schema block.
range :: [Int]
-- | Additional arguments for the schema block.
, args :: a }
deriving (Show)
instance Binary a => Binary (Body a) where
put Body{..} = put range >> put args
get = Body <$> get <*> get
-- | Maybe entry.
type Entry a = Maybe (Body a)
-- | Entry with additional arguemnts.
entryWith :: a -> [Int] -> Entry a
entryWith v xs = Just (Body xs v)
-- | Maybe entry with additional arguemnts.
entryWith'Mb :: Maybe a -> [Int] -> Entry a
entryWith'Mb (Just v) xs = Just (Body xs v)
entryWith'Mb Nothing _ = Nothing
-- | Plain entry with no additional arugments.
entry :: [Int] -> Entry ()
entry = entryWith ()
-- | Configuration of the schema. All configuration elements specify the
-- range over which a particular observation type should be taken on account.
-- For example, the @[-1, 0, 2]@ range means that observations of particular
-- type will be extracted with respect to previous (@k - 1@), current (@k@)
-- and after the next (@k + 2@) positions when identifying the observation
-- set for position @k@ in the input sentence.
data SchemaConf = SchemaConf {
-- | The 'orthB' schema block.
orthC :: Entry ()
-- | The 'splitOrthB' schema block.
, splitOrthC :: Entry ()
-- | The 'lowPrefixesB' schema block. The first list of ints
-- represents lengths of prefixes.
, lowPrefixesC :: Entry [Int]
-- | The 'lowSuffixesB' schema block. The first list of ints
-- represents lengths of suffixes.
, lowSuffixesC :: Entry [Int]
-- | The 'lemmaB' schema block.
, lemmaC :: Entry Int
-- | The 'shapeB' schema block.
, shapeC :: Entry ()
-- | The 'packedB' schema block.
, packedC :: Entry ()
-- | The 'shapePairB' schema block.
, shapePairC :: Entry ()
-- | The 'packedPairB' schema block.
, packedPairC :: Entry ()
-- | Dictionaries of NEs ('dictB' schema block).
, dictC :: Entry [Dict]
-- | Dictionary of internal triggers.
, intTrigsC :: Entry Dict
-- | Dictionary of external triggers.
, extTrigsC :: Entry Dict
} deriving (Show)
instance Binary SchemaConf where
put SchemaConf{..} = do
put orthC
put splitOrthC
put lowPrefixesC
put lowSuffixesC
put lemmaC
put shapeC
put packedC
put shapePairC
put packedPairC
put dictC
put intTrigsC
put extTrigsC
get = SchemaConf
<$> get <*> get <*> get <*> get
<*> get <*> get <*> get <*> get
<*> get <*> get <*> get <*> get
-- | Null configuration of the observation schema.
nullConf :: SchemaConf
nullConf = SchemaConf
Nothing Nothing Nothing Nothing
Nothing Nothing Nothing Nothing
Nothing Nothing Nothing Nothing
-- | Default configuration of the observation schema.
defaultConf
:: [Dict] -- ^ Named Entity dictionaries
-> Maybe Dict -- ^ Dictionary of internal triggers
-> Maybe Dict -- ^ Dictionary of external triggers
-> IO SchemaConf
defaultConf neDicts intDict extDict = do
return $ SchemaConf
{ orthC = Nothing
, splitOrthC = entry [-1, 0]
, lowPrefixesC = Nothing
, lowSuffixesC = entryWith [2, 3, 4] [0]
, lemmaC = entryWith 3 [-1, 0]
, shapeC = entry [-1, 0]
, packedC = entry [-1, 0]
, shapePairC = entry [0]
, packedPairC = entry [0]
, dictC = entryWith neDicts [-1, 0]
, intTrigsC = entryWith'Mb intDict [0]
, extTrigsC = entryWith'Mb extDict [-1] }
mkArg0 :: Block () -> Entry () -> Schema ()
mkArg0 blk (Just x) = fromBlock blk (range x)
mkArg0 _ Nothing = void ()
mkArg1 :: (a -> Block ()) -> Entry a -> Schema ()
mkArg1 blk (Just x) = fromBlock (blk (args x)) (range x)
mkArg1 _ Nothing = void ()
mkArgs1 :: (a -> Block ()) -> Entry [a] -> Schema ()
mkArgs1 blk (Just x) = sequenceS_
[ fromBlock
(blk dict)
(range x)
| dict <- args x ]
mkArgs1 _ Nothing = void ()
-- | Build the schema based on the configuration.
fromConf :: SchemaConf -> Schema ()
fromConf SchemaConf{..} = sequenceS_
[ mkArg0 orthB orthC
, mkArg0 splitOrthB splitOrthC
, mkArg1 lowPrefixesB lowPrefixesC
, mkArg1 lowSuffixesB lowSuffixesC
, mkArg1 lemmaB lemmaC
, mkArg0 shapeB shapeC
, mkArg0 packedB packedC
, mkArg0 shapePairB shapePairC
, mkArg0 packedPairB packedPairC
, mkArgs1 dictB dictC
, mkArg1 dictB intTrigsC
, mkArg1 dictB extTrigsC ]
-- | Use the schema to extract observations from the sentence.
schematize :: Schema a -> [Word] -> CRF.Sent Ob
schematize schema xs =
map (S.fromList . Ox.execOx . schema v) [0 .. n - 1]
where
v = V.fromList xs
n = V.length v
| kawu/nerf | src/NLP/Nerf/Schema.hs | bsd-2-clause | 11,056 | 0 | 17 | 3,122 | 3,048 | 1,614 | 1,434 | 235 | 2 |
module Utilities.Bits where
import Emulator.Types
import Data.Bits
import Data.Int
-- This is what the halfWordExtend function is doing but we've opted for
-- the fromIntegral approach which has a chance to be faster (untested)
--halfWordExtend :: HalfWord -> MWord
--halfWordExtend h = val .|. orVal
-- where
-- val = fromIntegral (h .&. 0xFFFF) :: MWord
-- orVal = case testBit h 15 of
-- True -> 0xFFFF0000
-- False -> 0x00000000
halfWordExtend :: HalfWord -> MWord
halfWordExtend h = fromIntegral (fromIntegral (fromIntegral h :: Int16) :: Int32)
byteExtend :: Byte -> MWord
byteExtend b = fromIntegral (fromIntegral (fromIntegral b :: Int8) :: Int32)
arithExtend :: MWord -> Int -> MWord
arithExtend v n = clearBit (if (testBit v n) then setBit v 31 else v) n
-- For when we cant use the TemplateHaskell version
staticBitmask :: Int -> Int -> MWord -> MWord
staticBitmask x y w = (w .&. mask) `shiftR` y
where
a, b :: MWord
a = 1 `shiftL` fromIntegral x
b = 1 `shiftL` fromIntegral y
mask :: MWord
mask = ((a - 1) .&. complement (b - 1)) .|. a
| intolerable/GroupProject | src/Utilities/Bits.hs | bsd-2-clause | 1,095 | 0 | 12 | 233 | 276 | 156 | 120 | 17 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ExtendedDefaultRules #-}
{-# LANGUAGE ForeignFunctionInterface #-}
module Main where
-- External dependencies imports
-- import CATerms
-- import Filesystem hiding (writeFile, readFile, withFile, openFile)
-- import Language.Java.Pretty
-- import Language.Java.Syntax
-- import qualified Filesystem as FS
import ATerm.AbstractSyntax
import ATerm.Generics as G
import ATerm.ReadWrite
import ATerm.Unshared
import Codec.Archive.Zip
import Control.Applicative
import Control.Exception.Base
import Control.Monad
import Control.Monad.State
import Data.List
import Data.Maybe
import Data.String
import Data.Tree
import Data.Tree.ATerm
import Data.Tree.AntiUnification
import Data.Tree.Types
import Data.Tree.Weaver
import Data.Tree.Yang
import Data.Vector (Vector)
import Filesystem.Path hiding (concat, (<.>), null)
import Foreign.C.Types
import Foreign.ForeignPtr
import Foreign.Marshal.Array
import Foreign.Ptr
import JavaATerms ()
import Language.Java.Parser
import Prelude hiding (FilePath)
import Shelly hiding (FilePath, (</>),get,put)
import System.Console.GetOpt
import System.Environment
import System.Exit
import System.IO hiding (FilePath)
import Text.CSV
import WeaveUtils
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Text as T
import qualified Data.Vector as V
-- Recommended by Shelly
default (T.Text)
-----------------------------------------------------------------------
-- * Option Parsing
data Options = Options
{ optVerbose :: Bool
, optSandbox :: FilePath
, optMode :: Mode
, optThreshold :: Double
, optNumChanges:: Int
}
data Mode
= GenerateATerms
| AntiUnifyATerms
| AntiUnifyGroup
| Graphviz
| Unparse
| Weave
| Similarity
deriving (Read, Show, Eq, Ord)
defaultOptions :: Options
defaultOptions = Options
{ optVerbose = False
, optSandbox = "/tmp/version-patterns"
, optMode = GenerateATerms
, optThreshold = 0
, optNumChanges = 100
}
options :: [ OptDescr (Options -> IO Options) ]
options =
[ Option "s" ["sandbox"]
(ReqArg
(\arg o -> return o { optSandbox = fromString arg })
"DIRECTORY")
"Directory for storing or reading aterms"
, Option "v" ["verbose"]
(NoArg
(\o -> return o { optVerbose = True }))
"Enable verbose output"
, Option "m" ["mode"]
(ReqArg
(\arg o -> do
let mode = fromMaybe (error "Unrecognized mode") (parseMode arg)
return o { optMode = mode })
"MODE")
"Mode of operation, MODE is one of: generate-aterms, antiunify-aterms, antiunify-group, graphviz, similarity, unparse, weave"
, Option "t" ["threshold"]
(ReqArg
(\arg o -> do
let threshold = read arg :: Double
threshold `seq` return o { optThreshold = threshold })
"THRESHOLD")
"Threshold for similarity, as a floating point value, in the range [0..1]"
, Option "n" ["num"]
(ReqArg
(\arg o -> do
let num = read arg :: Int
num `seq` return o { optNumChanges = num })
"NUM")
"The number of changes to consume"
, Option "h" ["help"]
(NoArg
(\_ -> do
prg <- getProgName
hPutStrLn stderr (usageInfo prg options)
exitWith ExitSuccess))
"Show help"
]
parseMode :: String -> Maybe Mode
parseMode "generate-aterms" = Just GenerateATerms
parseMode "antiunify-aterms" = Just AntiUnifyATerms
parseMode "antiunify-group" = Just AntiUnifyGroup
parseMode "graphviz" = Just Graphviz
parseMode "similarity" = Just Similarity
parseMode "unparse" = Just Unparse
parseMode "weave" = Just Weave
parseMode _ = Nothing
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-- * Git Diff
-- Ignore permissons on files:
-- drivers/char/mmtimer.c /tmp/IV5Cnd_mmtimer.c 58eddfdd3110a3a7168f2b8bdbfabefb9691016a 100644 /tmp/9W7Cnd_mmtimer.c 12006182f575a4f3cd09827bcaaea6523077e7b3 100644
data GitDiffArgs = GitDiffArgs
{ gdaFilePath :: T.Text
, gdaBeforeCommit :: T.Text
, gdaAfterCommit :: T.Text
}
deriving (Show, Read, Eq, Ord)
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-- * Main program
main :: IO ()
main = do
args <- getArgs
let (actions, rest, _) = getOpt RequireOrder options args
opts <- foldl (>>=) (return defaultOptions) actions
let verbosity = if optVerbose opts then verbosely else silently
shelly $ verbosity $ do
case optMode opts of
GenerateATerms -> generateTerms (optSandbox opts)
AntiUnifyATerms -> processTerms (optSandbox opts)
AntiUnifyGroup -> antiUnifyTerms (optSandbox opts) "antiunify.gv" (map read rest)
Graphviz -> generateGraphs (optSandbox opts)
Similarity -> similarTrees (optSandbox opts) (optThreshold opts)
Unparse -> unparseTerms (optSandbox opts)
Weave -> weaveTerms (optSandbox opts) (optNumChanges opts)
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-- * Heavy lifting
-- | generateTerms Assumes that the current working directory is a git repository.
-- It builds a list of pairs from the history of the repository. Visits each of those
-- commits and requests the arguments that git-diff would use between those versions.
-- Then it parses the source code that changed between each revision in the context it was
-- commited in. The parsed representations are saved as ATerms in a zip archive.
generateTerms :: FilePath -> Sh ()
generateTerms sandbox = do
-- We add "master" so that if the repo is currently at a weird revision or branch, we get
-- reasonable view of the history of master.
cs <- T.lines <$> run "git" ["log", "master", "--pretty=format:%H", "--reverse"]
-- TODO: use the full history
let pairs = {- take 10 -} (zip cs (drop 1 cs))
-- Log the version pairs for later processing
mkdir_p sandbox
let initArchive = versionPairs `addEntryToArchive` emptyArchive
versionPairsFP = "version-pairs.hs" :: String
versionPairs = toEntry versionPairsFP 0 (BL.pack (show pairs))
archiveFP = T.unpack (toTextIgnore (sandbox </> "version-patterns.zip"))
writeFileInChunks archiveFP (fromArchive initArchive)
flipFoldM_ pairs initArchive $ \archive' (first,second) -> do
setenv "GIT_EXTERNAL_DIFF" "echo"
diffLines <- T.lines <$> run "git" ["diff", first, second]
-- Git should always return the same information, eg., if this fails something has gone wrong
-- TODO: what about multiple files? would that generate multiple lines?
let parseDiffArgs :: [T.Text] -> GitDiffArgs
parseDiffArgs [fp,_,_,_,_,_,_] = GitDiffArgs { gdaFilePath = fp
, gdaBeforeCommit = first
, gdaAfterCommit = second }
parseDiffArgs l | otherwise = error ("unexpected output from git diff: " ++ T.unpack (T.concat l))
diffArgs :: [GitDiffArgs]
diffArgs = map parseDiffArgs (map T.words diffLines)
saveATerms :: Archive -> T.Text -> [GitDiffArgs] -> Sh Archive
saveATerms a commit gdas = do
-- To properly parse files we need the context that the repository was in
-- when the commit was made. So we do a checkout. We may also need to
-- run configure or other commands. We have no support for that yet.
void (run "git" ["checkout", commit])
-------------------------------
-- Hacks for configuring/building the linux kernel enough to make it
-- parsable by ROSE
-- just take the default config
-- escaping False (run "yes \"\" | make oldconfig" [])
-- setup the asm symlink
-- run "make" ["include/asm"]
-- End Hacks for the kernel
-------------------------------
-------------------------------
-- Hacks for configuring/building freetype2 enough to make it
-- parsable by ROSE
-- void (run "./configure" []) `catchany_sh` (const (return ()))
-- End Hacks for the kernel
-------------------------------
flipFoldM gdas a $ \archive gda -> do
let commitDir = fromText commit
gdasFP = T.unpack (toTextIgnore (commitDir </> "gdas.hs"))
gdasEntry = toEntry gdasFP 0 (BL.pack (show gdas))
gdasArchive = gdasEntry `addEntryToArchive` archive
-- parse (gdaFilePath gda) using src2trm and save the result in destDir
-- Only handle C source for now
if fileFilter (gdaFilePath gda)
then do
liftIO (putStrLn ("running src2term for " ++ (T.unpack (gdaFilePath gda))))
let from = fromText (gdaFilePath gda)
to = commitDir </> (replaceExtension from "trm")
catchany_sh
(do trm <- B.pack <$> writeSharedATerm <$> src2term from
let trmArchive = toEntry (T.unpack (toTextIgnore to)) 0 (BL.fromChunks [trm]) `addEntryToArchive` gdasArchive
writeFileInChunks archiveFP (fromArchive trmArchive)
liftIO (putStrLn ("Wrote: " ++ T.unpack (toTextIgnore to) ++ " in archive."))
liftIO (toArchive <$> (BL.readFile archiveFP)))
(\e -> do
liftIO (putStr "Error running src2term: ")
liftIO (putStrLn (show e))
return gdasArchive)
else
return gdasArchive
-- Finally, save off the term files
archive'' <- saveATerms archive' first diffArgs
saveATerms archive'' second diffArgs
src2term :: FilePath -> Sh ATermTable
src2term from = do
cs <- liftIO (readFile (T.unpack (toTextIgnore from)))
case parser compilationUnit cs of
Right prog -> return (toATermTable (toATerm prog))
Left e -> fail (show e)
-- | processTerms looks in the version-patterns.zip archive
-- for version-pairs.hs. When it finds it, then it starts
-- looking for GitDiffArgs in gdas.hs in each commit directory.
-- When it reads GitDiffArgs it loads the two term representations
-- mentioned in the GitDiffArgs and computes the antiunification
-- of the two and adds that to the zip archive.
processTerms :: FilePath -> Sh ()
processTerms dir = do
let archiveFP = T.unpack (toTextIgnore (dir </> "version-patterns.zip"))
initArchiveBS <- liftIO (BL.readFile archiveFP)
-- find version-pairs.hs in the archive
let mb_ds = readFromArchive initArchive "version-pairs.hs" :: Maybe [(T.Text,T.Text)]
initArchive = toArchive initArchiveBS
case mb_ds of
Just ds -> do
liftIO (putStrLn ("length ds = " ++ show (length ds)))
-- process each diff pair
flipFoldM_ ds initArchive $ \archive' (commitBefore,commitAfter) -> do
liftIO (putStrLn ("processing " ++ show (commitBefore,commitAfter)))
let commitDir = fromText commitBefore
liftIO (putStrLn ("Looking in " ++ show commitDir))
-- Look for the GitDiffArgs stored in the current commit directory of the archive
let gdasFilePath = commitDir </> "gdas.hs"
mb_gdas = readFromArchive archive' gdasFilePath :: Maybe [GitDiffArgs]
case mb_gdas of
Just gdas -> do
liftIO (putStrLn ("Found gdas.hs"))
-- For each GitDiffArg we will antiunify them separately
flipFoldM gdas archive' $ \archive gda -> do
catchany_sh
-- Make sure we can process this file
(if fileFilter (gdaFilePath gda)
then do
liftIO (putStrLn ("Antiunify using " ++ show gda))
let diffDir = fromText (commitBefore `T.append` ".." `T.append` commitAfter)
antiunifiedFilePath = diffDir </> (replaceExtension (fromText (gdaFilePath gda)) "hs")
antiTerms = antiUnifySh archive gda
case antiTerms of
-- Something went wrong
Left e -> liftIO (putStrLn e) >> return archive
Right (t,s1,s2) -> do
let entry = toEntry (T.unpack (toTextIgnore antiunifiedFilePath)) 0 (BL.pack (show (t,s1,s2)))
newArchive = entry `addEntryToArchive` archive
liftIO (putStrLn ("Wrote antiunification to: " ++ (T.unpack (toTextIgnore antiunifiedFilePath))))
writeFileInChunks archiveFP (fromArchive newArchive)
liftIO (putStrLn "Done writing archive.")
liftIO (toArchive <$> (BL.readFile archiveFP))
else return archive)
-- Log the error and move on
(\e -> do
liftIO (putStr "Error processingTerms: ")
liftIO (putStrLn (show e))
return archive)
Nothing -> return archive'
Nothing -> return ()
-- | antiUnifySh Looks at the GitDiffArgs and pulls two terms out of the archive
-- computes the antiunfication and returns the results
antiUnifySh :: Archive -> GitDiffArgs -> Either String (Term, Subs, Subs)
antiUnifySh archive gda = do
let termBeforeFilePath = fromText (gdaBeforeCommit gda) </>
replaceExtension (fromText (gdaFilePath gda)) "trm"
termAfterFilePath = fromText (gdaAfterCommit gda) </>
replaceExtension (fromText (gdaFilePath gda)) "trm"
mb_tb = findEntryByPath (T.unpack (toTextIgnore termBeforeFilePath)) archive
mb_ta = findEntryByPath (T.unpack (toTextIgnore termAfterFilePath)) archive
case (mb_tb, mb_ta) of
(Just tb, Just ta) ->
let termToTree t = atermToTree (getATerm t) t
termBefore = replaceFileInfos (termToTree (readATerm (BL.unpack (fromEntry tb))))
termAfter = replaceFileInfos (termToTree (readATerm (BL.unpack (fromEntry ta))))
in Right (termBefore `antiunify` termAfter)
_ -> Left "Failed to load terms"
-- |Find all terms whose filename ends in one of the ids passed in
-- eg., find . -name '*-id.trm', where id is one of the passed in ints
antiUnifyTerms :: FilePath -> String -> [Int] -> Sh ()
antiUnifyTerms dir fname termIds = do
liftIO (putStrLn ("antiUnifyTerms: " ++ unwords (map show termIds)))
-- findWhen :: (FilePath -> Sh Bool) -> FilePath -> Sh [FilePath]
fs <- findWhen match (dir </> fromString "weaves")
ts <- loadTerms fs
if length ts < 1 then error "not enough terms to antiunify" else return ()
let (t,_) = fromJust (antiunifyList ts)
gv = (concat ["digraph {\n",unlines (treeToGraphviz t),"}"])
liftIO (writeFile fname gv)
where
match :: FilePath -> Sh Bool
match fp = return (or [("-" ++ show i ++ ".trm") `isSuffixOf` T.unpack (toTextIgnore fp) | i <- termIds])
loadTerms :: [FilePath] -> Sh [Term]
loadTerms = mapM loadTerm
loadTerm :: FilePath -> Sh Term
loadTerm fp = do
cs <- liftIO (readFile (T.unpack (toTextIgnore fp)))
let t = readATerm cs
length cs `seq` return (atermToTree (getATerm t) t)
generateGraphs :: FilePath -> Sh ()
generateGraphs dir = do
let archiveFP = T.unpack (toTextIgnore (dir </> "version-patterns.zip"))
initArchiveBS <- liftIO (BL.readFile archiveFP)
-- find version-pairs.hs in the archive
let mb_ds = readFromArchive initArchive "version-pairs.hs" :: Maybe [(T.Text,T.Text)]
initArchive = toArchive initArchiveBS
index = filesInArchive initArchive
case mb_ds of
Nothing -> return ()
Just ds -> do
liftIO (putStrLn "just ds")
forM_ ds $ \(commitBefore,commitAfter) -> do
let diffDir = T.unpack (commitBefore `T.append` ".." `T.append` commitAfter `T.append` "/")
inDir = filter (diffDir `isPrefixOf`) index
hs = filter (".hs" `isSuffixOf`) inDir
forM_ hs $ \h -> do
liftIO (putStrLn h)
let term = readFromArchive initArchive (fromText (T.pack h)) :: Maybe (Term,Subs,Subs)
case term of
Nothing -> return ()
Just (_,s1,s2) -> do
let destPath = "/tmp/dagit" </> directory (fromString h)
mkdir_p destPath
makeGraphFromSubs (destPath </> filename (fromString h) <.> "s1") s1
makeGraphFromSubs (destPath </> filename (fromString h) <.> "s2") s2
makeGraphFromSubs :: FilePath -> Subs -> Sh ()
makeGraphFromSubs fp subs = do
let ps = M.assocs (extractMap subs)
gs = map (\(k,v) -> (extractName k, treeToGraphviz v)) ps
cs = map (\(k,v) -> (k,unlines v)) gs
o k = (T.unpack (toTextIgnore fp)) ++ "-" ++ k ++ ".gv"
forM_ cs (\(k,v) -> liftIO (writeFile (o k) (concat ["digraph {\n",v,"}"])))
where extractName (Node (LBLString n) _) = n
extractName _ = ""
extractMap (Subs t) = t
unparseTerms :: FilePath -> Sh ()
unparseTerms dir = do
let archiveFP = T.unpack (toTextIgnore (dir </> "version-patterns.zip"))
initArchiveBS <- liftIO (BL.readFile archiveFP)
-- find version-pairs.hs in the archive
let mb_ds = readFromArchive initArchive "version-pairs.hs" :: Maybe [(T.Text,T.Text)]
initArchive = toArchive initArchiveBS
index = filesInArchive initArchive
case mb_ds of
Nothing -> return ()
Just ds -> do
liftIO (putStrLn "just ds")
forM_ ds $ \(commitBefore,commitAfter) -> do
let diffDir = T.unpack (commitBefore `T.append` ".." `T.append` commitAfter `T.append` "/")
inDir = filter (diffDir `isPrefixOf`) index
hs = filter (".hs" `isSuffixOf`) inDir
forM_ hs $ \h -> do
liftIO (putStrLn h)
let term = readFromArchive initArchive (fromText (T.pack h)) :: Maybe (Term,Subs,Subs)
case term of
Nothing -> return ()
Just (_,s1,s2) -> do
let destPath = "/tmp/dagit" </> directory (fromString h)
mkdir_p destPath
term2src s1 >>= liftIO . putStrLn
term2src s2 >>= liftIO . putStrLn
term2src :: Subs -> Sh String
term2src subs = do
let ps = M.assocs (extractMap subs)
gs = map (\(k,v) -> (extractName k, treeToATerm v)) ps
cs = map (\(k,v) -> (k, getATermFull v)) gs
return (show cs)
where extractName (Node (LBLString n) _) = n
extractName _ = ""
extractMap (Subs t) = t
weaveTerms :: FilePath -> Int -> Sh ()
weaveTerms dir num = do
let archiveFP = T.unpack (toTextIgnore (dir </> "version-patterns.zip"))
initArchiveBS <- liftIO (BL.readFile archiveFP)
-- find version-pairs.hs in the archive
let mb_ds = readFromArchive archive "version-pairs.hs" :: Maybe [(T.Text,T.Text)]
archive = toArchive initArchiveBS
case mb_ds of
Just ds -> do
liftIO (putStrLn ("length ds = " ++ show (length ds)))
-- process each diff pair
(_,ps,ts) <- flipFoldM (take num ds) (0,[],[]) $ \(count,ps,ts) (commitBefore,commitAfter) -> do
liftIO (putStrLn ("processing " ++ show (commitBefore,commitAfter)))
let commitDir = fromText commitBefore
liftIO (putStrLn ("Looking in " ++ show commitDir))
-- Look for the GitDiffArgs stored in the current commit directory of the archive
let gdasFilePath = commitDir </> "gdas.hs"
mb_gdas = readFromArchive archive gdasFilePath :: Maybe [GitDiffArgs]
case mb_gdas of
Just gdas -> do
liftIO (putStrLn ("Found gdas.hs"))
-- For each GitDiffArg we will weave them separately
flipFoldM gdas (count,ps,ts) $ \(prevCount,prevPs,prevTs) gda -> do
catchany_sh
-- Make sure we can process this file
(if fileFilter (gdaFilePath gda)
then do
liftIO (putStrLn ("weave using " ++ show gda))
let diffDir = fromText (commitBefore `T.append` ".." `T.append` commitAfter)
weaveFilePath = diffDir </> (replaceExtension (fromText (gdaFilePath gda)) "hs")
woven = weaveSh archive gda
case woven of
-- Something went wrong
Left e -> liftIO (putStrLn e) >> return (prevCount,prevPs,prevTs)
Right w -> do
let destPath = "weaves" </> directory weaveFilePath
outfp = destPath </> (filename (replaceExtension weaveFilePath "gv"))
outgvfps = [directory outfp </>
(fromText (toTextIgnore (basename outfp) `T.append`
"-" `T.append` T.pack (show x))) <.> "gv"
| x <- [(prevCount::Int)..]]
outtrmfps = [directory outfp </>
(fromText (toTextIgnore (basename outfp) `T.append`
"-" `T.append` T.pack (show x))) <.> "trm"
| x <- [(prevCount::Int)..]]
mkGV l = concat ["digraph {\n", unlines l,"}"]
gvs = map (mkGV . eTreeToGraphviz) ws'
ws' = extract2 w
terms = map treeToATerm (extract w)
ts' = map treeType ws'
ps' = let ws = extract w
in zip ws (map (size . toSizedTree) ws)
if length ps' /= length ts' then error "ps' /= ts'" else return ()
mkdir_p destPath
liftIO (forM_ (zip (map (T.unpack . toTextIgnore) outgvfps) gvs)
(\(fp,gv) -> do
putStrLn ("Writing: " ++ fp)
writeFile fp gv
putStrLn ("Wrote graphviz of weave to: " ++ fp)))
liftIO (forM_ (zip (map (T.unpack . toTextIgnore) outtrmfps) terms)
(\(fp,term) -> do
putStrLn ("Writing: " ++ fp)
writeFile fp (writeSharedATerm term)
putStrLn ("Wrote aterm of weave to: " ++ fp)))
return (prevCount+length ps',prevPs ++ ps',prevTs++ts')
else return (prevCount,prevPs,prevTs))
-- Log the error and move on
(\e -> do
liftIO (putStr "Error processingTerms: ")
liftIO (putStrLn (show e))
return (prevCount,prevPs,prevTs))
Nothing -> return (0,[],[])
if length ps /= length ts then error "ps /= ts" else return ()
let dists :: MismatchType -> [((LabeledTree,Int),Maybe MismatchType)] -> [Double]
dists ty xs = [ let -- score = fromIntegral (treedist t1 t2 (==))/fromIntegral(max s1 s2)
-- score = fromIntegral (treedist t1 t2 (==))/fromIntegral s1
scorel = fromIntegral (treedist t1 t2 (==))
scorer = fromIntegral (treedist t2 t1 (==))
-- score = min (scorel / fromIntegral s1)
-- (scorer / fromIntegral s2)
score = min scorel scorer / fromIntegral (max s1 s2)
in if ty1 == ty2 && ty1 == Just ty
then score
else 0
| ((t1,s1),ty1) <- xs, ((t2,s2),ty2) <- xs ]
csvShow xs = unlines (map csvShow' xs)
where
csvShow' ys = intercalate "," (map show ys)
pairs = zip ps ts
chunkSize = length pairs
forestBefore = dists MismatchTypeLeft pairs
forestAfter = dists MismatchTypeRight pairs
forestDelete = dists RightHoleType pairs
forestAdd = dists LeftHoleType pairs
liftIO (writeFile "treetypes.csv" (intercalate "," (map (show.fromEnum') ts)))
liftIO (writeFile "treesimilarity-before.csv" (csvShow (chunk chunkSize forestBefore)))
liftIO (writeFile "treesimilarity-after.csv" (csvShow (chunk chunkSize forestAfter)))
liftIO (writeFile "treesimilarity-delete.csv" (csvShow (chunk chunkSize forestDelete)))
liftIO (writeFile "treesimilarity-add.csv" (csvShow (chunk chunkSize forestAdd)))
-- liftIO (writeFile "treesimilarity-all.csv" (csvShow (chunk (length ps) (dists ps))))
Nothing -> return ()
weaveSh :: IsString a => Archive -> GitDiffArgs -> Either a (WeaveTree Bool)
weaveSh archive gda = do
let termBeforeFilePath = fromText (gdaBeforeCommit gda) </> replaceExtension (fromText (gdaFilePath gda)) "trm"
termAfterFilePath = fromText (gdaAfterCommit gda) </> replaceExtension (fromText (gdaFilePath gda)) "trm"
mb_tb = findEntryByPath (T.unpack (toTextIgnore termBeforeFilePath)) archive
mb_ta = findEntryByPath (T.unpack (toTextIgnore termAfterFilePath)) archive
case (mb_tb, mb_ta) of
(Just tb, Just ta) ->
let termToTree t = atermToTree (getATerm t) t
termBefore = termToTree (readATerm (BL.unpack (fromEntry tb)))
termAfter = termToTree (readATerm (BL.unpack (fromEntry ta)))
(y1,y2) = treediff termBefore termAfter (==)
w = weave y1 y2 False
in Right w
_ -> Left "Failed to load terms"
similarTrees :: FilePath -> Double -> Sh ()
similarTrees dir thres = do
let fps = map (\nm -> T.unpack (toTextIgnore (dir </> fromString ("treesimilarity-" ++ nm ++ ".csv")))) alts
alts = ["before","after","delete","add"]
-- d3 <- liftIO (modexp d2 sz sz)
liftIO (putStrLn ("Similarity threshold: " ++ show thres))
similars <- zip alts <$> mapM load fps
mapM_ dumpGV similars
where
dumpGV (prefix,m) = forM_ (M.toAscList m) $ \(k,is) -> do
let set = S.toAscList is
antiUnifyTerms dir ("antiunify-" ++ prefix ++ "-" ++ show k ++ ".gv") set
-- horribly inefficient, but for some reason the csv parser
-- treats the final newline in a file as a record. So,
-- we strip it out.
dropTrailingNewline [] = []
dropTrailingNewline xs | last xs == '\n' = init xs
| otherwise = xs
load fp = do
cs <- liftIO (readFile fp)
let csvDat = case parseCSV fp (dropTrailingNewline cs) of
Right c -> map read <$> c :: [[Double]]
Left e -> error (show e)
d = V.fromList (concat csvDat)
d2 = (>= thres) <$> d
sz = length csvDat
return (similarityMatrix d2 sz)
similarityMatrix m sz = similar
where
sm = chunk sz (V.toList m)
filterSimilar :: M.Map Int (S.Set Int) -> M.Map Int (S.Set Int)
filterSimilar m = M.fromList $ case mapAccumL go S.empty (M.toList m) of
(_, ys) -> catMaybes ys
where
go :: S.Set Int -> (Int, S.Set Int) -> (S.Set Int, Maybe (Int,S.Set Int))
go seen (i,rs) = (seen', irs)
where
seen' = S.singleton i `S.union` seen `S.union` rs
irs = if i `S.notMember` seen then Just (i,rs) else Nothing
similar :: M.Map Int (S.Set Int)
similar = filterSimilar $ M.fromList $ do
(i,r) <- zip [0..] sm
let js = elemIndices True r
guard (not (null js))
return (i,S.fromList js)
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-- * Visualize Differences
wtreeToGraphviz :: WeaveTree a -- ^ Tree to print
-> [String] -- ^ DOT-file lines
wtreeToGraphviz t = snd $ evalIDGen t wToGV
wpLabel :: WeavePoint a -> String
wpLabel (Match _) = "MATCH"
wpLabel (Mismatch _ _) = "MISMATCH"
wpLabel (RightHole _) = "RHOLE"
wpLabel (LeftHole _) = "LHOLE"
wpToGV :: WeavePoint a -> IDGen (Int, [String])
wpToGV wp = do
myID <- genID
let self = makeNode myID [cGreen] (wpLabel wp)
case wp of
Match t -> do (kidID, kidStrings) <- wToGV t
let kEdge = makeEdge myID kidID
return (myID, self:kEdge:kidStrings)
Mismatch a b -> do (kidID1, kidStrings1) <- wToGV a
(kidID2, kidStrings2) <- wToGV b
let kEdge1 = makeEdge myID kidID1
kEdge2 = makeEdge myID kidID2
return (myID, self:kEdge1:kEdge2:(kidStrings1++kidStrings2))
LeftHole t -> do (kidID, kidStrings) <- wToGV t
let kEdge = makeEdge myID kidID
return (myID, self:kEdge:kidStrings)
RightHole t -> do (kidID, kidStrings) <- wToGV t
let kEdge = makeEdge myID kidID
return (myID, self:kEdge:kidStrings)
wToGV :: WeaveTree a -> IDGen (Int, [String])
wToGV (WLeaf t) = do
myID <- genID
let self = makeNode myID [cGreen] "WLeaf"
(kidID, kidStrings) <- tToGV gvShowLabel t
let kidEdge = makeEdge myID kidID
return (myID, self:kidEdge:kidStrings)
wToGV (WNode lbl _ wps) = do
myID <- genID
let self = makeNode myID [cGreen] ("WNode:"++(gvShowLabel lbl))
processed <- mapM wpToGV wps
let (kIDs, kSs) = unzip processed
kidEdges = map (makeEdge myID) kIDs
return (myID, self:(kidEdges++(concat kSs)))
-- | This code is taken from the compose-hpc rulegen:
{-|
Take a LabeledTree and return a list of lines for the
corresponding graphviz DOT file.
-}
treeToGraphviz :: LabeledTree -- ^ Tree to print
-> [String] -- ^ DOT-file lines
treeToGraphviz t = snd $ evalIDGen t (tToGV gvShowLabel)
--
-- node attributes for different node types
--
tToGV :: (a -> String) -> Tree a -> IDGen (Int, [String])
tToGV showIt (Node label kids) = do
myID <- genID
--let self = makeNode myID [cRed] (gvShowLabel label)
let self = makeNode myID [cRed] (showIt label)
processedKids <- mapM (tToGV showIt) kids
let (kidIDs, kidStrings) = unzip processedKids
kidEdges = map (makeEdge myID) kidIDs
return (myID, self:(kidEdges++(concat kidStrings)))
eTreeToGraphviz :: Tree (Label,Maybe MismatchType) -> [String]
eTreeToGraphviz t = snd $ evalIDGen t (tToGV gvShowLabelMismatch)
gvShowLabel :: Label -> String
gvShowLabel (LBLString s) = s
gvShowLabel (LBLList ) = "LIST"
gvShowLabel (LBLInt i ) = show i
gvShowLabelMismatch :: (Label,Maybe MismatchType) -> String
gvShowLabelMismatch (l, Just m) = gvShowLabel l ++ ": " ++ show m
gvShowLabelMismatch (l, Nothing) = gvShowLabel l
-- use state monad for generating unique identifiers
type IDGen = State Int
-- generate sequence of unique ID numbers
genID :: IDGen Int
genID = do
i <- get
put (i+1)
return i
-- generate variables with a fixed prefix and a unique suffix. For
-- example, with prefix "x", a sequence of invocations of this
-- function will yield the names "x0", "x1", "x2", and so on.
genName :: String -> IDGen String
genName n = do
i <- genID
return $ n ++ (show i)
evalIDGen :: a -> (a -> IDGen b) -> b
evalIDGen x f = evalState (f x) 0
-- helper for common case with no attribute : avoid having to write Nothing
-- all over the place
makeEdge :: Int -> Int -> String
makeEdge i j = makeAttrEdge i j Nothing
-- node maker
makeNode :: Int -> [String] -> String -> String
makeNode i attrs lbl =
"NODE"++(show i)++" ["++a++"];"
where a = intercalate "," (("label=\""++(cleanlabel lbl)++"\""):attrs)
cGreen :: String
cGreen = "color=green"
cRed :: String
cRed = "color=red"
cBlue :: String
cBlue = "color=blue"
cBlack :: String
cBlack = "color=black"
aBold :: String
aBold = "style=bold"
--
-- edge makers
--
makeAttrEdge :: Int -> Int -> Maybe [String] -> String
makeAttrEdge i j Nothing = "NODE"++(show i)++" -> NODE"++(show j)++";"
makeAttrEdge i j (Just as) = "NODE"++(show i)++" -> NODE"++(show j)++" ["++a++"];"
where a = intercalate "," as
cleanlabel :: String -> String
cleanlabel lbl = filter (\c -> c /= '\\' && c /= '\'' && c /= '\"') lbl
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-- * Utility Functions
-- | Lazily pulls a Readable value out of the requested file in the archive.
readFromArchive :: Read a => Archive -> FilePath -> Maybe a
readFromArchive archive fp =
(read . BL.unpack . fromEntry) <$> findEntryByPath (T.unpack (toTextIgnore fp)) archive
-- | Like the normal withFile except that internally it uses
-- 'shelly' and 'liftIO' to make the type Sh instead of IO.
withFileSh :: String -> IOMode -> (Handle -> Sh r) -> Sh r
withFileSh fp mode f =
liftIO (bracket (openFile fp mode) hClose (\h -> shelly (f h)))
-- | We make an attempt to be somewhat atomic:
-- We throw ".tmp" onto the file extension, write to it in chunks
-- and when the chunks are written we move the file over top of
-- the requested file name.
writeFileInChunks :: String -> BL.ByteString -> Sh ()
writeFileInChunks fp bl = do
withFileSh (fp++".tmp") WriteMode $ \h -> do
forM_ (BL.toChunks bl) $ \b -> do
liftIO (B.hPut h b)
mv (fromText (T.pack (fp++".tmp")))
(fromText (T.pack fp))
-- | We're mostly interested in C at the moment, so that means
-- .c and .h files.
fileFilter :: T.Text -> Bool
fileFilter fp = (".java" `T.isSuffixOf` fp)
flipFoldM_ :: Monad m => [b] -> a -> (a -> b -> m a) -> m ()
flipFoldM_ xs a f = foldM_ f a xs
flipFoldM :: Monad m => [b] -> a -> (a -> b -> m a) -> m a
flipFoldM xs a f = foldM f a xs
-- | Remove file_infos from the tree
filterFileInfos :: LabeledTree -> Maybe LabeledTree
filterFileInfos tree = removeSubtrees (LBLString "file_info") tree
-- | Homogenize the file_infos in the tree
replaceFileInfos :: LabeledTree -> LabeledTree
replaceFileInfos t = replaceSubtrees (LBLString "file_info")
(Node (LBLString "file_info")
[Node (LBLString "\"compilerGenerated\"") []
,Node (LBLInt 0) []
,Node (LBLInt 0) []])
t
size :: SizedTree a -> Int
size (Node (_,s) _) = s
treeType :: Tree (a,Maybe b) -> Maybe b
treeType (Node (_,Just b) _) = Just b
treeType (Node (_,Nothing) kids) = foldl' (<|>) Nothing (map treeType kids)
chunk :: Int -> [a] -> [[a]]
chunk _ [] = []
chunk n xs = take n xs : chunk n (drop n xs)
fromEnum' :: Enum a => Maybe a -> Int
fromEnum' (Just a) = fromEnum a
fromEnum' Nothing = -1
-- Haskell doesn't know C99's bool type, so we use CChar
foreign import ccall "mult" c_mult :: Ptr CChar -> Ptr CChar -> Ptr CChar -> CInt -> IO ()
true :: Int -> Int -> Vector Bool
true nrs ncs = V.fromList (replicate (nrs*ncs) True)
-- | Computes x ^ y for an sz by sz matrix where
-- we use Bool as the field with 2 elements
modexp :: Vector Bool -> Int -> Int -> IO (Vector Bool)
modexp _ sz 0 = return (true sz sz)
modexp x sz y
| even y = do
z <- xx
mult z z sz
| otherwise = do
z <- xx
z' <- mult z z sz
mult x z' sz
where xx = mult x x sz
-- | Calculates an exponentiation of the matrix in the field with two elements.
-- Take a square matrix as a vector, the size of the matrix in one dimension,
-- the power to raise the matrix to and returns the result.
mult :: Vector Bool -> Vector Bool -> Int -> IO (Vector Bool)
mult x y sz = do
let len = V.length x
x' = toChar <$> x
y' = toChar <$> y
a <- mallocForeignPtrBytes len
b <- mallocForeignPtrBytes len
c <- mallocForeignPtrBytes len
withForeignPtr a $ \ptrX -> do
pokeArray ptrX (V.toList x')
withForeignPtr b $ \ptrY -> do
pokeArray ptrY (V.toList y')
withForeignPtr c $ \ptrC -> do
c_mult ptrX ptrY ptrC (fromIntegral sz)
V.map toBool <$> V.fromList <$> peekArray len ptrC
where
toBool :: CChar -> Bool
toBool = toEnum . fromEnum
toChar :: Bool -> CChar
toChar = toEnum . fromEnum
-----------------------------------------------------------------------
| dagit/edit-patterns | Main.hs | bsd-3-clause | 37,050 | 0 | 49 | 10,782 | 10,527 | 5,371 | 5,156 | 639 | 8 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
-----------------------------------------------------------------------------
-- |
-- Module : Text.CSL.Input.Bibtex
-- Copyright : (c) John MacFarlane
-- License : BSD-style (see LICENSE)
--
-- Maintainer : John MacFarlane <fiddlosopher@gmail.com>
-- Stability : unstable-- Portability : unportable
--
-----------------------------------------------------------------------------
module Text.CSL.Input.Bibtex
( readBibtex
, readBibtexString
, Lang(..)
, langToLocale
, getLangFromEnv
)
where
import Prelude
import Control.Applicative
import qualified Control.Exception as E
import Control.Monad
import Control.Monad.RWS hiding ((<>))
import Data.Char (isAlphaNum, isDigit, isUpper, toLower,
toUpper)
import Data.List (foldl', intercalate)
import Data.List.Split (splitOn, splitWhen, wordsBy)
import qualified Data.Map as Map
import Data.Maybe
import System.Environment (getEnvironment)
import Text.CSL.Compat.Pandoc (readLaTeX)
import Text.CSL.Exception (CiteprocException (ErrorReadingBib, ErrorReadingBibFile))
import Text.CSL.Parser (parseLocale)
import Text.CSL.Reference
import Text.CSL.Style (Agent (..), emptyAgent, CslTerm (..),
Formatted (..), Locale (..))
import Text.CSL.Util (onBlocks, protectCase, safeRead,
splitStrWhen, trim, unTitlecase)
import Text.Pandoc.Definition
import qualified Text.Pandoc.UTF8 as UTF8
import qualified Text.Pandoc.Walk as Walk
import Text.Parsec hiding (State, many, (<|>))
blocksToFormatted :: [Block] -> Bib Formatted
blocksToFormatted bs =
case bs of
[Plain xs] -> inlinesToFormatted xs
[Para xs] -> inlinesToFormatted xs
_ -> inlinesToFormatted $ Walk.query (:[]) bs
adjustSpans :: Lang -> Inline -> [Inline]
adjustSpans _ (Span ("",[],[]) xs) = xs
adjustSpans lang (RawInline (Format "latex") s)
| s == "\\hyphen" || s == "\\hyphen " = [Str "-"]
| otherwise = Walk.walk (concatMap (adjustSpans lang))
$ parseRawLaTeX lang s
adjustSpans _ x = [x]
parseRawLaTeX :: Lang -> String -> [Inline]
parseRawLaTeX lang ('\\':xs) =
case latex' contents of
[Para ys] -> f command ys
[Plain ys] -> f command ys
_ -> []
where (command', contents') = break (=='{') xs
command = trim command'
contents = drop 1 $ reverse $ drop 1 $ reverse contents'
f "mkbibquote" ils = [Quoted DoubleQuote ils]
f "mkbibemph" ils = [Emph ils]
f "mkbibitalic" ils = [Emph ils] -- TODO: italic/=emph
f "mkbibbold" ils = [Strong ils]
f "mkbibparens" ils = [Str "("] ++ ils ++ [Str ")"] -- TODO: ...
f "mkbibbrackets" ils = [Str "["] ++ ils ++ [Str "]"] -- TODO: ...
-- ... both should be nestable & should work in year fields
f "autocap" ils = ils -- TODO: should work in year fields
f "textnormal" ils = [Span ("",["nodecor"],[]) ils]
f "bibstring" [Str s] = [Str $ resolveKey' lang s]
f _ ils = [Span nullAttr ils]
parseRawLaTeX _ _ = []
inlinesToFormatted :: [Inline] -> Bib Formatted
inlinesToFormatted ils = do
lang <- gets localeLanguage
return $ Formatted $ Walk.walk (concatMap (adjustSpans lang)) ils
data Item = Item{ identifier :: String
, entryType :: String
, fields :: Map.Map String String
}
-- | Get 'Lang' from the environment variable LANG, defaulting to en-US.
getLangFromEnv :: IO Lang
getLangFromEnv = do
env <- getEnvironment
return $ case lookup "LANG" env of
Just x -> case splitWhen (\c -> c == '.' || c == '_' || c == '-') x of
(w:z:_) -> Lang w z
[w] | not (null w) -> Lang w mempty
_ -> Lang "en" "US"
Nothing -> Lang "en" "US"
-- | Parse a BibTeX or BibLaTeX file into a list of 'Reference's.
-- The first parameter is a predicate to filter identifiers.
-- If the second parameter is true, the file will be treated as
-- BibTeX; otherwse as BibLaTeX. If the third parameter is
-- true, an "untitlecase" transformation will be performed.
readBibtex :: (String -> Bool) -> Bool -> Bool -> FilePath -> IO [Reference]
readBibtex idpred isBibtex caseTransform f = do
contents <- UTF8.readFile f
E.catch (readBibtexString idpred isBibtex caseTransform contents)
(\e -> case e of
ErrorReadingBib es -> E.throwIO $ ErrorReadingBibFile f es
_ -> E.throwIO e)
-- | Like 'readBibtex' but operates on a String rather than a file.
readBibtexString :: (String -> Bool) -> Bool -> Bool -> String
-> IO [Reference]
readBibtexString idpred isBibtex caseTransform contents = do
lang <- getLangFromEnv
locale <- parseLocale (langToLocale lang)
case runParser (bibEntries <* eof) (Map.empty) "stdin" contents of
-- drop 8 to remove "stdin" + space
Left err -> E.throwIO $ ErrorReadingBib $ drop 8 $ show err
Right xs -> return $ mapMaybe
(itemToReference lang locale isBibtex caseTransform)
(filter (idpred . identifier)
(resolveCrossRefs isBibtex
xs))
type BibParser = Parsec String (Map.Map String String)
bibEntries :: BibParser [Item]
bibEntries = do
skipMany nonEntry
many (bibItem <* skipMany nonEntry)
where nonEntry = bibSkip <|>
try (char '@' >>
(bibComment <|> bibPreamble <|> bibString))
bibSkip :: BibParser ()
bibSkip = skipMany1 (satisfy (/='@'))
bibComment :: BibParser ()
bibComment = do
cistring "comment"
spaces
void inBraces <|> bibSkip <|> return ()
bibPreamble :: BibParser ()
bibPreamble = do
cistring "preamble"
spaces
void inBraces
bibString :: BibParser ()
bibString = do
cistring "string"
spaces
char '{'
spaces
(k,v) <- entField
char '}'
updateState (Map.insert k v)
return ()
inBraces :: BibParser String
inBraces = try $ do
char '{'
res <- manyTill
( many1 (noneOf "{}\\")
<|> (char '\\' >> ( (char '{' >> return "\\{")
<|> (char '}' >> return "\\}")
<|> return "\\"))
<|> (braced <$> inBraces)
) (char '}')
return $ concat res
braced :: String -> String
braced s = "{" ++ s ++ "}"
inQuotes :: BibParser String
inQuotes = do
char '"'
concat <$> manyTill ( many1 (noneOf "\"\\{")
<|> (char '\\' >> (\c -> ['\\',c]) <$> anyChar)
<|> braced <$> inBraces
) (char '"')
fieldName :: BibParser String
fieldName =
resolveAlias . map toLower <$> many1 (letter <|> digit <|> oneOf "-_:+")
isBibtexKeyChar :: Char -> Bool
isBibtexKeyChar c = isAlphaNum c || c `elem` ".:;?!`'()/*@_+=-[]*&"
bibItem :: BibParser Item
bibItem = do
char '@'
enttype <- map toLower <$> many1 letter
spaces
char '{'
spaces
entid <- many1 (satisfy isBibtexKeyChar)
spaces
char ','
spaces
entfields <- entField `sepEndBy` (char ',' >> spaces)
spaces
char '}'
return $ Item entid enttype (Map.fromList entfields)
entField :: BibParser (String, String)
entField = do
k <- fieldName
spaces
char '='
spaces
vs <- (expandString <|> inQuotes <|> inBraces <|> rawWord) `sepBy`
try (spaces >> char '#' >> spaces)
spaces
return (k, concat vs)
resolveAlias :: String -> String
resolveAlias "archiveprefix" = "eprinttype"
resolveAlias "primaryclass" = "eprintclass"
resolveAlias s = s
rawWord :: BibParser String
rawWord = many1 alphaNum
expandString :: BibParser String
expandString = do
k <- fieldName
strs <- getState
case Map.lookup k strs of
Just v -> return v
Nothing -> return k -- return raw key if not found
cistring :: String -> BibParser String
cistring s = try (go s)
where go [] = return []
go (c:cs) = do
x <- char (toLower c) <|> char (toUpper c)
xs <- go cs
return (x:xs)
resolveCrossRefs :: Bool -> [Item] -> [Item]
resolveCrossRefs isBibtex entries =
map (resolveCrossRef isBibtex entries) entries
splitKeys :: String -> [String]
splitKeys = wordsBy (\c -> c == ' ' || c == ',')
getXrefFields :: Bool -> Item -> [Item] -> String -> [(String, String)]
getXrefFields isBibtex baseEntry entries keys = do
let keys' = splitKeys keys
xrefEntry <- [e | e <- entries, identifier e `elem` keys']
(k, v) <- Map.toList $ fields xrefEntry
if k == "crossref" || k == "xdata"
then do
xs <- mapM (getXrefFields isBibtex baseEntry entries)
(splitKeys v)
(x, y) <- xs
guard $ isNothing $ Map.lookup x $ fields xrefEntry
return (x, y)
else do
k' <- if isBibtex
then return k
else transformKey (entryType xrefEntry) (entryType baseEntry) k
guard $ isNothing $ Map.lookup k' $ fields baseEntry
return (k',v)
resolveCrossRef :: Bool -> [Item] -> Item -> Item
resolveCrossRef isBibtex entries entry =
Map.foldrWithKey go entry (fields entry)
where go key val entry' =
if key == "crossref" || key == "xdata"
then entry'{ fields = fields entry' <>
Map.fromList (getXrefFields isBibtex
entry entries val) }
else entry'
-- transformKey source target key
-- derived from Appendix C of bibtex manual
transformKey :: String -> String -> String -> [String]
transformKey _ _ "ids" = []
transformKey _ _ "crossref" = []
transformKey _ _ "xref" = []
transformKey _ _ "entryset" = []
transformKey _ _ "entrysubtype" = []
transformKey _ _ "execute" = []
transformKey _ _ "label" = []
transformKey _ _ "options" = []
transformKey _ _ "presort" = []
transformKey _ _ "related" = []
transformKey _ _ "relatedoptions" = []
transformKey _ _ "relatedstring" = []
transformKey _ _ "relatedtype" = []
transformKey _ _ "shorthand" = []
transformKey _ _ "shorthandintro" = []
transformKey _ _ "sortkey" = []
transformKey x y "author"
| x `elem` ["mvbook", "book"] &&
y `elem` ["inbook", "bookinbook", "suppbook"] = ["bookauthor", "author"]
-- note: this next clause is not in the biblatex manual, but it makes
-- sense in the context of CSL conversion:
transformKey x y "author"
| x == "mvbook" && y == "book" = ["bookauthor", "author"]
transformKey "mvbook" y z
| y `elem` ["book", "inbook", "bookinbook", "suppbook"] = standardTrans z
transformKey x y z
| x `elem` ["mvcollection", "mvreference"] &&
y `elem` ["collection", "reference", "incollection", "inreference",
"suppcollection"] = standardTrans z
transformKey "mvproceedings" y z
| y `elem` ["proceedings", "inproceedings"] = standardTrans z
transformKey "book" y z
| y `elem` ["inbook", "bookinbook", "suppbook"] = bookTrans z
transformKey x y z
| x `elem` ["collection", "reference"] &&
y `elem` ["incollection", "inreference", "suppcollection"] = bookTrans z
transformKey "proceedings" "inproceedings" z = bookTrans z
transformKey "periodical" y z
| y `elem` ["article", "suppperiodical"] =
case z of
"title" -> ["journaltitle"]
"subtitle" -> ["journalsubtitle"]
"shorttitle" -> []
"sorttitle" -> []
"indextitle" -> []
"indexsorttitle" -> []
_ -> [z]
transformKey _ _ x = [x]
standardTrans :: String -> [String]
standardTrans z =
case z of
"title" -> ["maintitle"]
"subtitle" -> ["mainsubtitle"]
"titleaddon" -> ["maintitleaddon"]
"shorttitle" -> []
"sorttitle" -> []
"indextitle" -> []
"indexsorttitle" -> []
_ -> [z]
bookTrans :: String -> [String]
bookTrans z =
case z of
"title" -> ["booktitle"]
"subtitle" -> ["booksubtitle"]
"titleaddon" -> ["booktitleaddon"]
"shorttitle" -> []
"sorttitle" -> []
"indextitle" -> []
"indexsorttitle" -> []
_ -> [z]
-- | A representation of a language and localization.
data Lang = Lang String String -- e.g. "en" "US"
-- | Prints a 'Lang' in BCP 47 format.
langToLocale :: Lang -> String
langToLocale (Lang x y) = x ++ ('-':y)
-- Biblatex Localization Keys (see Biblatex manual)
-- Currently we only map a subset likely to be used in Biblatex *databases*
-- (in fields such as `type`, and via `\bibstring{}` commands).
resolveKey :: Lang -> Formatted -> Formatted
resolveKey lang (Formatted ils) = Formatted (Walk.walk go ils)
where go (Str s) = Str $ resolveKey' lang s
go x = x
-- biblatex localization keys, from files at
-- http://github.com/plk/biblatex/tree/master/tex/latex/biblatex/lbx
-- Some keys missing in these were added from csl locale files at
-- http://github.com/citation-style-language/locales -- labeled "csl"
resolveKey' :: Lang -> String -> String
resolveKey' (Lang "ca" "AD") k =
case map toLower k of
"inpreparation" -> "en preparació"
"submitted" -> "enviat"
"forthcoming" -> "disponible en breu"
"inpress" -> "a impremta"
"prepublished" -> "pre-publicat"
"mathesis" -> "tesi de màster"
"phdthesis" -> "tesi doctoral"
"candthesis" -> "tesi de candidatura"
"techreport" -> "informe tècnic"
"resreport" -> "informe de recerca"
"software" -> "programari"
"datacd" -> "CD de dades"
"audiocd" -> "CD d’àudio"
"patent" -> "patent"
"patentde" -> "patent alemana"
"patenteu" -> "patent europea"
"patentfr" -> "patent francesa"
"patentuk" -> "patent britànica"
"patentus" -> "patent estatunidenca"
"patreq" -> "soŀlicitud de patent"
"patreqde" -> "soŀlicitud de patent alemana"
"patreqeu" -> "soŀlicitud de patent europea"
"patreqfr" -> "soŀlicitud de patent francesa"
"patrequk" -> "soŀlicitud de patent britànica"
"patrequs" -> "soŀlicitud de patent estatunidenca"
"countryde" -> "Alemanya"
"countryeu" -> "Unió Europea"
"countryep" -> "Unió Europea"
"countryfr" -> "França"
"countryuk" -> "Regne Unit"
"countryus" -> "Estats Units d’Amèrica"
"newseries" -> "sèrie nova"
"oldseries" -> "sèrie antiga"
_ -> k
resolveKey' (Lang "da" "DK") k =
case map toLower k of
-- "inpreparation" -> "" -- missing
-- "submitted" -> "" -- missing
"forthcoming" -> "kommende" -- csl
"inpress" -> "i tryk" -- csl
-- "prepublished" -> "" -- missing
"mathesis" -> "speciale"
"phdthesis" -> "ph.d.-afhandling"
"candthesis" -> "kandidatafhandling"
"techreport" -> "teknisk rapport"
"resreport" -> "forskningsrapport"
"software" -> "software"
"datacd" -> "data-cd"
"audiocd" -> "lyd-cd"
"patent" -> "patent"
"patentde" -> "tysk patent"
"patenteu" -> "europæisk patent"
"patentfr" -> "fransk patent"
"patentuk" -> "britisk patent"
"patentus" -> "amerikansk patent"
"patreq" -> "ansøgning om patent"
"patreqde" -> "ansøgning om tysk patent"
"patreqeu" -> "ansøgning om europæisk patent"
"patreqfr" -> "ansøgning om fransk patent"
"patrequk" -> "ansøgning om britisk patent"
"patrequs" -> "ansøgning om amerikansk patent"
"countryde" -> "Tyskland"
"countryeu" -> "Europæiske Union"
"countryep" -> "Europæiske Union"
"countryfr" -> "Frankrig"
"countryuk" -> "Storbritanien"
"countryus" -> "USA"
"newseries" -> "ny serie"
"oldseries" -> "gammel serie"
_ -> k
resolveKey' (Lang "de" "DE") k =
case map toLower k of
"inpreparation" -> "in Vorbereitung"
"submitted" -> "eingereicht"
"forthcoming" -> "im Erscheinen"
"inpress" -> "im Druck"
"prepublished" -> "Vorveröffentlichung"
"mathesis" -> "Magisterarbeit"
"phdthesis" -> "Dissertation"
-- "candthesis" -> "" -- missing
"techreport" -> "Technischer Bericht"
"resreport" -> "Forschungsbericht"
"software" -> "Computer-Software"
"datacd" -> "CD-ROM"
"audiocd" -> "Audio-CD"
"patent" -> "Patent"
"patentde" -> "deutsches Patent"
"patenteu" -> "europäisches Patent"
"patentfr" -> "französisches Patent"
"patentuk" -> "britisches Patent"
"patentus" -> "US-Patent"
"patreq" -> "Patentanmeldung"
"patreqde" -> "deutsche Patentanmeldung"
"patreqeu" -> "europäische Patentanmeldung"
"patreqfr" -> "französische Patentanmeldung"
"patrequk" -> "britische Patentanmeldung"
"patrequs" -> "US-Patentanmeldung"
"countryde" -> "Deutschland"
"countryeu" -> "Europäische Union"
"countryep" -> "Europäische Union"
"countryfr" -> "Frankreich"
"countryuk" -> "Großbritannien"
"countryus" -> "USA"
"newseries" -> "neue Folge"
"oldseries" -> "alte Folge"
_ -> k
resolveKey' (Lang "en" "US") k =
case map toLower k of
"audiocd" -> "audio CD"
"by" -> "by"
"candthesis" -> "Candidate thesis"
"countryde" -> "Germany"
"countryep" -> "European Union"
"countryeu" -> "European Union"
"countryfr" -> "France"
"countryuk" -> "United Kingdom"
"countryus" -> "United States of America"
"datacd" -> "data CD"
"edition" -> "ed."
"forthcoming" -> "forthcoming"
"inpreparation" -> "in preparation"
"inpress" -> "in press"
"introduction" -> "introduction"
"jourser" -> "ser."
"mathesis" -> "Master’s thesis"
"newseries" -> "new series"
"nodate" -> "n. d."
"number" -> "no."
"numbers" -> "nos."
"oldseries" -> "old series"
"patent" -> "patent"
"patentde" -> "German patent"
"patenteu" -> "European patent"
"patentfr" -> "French patent"
"patentuk" -> "British patent"
"patentus" -> "U.S. patent"
"patreq" -> "patent request"
"patreqde" -> "German patent request"
"patreqeu" -> "European patent request"
"patreqfr" -> "French patent request"
"patrequk" -> "British patent request"
"patrequs" -> "U.S. patent request"
"phdthesis" -> "PhD thesis"
"prepublished" -> "pre-published"
"pseudonym" -> "pseud."
"recorded" -> "recorded"
"resreport" -> "research report"
"reviewof" -> "Review of"
"revisededition" -> "rev. ed."
"software" -> "computer software"
"submitted" -> "submitted"
"techreport" -> "technical report"
"volume" -> "vol."
_ -> k
resolveKey' (Lang "es" "ES") k =
case map toLower k of
-- "inpreparation" -> "" -- missing
-- "submitted" -> "" -- missing
"forthcoming" -> "previsto" -- csl
"inpress" -> "en imprenta" -- csl
-- "prepublished" -> "" -- missing
"mathesis" -> "Tesis de licenciatura"
"phdthesis" -> "Tesis doctoral"
-- "candthesis" -> "" -- missing
"techreport" -> "informe técnico"
-- "resreport" -> "" -- missing
-- "software" -> "" -- missing
-- "datacd" -> "" -- missing
-- "audiocd" -> "" -- missing
"patent" -> "patente"
"patentde" -> "patente alemana"
"patenteu" -> "patente europea"
"patentfr" -> "patente francesa"
"patentuk" -> "patente británica"
"patentus" -> "patente americana"
"patreq" -> "solicitud de patente"
"patreqde" -> "solicitud de patente alemana"
"patreqeu" -> "solicitud de patente europea"
"patreqfr" -> "solicitud de patente francesa"
"patrequk" -> "solicitud de patente británica"
"patrequs" -> "solicitud de patente americana"
"countryde" -> "Alemania"
"countryeu" -> "Unión Europea"
"countryep" -> "Unión Europea"
"countryfr" -> "Francia"
"countryuk" -> "Reino Unido"
"countryus" -> "Estados Unidos de América"
"newseries" -> "nueva época"
"oldseries" -> "antigua época"
_ -> k
resolveKey' (Lang "fi" "FI") k =
case map toLower k of
-- "inpreparation" -> "" -- missing
-- "submitted" -> "" -- missing
"forthcoming" -> "tulossa" -- csl
"inpress" -> "painossa" -- csl
-- "prepublished" -> "" -- missing
"mathesis" -> "tutkielma"
"phdthesis" -> "tohtorinväitöskirja"
"candthesis" -> "kandidat"
"techreport" -> "tekninen raportti"
"resreport" -> "tutkimusraportti"
"software" -> "ohjelmisto"
"datacd" -> "data-CD"
"audiocd" -> "ääni-CD"
"patent" -> "patentti"
"patentde" -> "saksalainen patentti"
"patenteu" -> "Euroopan Unionin patentti"
"patentfr" -> "ranskalainen patentti"
"patentuk" -> "englantilainen patentti"
"patentus" -> "yhdysvaltalainen patentti"
"patreq" -> "patenttihakemus"
"patreqde" -> "saksalainen patenttihakemus"
"patreqeu" -> "Euroopan Unionin patenttihakemus"
"patreqfr" -> "ranskalainen patenttihakemus"
"patrequk" -> "englantilainen patenttihakemus"
"patrequs" -> "yhdysvaltalainen patenttihakemus"
"countryde" -> "Saksa"
"countryeu" -> "Euroopan Unioni"
"countryep" -> "Euroopan Unioni"
"countryfr" -> "Ranska"
"countryuk" -> "Iso-Britannia"
"countryus" -> "Yhdysvallat"
"newseries" -> "uusi sarja"
"oldseries" -> "vanha sarja"
_ -> k
resolveKey' (Lang "fr" "FR") k =
case map toLower k of
"inpreparation" -> "en préparation"
"submitted" -> "soumis"
"forthcoming" -> "à paraître"
"inpress" -> "sous presse"
"prepublished" -> "prépublié"
"mathesis" -> "mémoire de master"
"phdthesis" -> "thèse de doctorat"
"candthesis" -> "thèse de candidature"
"techreport" -> "rapport technique"
"resreport" -> "rapport scientifique"
"software" -> "logiciel"
"datacd" -> "cédérom"
"audiocd" -> "disque compact audio"
"patent" -> "brevet"
"patentde" -> "brevet allemand"
"patenteu" -> "brevet européen"
"patentfr" -> "brevet français"
"patentuk" -> "brevet britannique"
"patentus" -> "brevet américain"
"patreq" -> "demande de brevet"
"patreqde" -> "demande de brevet allemand"
"patreqeu" -> "demande de brevet européen"
"patreqfr" -> "demande de brevet français"
"patrequk" -> "demande de brevet britannique"
"patrequs" -> "demande de brevet américain"
"countryde" -> "Allemagne"
"countryeu" -> "Union européenne"
"countryep" -> "Union européenne"
"countryfr" -> "France"
"countryuk" -> "Royaume-Uni"
"countryus" -> "États-Unis"
"newseries" -> "nouvelle série"
"oldseries" -> "ancienne série"
_ -> k
resolveKey' (Lang "it" "IT") k =
case map toLower k of
-- "inpreparation" -> "" -- missing
-- "submitted" -> "" -- missing
"forthcoming" -> "futuro" -- csl
"inpress" -> "in stampa"
-- "prepublished" -> "" -- missing
"mathesis" -> "tesi di laurea magistrale"
"phdthesis" -> "tesi di dottorato"
-- "candthesis" -> "" -- missing
"techreport" -> "rapporto tecnico"
"resreport" -> "rapporto di ricerca"
-- "software" -> "" -- missing
-- "datacd" -> "" -- missing
-- "audiocd" -> "" -- missing
"patent" -> "brevetto"
"patentde" -> "brevetto tedesco"
"patenteu" -> "brevetto europeo"
"patentfr" -> "brevetto francese"
"patentuk" -> "brevetto britannico"
"patentus" -> "brevetto americano"
"patreq" -> "brevetto richiesto"
"patreqde" -> "brevetto tedesco richiesto"
"patreqeu" -> "brevetto europeo richiesto"
"patreqfr" -> "brevetto francese richiesto"
"patrequk" -> "brevetto britannico richiesto"
"patrequs" -> "brevetto U.S.A. richiesto"
"countryde" -> "Germania"
"countryeu" -> "Unione Europea"
"countryep" -> "Unione Europea"
"countryfr" -> "Francia"
"countryuk" -> "Regno Unito"
"countryus" -> "Stati Uniti d’America"
"newseries" -> "nuova serie"
"oldseries" -> "vecchia serie"
_ -> k
resolveKey' (Lang "nl" "NL") k =
case map toLower k of
"inpreparation" -> "in voorbereiding"
"submitted" -> "ingediend"
"forthcoming" -> "onderweg"
"inpress" -> "in druk"
"prepublished" -> "voorpublicatie"
"mathesis" -> "masterscriptie"
"phdthesis" -> "proefschrift"
-- "candthesis" -> "" -- missing
"techreport" -> "technisch rapport"
"resreport" -> "onderzoeksrapport"
"software" -> "computersoftware"
"datacd" -> "cd-rom"
"audiocd" -> "audio-cd"
"patent" -> "patent"
"patentde" -> "Duits patent"
"patenteu" -> "Europees patent"
"patentfr" -> "Frans patent"
"patentuk" -> "Brits patent"
"patentus" -> "Amerikaans patent"
"patreq" -> "patentaanvraag"
"patreqde" -> "Duitse patentaanvraag"
"patreqeu" -> "Europese patentaanvraag"
"patreqfr" -> "Franse patentaanvraag"
"patrequk" -> "Britse patentaanvraag"
"patrequs" -> "Amerikaanse patentaanvraag"
"countryde" -> "Duitsland"
"countryeu" -> "Europese Unie"
"countryep" -> "Europese Unie"
"countryfr" -> "Frankrijk"
"countryuk" -> "Verenigd Koninkrijk"
"countryus" -> "Verenigde Staten van Amerika"
"newseries" -> "nieuwe reeks"
"oldseries" -> "oude reeks"
_ -> k
resolveKey' (Lang "pl" "PL") k =
case map toLower k of
"inpreparation" -> "przygotowanie"
"submitted" -> "prezentacja"
"forthcoming" -> "przygotowanie"
"inpress" -> "wydrukowane"
"prepublished" -> "przedwydanie"
"mathesis" -> "praca magisterska"
"phdthesis" -> "praca doktorska"
"techreport" -> "sprawozdanie techniczne"
"resreport" -> "sprawozdanie naukowe"
"software" -> "oprogramowanie"
"datacd" -> "CD-ROM"
"audiocd" -> "audio CD"
"patent" -> "patent"
"patentde" -> "patent Niemiec"
"patenteu" -> "patent Europy"
"patentfr" -> "patent Francji"
"patentuk" -> "patent Wielkiej Brytanji"
"patentus" -> "patent USA"
"patreq" -> "podanie na patent"
"patreqeu" -> "podanie na patent Europy"
"patrequs" -> "podanie na patent USA"
"countryde" -> "Niemcy"
"countryeu" -> "Unia Europejska"
"countryep" -> "Unia Europejska"
"countryfr" -> "Francja"
"countryuk" -> "Wielka Brytania"
"countryus" -> "Stany Zjednoczone Ameryki"
"newseries" -> "nowa serja"
"oldseries" -> "stara serja"
_ -> k
resolveKey' (Lang "pt" "PT") k =
case map toLower k of
-- "candthesis" -> "" -- missing
"techreport" -> "relatório técnico"
"resreport" -> "relatório de pesquisa"
"software" -> "software"
"datacd" -> "CD-ROM"
"patent" -> "patente"
"patentde" -> "patente alemã"
"patenteu" -> "patente européia"
"patentfr" -> "patente francesa"
"patentuk" -> "patente britânica"
"patentus" -> "patente americana"
"patreq" -> "pedido de patente"
"patreqde" -> "pedido de patente alemã"
"patreqeu" -> "pedido de patente européia"
"patreqfr" -> "pedido de patente francesa"
"patrequk" -> "pedido de patente britânica"
"patrequs" -> "pedido de patente americana"
"countryde" -> "Alemanha"
"countryeu" -> "União Europeia"
"countryep" -> "União Europeia"
"countryfr" -> "França"
"countryuk" -> "Reino Unido"
"countryus" -> "Estados Unidos da América"
"newseries" -> "nova série"
"oldseries" -> "série antiga"
-- "inpreparation" -> "" -- missing
"forthcoming" -> "a publicar" -- csl
"inpress" -> "na imprensa"
-- "prepublished" -> "" -- missing
"mathesis" -> "tese de mestrado"
"phdthesis" -> "tese de doutoramento"
"audiocd" -> "CD áudio"
_ -> k
resolveKey' (Lang "pt" "BR") k =
case map toLower k of
-- "candthesis" -> "" -- missing
"techreport" -> "relatório técnico"
"resreport" -> "relatório de pesquisa"
"software" -> "software"
"datacd" -> "CD-ROM"
"patent" -> "patente"
"patentde" -> "patente alemã"
"patenteu" -> "patente européia"
"patentfr" -> "patente francesa"
"patentuk" -> "patente britânica"
"patentus" -> "patente americana"
"patreq" -> "pedido de patente"
"patreqde" -> "pedido de patente alemã"
"patreqeu" -> "pedido de patente européia"
"patreqfr" -> "pedido de patente francesa"
"patrequk" -> "pedido de patente britânica"
"patrequs" -> "pedido de patente americana"
"countryde" -> "Alemanha"
"countryeu" -> "União Europeia"
"countryep" -> "União Europeia"
"countryfr" -> "França"
"countryuk" -> "Reino Unido"
"countryus" -> "Estados Unidos da América"
"newseries" -> "nova série"
"oldseries" -> "série antiga"
"inpreparation" -> "em preparação"
"forthcoming" -> "aceito para publicação"
"inpress" -> "no prelo"
"prepublished" -> "pré-publicado"
"mathesis" -> "dissertação de mestrado"
"phdthesis" -> "tese de doutorado"
"audiocd" -> "CD de áudio"
_ -> k
resolveKey' (Lang "sv" "SE") k =
case map toLower k of
-- "inpreparation" -> "" -- missing
-- "submitted" -> "" -- missing
"forthcoming" -> "kommande" -- csl
"inpress" -> "i tryck" -- csl
-- "prepublished" -> "" -- missing
"mathesis" -> "examensarbete"
"phdthesis" -> "doktorsavhandling"
"candthesis" -> "kandidatavhandling"
"techreport" -> "teknisk rapport"
"resreport" -> "forskningsrapport"
"software" -> "datorprogram"
"datacd" -> "data-cd"
"audiocd" -> "ljud-cd"
"patent" -> "patent"
"patentde" -> "tyskt patent"
"patenteu" -> "europeiskt patent"
"patentfr" -> "franskt patent"
"patentuk" -> "brittiskt patent"
"patentus" -> "amerikanskt patent"
"patreq" -> "patentansökan"
"patreqde" -> "ansökan om tyskt patent"
"patreqeu" -> "ansökan om europeiskt patent"
"patreqfr" -> "ansökan om franskt patent"
"patrequk" -> "ansökan om brittiskt patent"
"patrequs" -> "ansökan om amerikanskt patent"
"countryde" -> "Tyskland"
"countryeu" -> "Europeiska unionen"
"countryep" -> "Europeiska unionen"
"countryfr" -> "Frankrike"
"countryuk" -> "Storbritannien"
"countryus" -> "USA"
"newseries" -> "ny följd"
"oldseries" -> "gammal följd"
_ -> k
resolveKey' _ k = resolveKey' (Lang "en" "US") k
parseMonth :: String -> Maybe Int
parseMonth s =
case map toLower s of
"jan" -> Just 1
"feb" -> Just 2
"mar" -> Just 3
"apr" -> Just 4
"may" -> Just 5
"jun" -> Just 6
"jul" -> Just 7
"aug" -> Just 8
"sep" -> Just 9
"oct" -> Just 10
"nov" -> Just 11
"dec" -> Just 12
_ -> safeRead s
data BibState = BibState{
untitlecase :: Bool
, localeLanguage :: Lang
}
type Bib = RWST Item () BibState Maybe
notFound :: String -> Bib a
notFound f = fail $ f ++ " not found"
getField :: String -> Bib Formatted
getField f = do
fs <- asks fields
case Map.lookup f fs of
Just x -> latex x
Nothing -> notFound f
getPeriodicalTitle :: String -> Bib Formatted
getPeriodicalTitle f = do
fs <- asks fields
case Map.lookup f fs of
Just x -> blocksToFormatted $ onBlocks protectCase $ latex' $ trim x
Nothing -> notFound f
getTitle :: String -> Bib Formatted
getTitle f = do
fs <- asks fields
case Map.lookup f fs of
Just x -> latexTitle x
Nothing -> notFound f
getShortTitle :: Bool -> String -> Bib Formatted
getShortTitle requireColon f = do
fs <- asks fields
utc <- gets untitlecase
let processTitle = if utc then onBlocks unTitlecase else id
case Map.lookup f fs of
Just x -> case processTitle $ latex' x of
bs | not requireColon || containsColon bs ->
blocksToFormatted $ upToColon bs
| otherwise -> return mempty
Nothing -> notFound f
containsColon :: [Block] -> Bool
containsColon [Para xs] = Str ":" `elem` xs
containsColon [Plain xs] = containsColon [Para xs]
containsColon _ = False
upToColon :: [Block] -> [Block]
upToColon [Para xs] = [Para $ takeWhile (/= Str ":") xs]
upToColon [Plain xs] = upToColon [Para xs]
upToColon bs = bs
getDates :: String -> Bib [RefDate]
getDates f = parseEDTFDate <$> getRawField f
isNumber :: String -> Bool
isNumber ('-':d:ds) = all isDigit (d:ds)
isNumber (d:ds) = all isDigit (d:ds)
isNumber _ = False
-- A negative (BC) year might be written with -- or --- in bibtex:
fixLeadingDash :: String -> String
fixLeadingDash (c:d:ds)
| (c == '–' || c == '—') && isDigit d = '-':d:ds
fixLeadingDash xs = xs
getOldDates :: String -> Bib [RefDate]
getOldDates prefix = do
year' <- fixLeadingDash <$> getRawField (prefix ++ "year") <|> return ""
month' <- (parseMonth
<$> getRawField (prefix ++ "month")) <|> return Nothing
day' <- (safeRead <$> getRawField (prefix ++ "day")) <|> return Nothing
endyear' <- (fixLeadingDash <$> getRawField (prefix ++ "endyear"))
<|> return ""
endmonth' <- (parseMonth <$> getRawField (prefix ++ "endmonth"))
<|> return Nothing
endday' <- (safeRead <$> getRawField (prefix ++ "endday")) <|> return Nothing
let start' = RefDate { year = safeRead year'
, month = month'
, season = Nothing
, day = day'
, other = Literal $ if isNumber year' then "" else year'
, circa = False
}
let end' = RefDate { year = safeRead endyear'
, month = endmonth'
, day = endday'
, season = Nothing
, other = Literal $ if isNumber endyear' then "" else endyear'
, circa = False
}
let hasyear r = isJust (year r)
return $ filter hasyear [start', end']
getRawField :: String -> Bib String
getRawField f = do
fs <- asks fields
case Map.lookup f fs of
Just x -> return x
Nothing -> notFound f
getAuthorList :: Options -> String -> Bib [Agent]
getAuthorList opts f = do
fs <- asks fields
case Map.lookup f fs of
Just x -> latexAuthors opts x
Nothing -> notFound f
getLiteralList :: String -> Bib [Formatted]
getLiteralList f = do
fs <- asks fields
case Map.lookup f fs of
Just x -> toLiteralList $ latex' x
Nothing -> notFound f
-- separates items with semicolons
getLiteralList' :: String -> Bib Formatted
getLiteralList' f = (Formatted . intercalate [Str ";", Space] . map unFormatted)
<$> getLiteralList f
splitByAnd :: [Inline] -> [[Inline]]
splitByAnd = splitOn [Space, Str "and", Space]
toLiteralList :: [Block] -> Bib [Formatted]
toLiteralList [Para xs] =
mapM inlinesToFormatted $ splitByAnd xs
toLiteralList [Plain xs] = toLiteralList [Para xs]
toLiteralList _ = mzero
toAuthorList :: Options -> [Block] -> Bib [Agent]
toAuthorList opts [Para xs] =
filter (/= emptyAgent) <$> mapM (toAuthor opts) (splitByAnd xs)
toAuthorList opts [Plain xs] = toAuthorList opts [Para xs]
toAuthorList _ _ = mzero
toAuthor :: Options -> [Inline] -> Bib Agent
toAuthor _ [Str "others"] =
return
Agent { givenName = []
, droppingPart = mempty
, nonDroppingPart = mempty
, familyName = mempty
, nameSuffix = mempty
, literal = Formatted [Str "others"]
, commaSuffix = False
, parseNames = False
}
toAuthor _ [Span ("",[],[]) ils] =
return -- corporate author
Agent { givenName = []
, droppingPart = mempty
, nonDroppingPart = mempty
, familyName = mempty
, nameSuffix = mempty
, literal = Formatted ils
, commaSuffix = False
, parseNames = False
}
-- extended BibLaTeX name format - see #266
toAuthor _ ils@(Str ys:_) | '=' `elem` ys = do
let commaParts = splitWhen (== Str ",")
$ splitStrWhen (\c -> c == ',' || c == '=' || c == '\160')
$ ils
let addPart ag (Str "given" : Str "=" : xs) =
ag{ givenName = givenName ag ++ [Formatted xs] }
addPart ag (Str "family" : Str "=" : xs) =
ag{ familyName = Formatted xs }
addPart ag (Str "prefix" : Str "=" : xs) =
ag{ droppingPart = Formatted xs }
addPart ag (Str "useprefix" : Str "=" : Str "true" : _) =
ag{ nonDroppingPart = droppingPart ag, droppingPart = mempty }
addPart ag (Str "suffix" : Str "=" : xs) =
ag{ nameSuffix = Formatted xs }
addPart ag (Space : xs) = addPart ag xs
addPart ag _ = ag
return $ foldl' addPart emptyAgent commaParts
-- First von Last
-- von Last, First
-- von Last, Jr ,First
-- NOTE: biblatex and bibtex differ on:
-- Drummond de Andrade, Carlos
-- bibtex takes "Drummond de" as the von;
-- biblatex takes the whole as a last name.
-- See https://github.com/plk/biblatex/issues/236
-- Here we implement the more sensible biblatex behavior.
toAuthor opts ils = do
let useprefix = optionSet "useprefix" opts
let usecomma = optionSet "juniorcomma" opts
let bibtex = optionSet "bibtex" opts
let words' = wordsBy (\x -> x == Space || x == Str "\160")
let commaParts = map words' $ splitWhen (== Str ",")
$ splitStrWhen (\c -> c == ',' || c == '\160') ils
let (first, vonlast, jr) =
case commaParts of
--- First is the longest sequence of white-space separated
-- words starting with an uppercase and that is not the
-- whole string. von is the longest sequence of whitespace
-- separated words whose last word starts with lower case
-- and that is not the whole string.
[fvl] -> let (caps', rest') = span isCapitalized fvl
in if null rest' && not (null caps')
then (init caps', [last caps'], [])
else (caps', rest', [])
[vl,f] -> (f, vl, [])
(vl:j:f:_) -> (f, vl, j )
[] -> ([], [], [])
let (von, lastname) =
if bibtex
then case span isCapitalized $ reverse vonlast of
([],w:ws) -> (reverse ws, [w])
(vs, ws) -> (reverse ws, reverse vs)
else case break isCapitalized vonlast of
(vs@(_:_), []) -> (init vs, [last vs])
(vs, ws) -> (vs, ws)
let prefix = Formatted $ intercalate [Space] von
let family = Formatted $ intercalate [Space] lastname
let suffix = Formatted $ intercalate [Space] jr
let givens = map Formatted first
return Agent
{ givenName = givens
, droppingPart = if useprefix then mempty else prefix
, nonDroppingPart = if useprefix then prefix else mempty
, familyName = family
, nameSuffix = suffix
, literal = mempty
, commaSuffix = usecomma
, parseNames = False
}
isCapitalized :: [Inline] -> Bool
isCapitalized (Str (c:cs) : rest)
| isUpper c = True
| isDigit c = isCapitalized (Str cs : rest)
| otherwise = False
isCapitalized (_:rest) = isCapitalized rest
isCapitalized [] = True
optionSet :: String -> Options -> Bool
optionSet key opts = case lookup key opts of
Just "true" -> True
Just s -> s == mempty
_ -> False
latex' :: String -> [Block]
latex' s = Walk.walk removeSoftBreak bs
where Pandoc _ bs = readLaTeX s
removeSoftBreak :: Inline -> Inline
removeSoftBreak SoftBreak = Space
removeSoftBreak x = x
latex :: String -> Bib Formatted
latex s = blocksToFormatted $ latex' $ trim s
latexTitle :: String -> Bib Formatted
latexTitle s = do
utc <- gets untitlecase
let processTitle = if utc then onBlocks unTitlecase else id
blocksToFormatted $ processTitle $ latex' s
latexAuthors :: Options -> String -> Bib [Agent]
latexAuthors opts = toAuthorList opts . latex' . trim
bib :: Bib Reference -> Item -> Maybe Reference
bib m entry = fst Control.Applicative.<$> evalRWST m entry (BibState True (Lang "en" "US"))
toLocale :: String -> String
toLocale "english" = "en-US" -- "en-EN" unavailable in CSL
toLocale "usenglish" = "en-US"
toLocale "american" = "en-US"
toLocale "british" = "en-GB"
toLocale "ukenglish" = "en-GB"
toLocale "canadian" = "en-US" -- "en-CA" unavailable in CSL
toLocale "australian" = "en-GB" -- "en-AU" unavailable in CSL
toLocale "newzealand" = "en-GB" -- "en-NZ" unavailable in CSL
toLocale "afrikaans" = "af-ZA"
toLocale "arabic" = "ar"
toLocale "basque" = "eu"
toLocale "bulgarian" = "bg-BG"
toLocale "catalan" = "ca-AD"
toLocale "croatian" = "hr-HR"
toLocale "czech" = "cs-CZ"
toLocale "danish" = "da-DK"
toLocale "dutch" = "nl-NL"
toLocale "estonian" = "et-EE"
toLocale "finnish" = "fi-FI"
toLocale "canadien" = "fr-CA"
toLocale "acadian" = "fr-CA"
toLocale "french" = "fr-FR"
toLocale "francais" = "fr-FR"
toLocale "austrian" = "de-AT"
toLocale "naustrian" = "de-AT"
toLocale "german" = "de-DE"
toLocale "germanb" = "de-DE"
toLocale "ngerman" = "de-DE"
toLocale "greek" = "el-GR"
toLocale "polutonikogreek" = "el-GR"
toLocale "hebrew" = "he-IL"
toLocale "hungarian" = "hu-HU"
toLocale "icelandic" = "is-IS"
toLocale "italian" = "it-IT"
toLocale "japanese" = "ja-JP"
toLocale "latvian" = "lv-LV"
toLocale "lithuanian" = "lt-LT"
toLocale "magyar" = "hu-HU"
toLocale "mongolian" = "mn-MN"
toLocale "norsk" = "nb-NO"
toLocale "nynorsk" = "nn-NO"
toLocale "farsi" = "fa-IR"
toLocale "polish" = "pl-PL"
toLocale "brazil" = "pt-BR"
toLocale "brazilian" = "pt-BR"
toLocale "portugues" = "pt-PT"
toLocale "portuguese" = "pt-PT"
toLocale "romanian" = "ro-RO"
toLocale "russian" = "ru-RU"
toLocale "serbian" = "sr-RS"
toLocale "serbianc" = "sr-RS"
toLocale "slovak" = "sk-SK"
toLocale "slovene" = "sl-SL"
toLocale "spanish" = "es-ES"
toLocale "swedish" = "sv-SE"
toLocale "thai" = "th-TH"
toLocale "turkish" = "tr-TR"
toLocale "ukrainian" = "uk-UA"
toLocale "vietnamese" = "vi-VN"
toLocale "latin" = "la"
toLocale x = x
concatWith :: Char -> [Formatted] -> Formatted
concatWith sep = Formatted . foldl' go mempty . map unFormatted
where go :: [Inline] -> [Inline] -> [Inline]
go accum [] = accum
go accum s = case reverse accum of
[] -> s
(Str x:_)
| not (null x) && last x `elem` "!?.,:;"
-> accum ++ (Space : s)
_ -> accum ++ (Str [sep] : Space : s)
type Options = [(String, String)]
parseOptions :: String -> Options
parseOptions = map breakOpt . splitWhen (==',')
where breakOpt x = case break (=='=') x of
(w,v) -> (map toLower $ trim w,
map toLower $ trim $ drop 1 v)
ordinalize :: Locale -> String -> String
ordinalize locale n =
case [termSingular c | c <- terms, cslTerm c == ("ordinal-" ++ pad0 n)] ++
[termSingular c | c <- terms, cslTerm c == "ordinal"] of
(suff:_) -> n ++ suff
[] -> n
where pad0 [c] = ['0',c]
pad0 s = s
terms = localeTerms locale
itemToReference :: Lang -> Locale -> Bool -> Bool -> Item -> Maybe Reference
itemToReference lang locale bibtex caseTransform = bib $ do
modify $ \st -> st{ localeLanguage = lang,
untitlecase = case lang of
Lang "en" _ -> caseTransform
_ -> False }
id' <- asks identifier
otherIds <- (map trim . splitWhen (==',') <$> getRawField "ids")
<|> return []
et <- asks entryType
guard $ et /= "xdata"
opts <- (parseOptions <$> getRawField "options") <|> return []
let getAuthorList' = getAuthorList
(("bibtex", map toLower $ show bibtex):opts)
st <- getRawField "entrysubtype" <|> return mempty
isEvent <- (True <$ (getRawField "eventdate"
<|> getRawField "eventtitle"
<|> getRawField "venue")) <|> return False
reftype' <- resolveKey lang <$> getField "type" <|> return mempty
let (reftype, refgenre) = case et of
"article"
| st == "magazine" -> (ArticleMagazine,mempty)
| st == "newspaper" -> (ArticleNewspaper,mempty)
| otherwise -> (ArticleJournal,mempty)
"book" -> (Book,mempty)
"booklet" -> (Pamphlet,mempty)
"bookinbook" -> (Chapter,mempty)
"collection" -> (Book,mempty)
"electronic" -> (Webpage,mempty)
"inbook" -> (Chapter,mempty)
"incollection" -> (Chapter,mempty)
"inreference" -> (EntryEncyclopedia,mempty)
"inproceedings" -> (PaperConference,mempty)
"manual" -> (Book,mempty)
"mastersthesis" -> (Thesis, if reftype' == mempty
then Formatted [Str $ resolveKey' lang "mathesis"]
else reftype')
"misc" -> (NoType,mempty)
"mvbook" -> (Book,mempty)
"mvcollection" -> (Book,mempty)
"mvproceedings" -> (Book,mempty)
"mvreference" -> (Book,mempty)
"online" -> (Webpage,mempty)
"patent" -> (Patent,mempty)
"periodical"
| st == "magazine" -> (ArticleMagazine,mempty)
| st == "newspaper" -> (ArticleNewspaper,mempty)
| otherwise -> (ArticleJournal,mempty)
"phdthesis" -> (Thesis, if reftype' == mempty
then Formatted [Str $ resolveKey' lang "phdthesis"]
else reftype')
"proceedings" -> (Book,mempty)
"reference" -> (Book,mempty)
"report" -> (Report,mempty)
"suppbook" -> (Chapter,mempty)
"suppcollection" -> (Chapter,mempty)
"suppperiodical"
| st == "magazine" -> (ArticleMagazine,mempty)
| st == "newspaper" -> (ArticleNewspaper,mempty)
| otherwise -> (ArticleJournal,mempty)
"techreport" -> (Report,mempty)
"thesis" -> (Thesis,mempty)
"unpublished" -> (if isEvent then Speech else Manuscript,mempty)
"www" -> (Webpage,mempty)
-- biblatex, "unsupported"
"artwork" -> (Graphic,mempty)
"audio" -> (Song,mempty) -- for audio *recordings*
"commentary" -> (Book,mempty)
"image" -> (Graphic,mempty) -- or "figure" ?
"jurisdiction" -> (LegalCase,mempty)
"legislation" -> (Legislation,mempty) -- or "bill" ?
"legal" -> (Treaty,mempty)
"letter" -> (PersonalCommunication,mempty)
"movie" -> (MotionPicture,mempty)
"music" -> (Song,mempty) -- for musical *recordings*
"performance" -> (Speech,mempty)
"review" -> (Review,mempty) -- or "review-book" ?
"software" -> (Book,mempty) -- for lack of any better match
"standard" -> (Legislation,mempty)
"video" -> (MotionPicture,mempty)
-- biblatex-apa:
"data" -> (Dataset,mempty)
"letters" -> (PersonalCommunication,mempty)
"newsarticle" -> (ArticleNewspaper,mempty)
_ -> (NoType,mempty)
-- hyphenation:
let defaultHyphenation = case lang of
Lang x y -> x ++ "-" ++ y
let getLangId = do
langid <- (trim . map toLower) <$> getRawField "langid"
idopts <- (trim . map toLower) <$>
getRawField "langidopts" <|> return ""
case (langid, idopts) of
("english","variant=british") -> return "british"
("english","variant=american") -> return "american"
("english","variant=us") -> return "american"
("english","variant=usmax") -> return "american"
("english","variant=uk") -> return "british"
("english","variant=australian") -> return "australian"
("english","variant=newzealand") -> return "newzealand"
(x,_) -> return x
hyphenation <- ((toLocale . map toLower) <$>
(getLangId <|> getRawField "hyphenation"))
<|> return mempty
-- authors:
author' <- getAuthorList' "author" <|> return []
containerAuthor' <- getAuthorList' "bookauthor" <|> return []
translator' <- getAuthorList' "translator" <|> return []
editortype <- getRawField "editortype" <|> return mempty
editor'' <- getAuthorList' "editor" <|> return []
director'' <- getAuthorList' "director" <|> return []
let (editor', director') = case editortype of
"director" -> ([], editor'')
_ -> (editor'', director'')
-- FIXME: add same for editora, editorb, editorc
-- titles
let isArticle = et `elem` ["article", "periodical", "suppperiodical", "review"]
let isPeriodical = et == "periodical"
let isChapterlike = et `elem`
["inbook","incollection","inproceedings","inreference","bookinbook"]
hasMaintitle <- (True <$ getRawField "maintitle") <|> return False
let hyphenation' = if null hyphenation
then defaultHyphenation
else hyphenation
let la = case splitWhen (== '-') hyphenation' of
(x:_) -> x
[] -> mempty
modify $ \s -> s{ untitlecase = caseTransform && la == "en" }
title' <- (guard isPeriodical >> getTitle "issuetitle")
<|> (guard hasMaintitle >> guard (not isChapterlike) >> getTitle "maintitle")
<|> getTitle "title"
<|> return mempty
subtitle' <- (guard isPeriodical >> getTitle "issuesubtitle")
<|> (guard hasMaintitle >> guard (not isChapterlike) >> getTitle "mainsubtitle")
<|> getTitle "subtitle"
<|> return mempty
titleaddon' <- (guard hasMaintitle >> guard (not isChapterlike) >> getTitle "maintitleaddon")
<|> getTitle "titleaddon"
<|> return mempty
volumeTitle' <- (guard hasMaintitle >> guard (not isChapterlike) >> getTitle "title")
<|> (guard hasMaintitle >> guard isChapterlike >> getTitle "booktitle")
<|> return mempty
volumeSubtitle' <- (guard hasMaintitle >> guard (not isChapterlike) >> getTitle "subtitle")
<|> (guard hasMaintitle >> guard isChapterlike >> getTitle "booksubtitle")
<|> return mempty
volumeTitleAddon' <- (guard hasMaintitle >> guard (not isChapterlike) >> getTitle "titleaddon")
<|> (guard hasMaintitle >> guard isChapterlike >> getTitle "booktitleaddon")
<|> return mempty
containerTitle' <- (guard isPeriodical >> getPeriodicalTitle "title")
<|> (guard isChapterlike >> getTitle "maintitle")
<|> (guard isChapterlike >> getTitle "booktitle")
<|> getPeriodicalTitle "journaltitle"
<|> getPeriodicalTitle "journal"
<|> return mempty
containerSubtitle' <- (guard isPeriodical >> getPeriodicalTitle "subtitle")
<|> (guard isChapterlike >> getTitle "mainsubtitle")
<|> (guard isChapterlike >> getTitle "booksubtitle")
<|> getPeriodicalTitle "journalsubtitle"
<|> return mempty
containerTitleAddon' <- (guard isPeriodical >> getPeriodicalTitle "titleaddon")
<|> (guard isChapterlike >> getTitle "maintitleaddon")
<|> (guard isChapterlike >> getTitle "booktitleaddon")
<|> return mempty
containerTitleShort' <- (guard isPeriodical >> guard (not hasMaintitle)
>> getField "shorttitle")
<|> getPeriodicalTitle "shortjournal"
<|> return mempty
-- change numerical series title to e.g. 'series 3'
let fixSeriesTitle (Formatted [Str xs]) | all isDigit xs =
Formatted [Str (ordinalize locale xs),
Space, Str (resolveKey' lang "ser.")]
fixSeriesTitle x = x
seriesTitle' <- (fixSeriesTitle . resolveKey lang) <$>
getTitle "series" <|> return mempty
shortTitle' <- (guard (not hasMaintitle || isChapterlike) >>
getTitle "shorttitle")
<|> if (subtitle' /= mempty || titleaddon' /= mempty) &&
not hasMaintitle
then getShortTitle False "title"
else getShortTitle True "title"
<|> return mempty
eventTitle' <- getTitle "eventtitle" <|> return mempty
origTitle' <- getTitle "origtitle" <|> return mempty
-- publisher
pubfields <- mapM (\f -> Just `fmap`
(if bibtex || f == "howpublished"
then getField f
else getLiteralList' f)
<|> return Nothing)
["school","institution","organization", "howpublished","publisher"]
let publisher' = concatWith ';' $ catMaybes pubfields
origpublisher' <- getField "origpublisher" <|> return mempty
-- places
venue' <- getField "venue" <|> return mempty
address' <- (if bibtex
then getField "address"
else getLiteralList' "address"
<|> (guard (et /= "patent") >>
getLiteralList' "location"))
<|> return mempty
origLocation' <- (if bibtex
then getField "origlocation"
else getLiteralList' "origlocation")
<|> return mempty
jurisdiction' <- if et == "patent"
then ((concatWith ';' . map (resolveKey lang)) <$>
getLiteralList "location") <|> return mempty
else return mempty
-- locators
pages' <- getField "pages" <|> return mempty
volume' <- getField "volume" <|> return mempty
part' <- getField "part" <|> return mempty
volumes' <- getField "volumes" <|> return mempty
pagetotal' <- getField "pagetotal" <|> return mempty
chapter' <- getField "chapter" <|> return mempty
edition' <- getField "edition" <|> return mempty
version' <- getField "version" <|> return mempty
(number', collectionNumber', issue') <-
(getField "number" <|> return mempty) >>= \x ->
if et `elem` ["book","collection","proceedings","reference",
"mvbook","mvcollection","mvproceedings", "mvreference",
"bookinbook","inbook", "incollection","inproceedings",
"inreference", "suppbook","suppcollection"]
then return (mempty,x,mempty)
else if isArticle
then (getField "issue" >>= \y ->
return (mempty,mempty,concatWith ',' [x,y]))
<|> return (mempty,mempty,x)
else return (x,mempty,mempty)
-- dates
issued' <- getDates "date" <|> getOldDates mempty <|> return []
eventDate' <- getDates "eventdate" <|> getOldDates "event"
<|> return []
origDate' <- getDates "origdate" <|> getOldDates "orig"
<|> return []
accessed' <- getDates "urldate" <|> getOldDates "url" <|> return []
-- url, doi, isbn, etc.:
-- note that with eprinttype = arxiv, we take eprint to be a partial url
-- archivePrefix is an alias for eprinttype
url' <- (guard (et == "online" || lookup "url" opts /= Just "false")
>> getRawField "url")
<|> (do etype <- getRawField "eprinttype"
eprint <- getRawField "eprint"
let baseUrl =
case map toLower etype of
"arxiv" -> "http://arxiv.org/abs/"
"jstor" -> "http://www.jstor.org/stable/"
"pubmed" -> "http://www.ncbi.nlm.nih.gov/pubmed/"
"googlebooks" -> "http://books.google.com?id="
_ -> ""
if null baseUrl
then mzero
else return $ baseUrl ++ eprint)
<|> return mempty
doi' <- (guard (lookup "doi" opts /= Just "false") >> getRawField "doi")
<|> return mempty
isbn' <- getRawField "isbn" <|> return mempty
issn' <- getRawField "issn" <|> return mempty
pmid' <- getRawField "pmid" <|> return mempty
pmcid' <- getRawField "pmcid" <|> return mempty
callNumber' <- getRawField "library" <|> return mempty
-- notes
annotation' <- getField "annotation" <|> getField "annote"
<|> return mempty
abstract' <- getField "abstract" <|> return mempty
keywords' <- getField "keywords" <|> return mempty
note' <- if et == "periodical"
then return mempty
else getField "note" <|> return mempty
addendum' <- if bibtex
then return mempty
else getField "addendum"
<|> return mempty
pubstate' <- resolveKey lang `fmap`
( getField "pubstate"
<|> case issued' of
(x:_) | other x == Literal "forthcoming" ->
return (Formatted [Str "forthcoming"])
_ -> return mempty
)
let convertEnDash (Str s) = Str (map (\c -> if c == '–' then '-' else c) s)
convertEnDash x = x
let takeDigits (Str xs : _) =
case takeWhile isDigit xs of
[] -> []
ds -> [Str ds]
takeDigits x = x
return $ emptyReference
{ refId = Literal id'
, refOtherIds = map Literal otherIds
, refType = reftype
, author = author'
, editor = editor'
, translator = translator'
-- , recipient = undefined -- :: [Agent]
-- , interviewer = undefined -- :: [Agent]
-- , composer = undefined -- :: [Agent]
, director = director'
-- , illustrator = undefined -- :: [Agent]
-- , originalAuthor = undefined -- :: [Agent]
, containerAuthor = containerAuthor'
-- , collectionEditor = undefined -- :: [Agent]
-- , editorialDirector = undefined -- :: [Agent]
-- , reviewedAuthor = undefined -- :: [Agent]
, issued = issued'
, eventDate = eventDate'
, accessed = accessed'
-- , container = undefined -- :: [RefDate]
, originalDate = origDate'
-- , submitted = undefined -- :: [RefDate]
, title = concatWith '.' [
concatWith ':' [title', subtitle']
, titleaddon' ]
, titleShort = shortTitle'
-- , reviewedTitle = undefined -- :: String
, containerTitle = concatWith '.' [
concatWith ':' [ containerTitle'
, containerSubtitle']
, containerTitleAddon' ]
, collectionTitle = seriesTitle'
, volumeTitle = concatWith '.' [
concatWith ':' [ volumeTitle'
, volumeSubtitle']
, volumeTitleAddon' ]
, containerTitleShort = containerTitleShort'
, collectionNumber = collectionNumber'
, originalTitle = origTitle'
, publisher = publisher'
, originalPublisher = origpublisher'
, publisherPlace = address'
, originalPublisherPlace = origLocation'
, jurisdiction = jurisdiction'
, event = eventTitle'
, eventPlace = venue'
, page = Formatted $
Walk.walk convertEnDash $ unFormatted pages'
, pageFirst = Formatted $ takeDigits $ unFormatted pages'
, numberOfPages = pagetotal'
, version = version'
, volume = Formatted $ intercalate [Str "."]
$ filter (not . null)
[unFormatted volume', unFormatted part']
, numberOfVolumes = volumes'
, issue = issue'
, chapterNumber = chapter'
-- , medium = undefined -- :: String
, status = pubstate'
, edition = edition'
-- , section = undefined -- :: String
-- , source = undefined -- :: String
, genre = if refgenre == mempty
then reftype'
else refgenre
, note = concatWith '.' [note', addendum']
, annote = annotation'
, abstract = abstract'
, keyword = keywords'
, number = number'
, url = Literal url'
, doi = Literal doi'
, isbn = Literal isbn'
, issn = Literal issn'
, pmcid = Literal pmcid'
, pmid = Literal pmid'
, language = Literal hyphenation
, callNumber = Literal callNumber'
}
| adunning/pandoc-citeproc | src/Text/CSL/Input/Bibtex.hs | bsd-3-clause | 66,320 | 185 | 35 | 22,742 | 15,550 | 7,970 | 7,580 | 1,410 | 406 |
module Noobing.Experimenting.IO (
hello
) where
hello :: IO ()
hello = do
putStrLn "hello!"
| markmq/Noobing | src/Noobing/Experimenting/IO.hs | bsd-3-clause | 95 | 0 | 7 | 18 | 33 | 18 | 15 | 5 | 1 |
{-# LANGUAGE TupleSections #-}
module Day17 where
-- Improvements to Day12
import Control.Monad.Reader
import Control.Monad.Trans.Either
import qualified Data.Map as Map
data Type
= Function Type Type
| RecordT [(String, Type)]
| VariantT [(String, Type)]
deriving (Eq, Show)
data CheckTerm
-- neither a constructor nor change of direction
= Let InferTerm Type (InferTerm -> CheckTerm)
-- | Fresh
-- switch direction (check -> infer)
| Neutral InferTerm
-- constructors
-- \x -> CheckedTerm
| Abs (CheckTerm -> CheckTerm)
| Record [(String, CheckTerm)]
| Variant String CheckTerm
data InferTerm
-- switch direction (infer -> check)
= Annot CheckTerm Type
-- eliminators
--
-- note that eliminators always take an InferTerm as the inspected term,
-- since that's the neutral position, then CheckTerms for the rest
| App InferTerm CheckTerm
| AccessField InferTerm String Type
| Case InferTerm Type [(String, CheckTerm -> CheckTerm)]
xxx = error "not yet implemented"
eval :: InferTerm -> EvalCtx CheckTerm
eval t = case t of
Annot cTerm _ -> return cTerm
App f x -> do
f' <- eval f
case f' of
Neutral _ -> xxx
Abs f'' -> return $ f'' x
AccessField iTm name _ -> do
evaled <- eval iTm
case evaled of
Neutral _ -> return $ Neutral (AccessField xxx xxx xxx)
Record fields -> case Map.lookup name (Map.fromList fields) of
Just field -> return field
Nothing -> left "didn't find field in record"
_ -> left "unexpected"
Case iTm _ branches -> do
evaled <- eval iTm
case evaled of
Neutral _ -> xxx
Variant name cTm -> case Map.lookup name (Map.fromList branches) of
Just branch -> return $ branch evaled
-- evalC :: CheckTerm -> EvalCtx CheckTerm
-- evalC t = case t of
-- Let iTm _ body -> return $ body iTm
-- Neutral _ -> return t
-- Abs body ->
-- -- Record [(String, CheckTerm)]
-- -- Variant String CheckTerm
type EvalCtx = EitherT String (Reader [CheckTerm])
type CheckCtx = EitherT String (Reader [Type])
runChecker :: CheckCtx () -> Maybe String
runChecker calc = case runReader (runEitherT calc) [] of
Right () -> Nothing
Left str -> Just str
unifyTy :: Type -> Type -> CheckCtx Type
unifyTy (Function dom1 codom1) (Function dom2 codom2) =
Function <$> unifyTy dom1 dom2 <*> unifyTy codom1 codom2
unifyTy (RecordT lTy) (RecordT rTy) = do
-- RecordT [(String, Type)]
-- Take the intersection of possible records. Make sure the overlap matches!
let isect = Map.intersectionWith (,) (Map.fromList lTy) (Map.fromList rTy)
isect' <- mapM (uncurry unifyTy) isect
return $ RecordT (Map.toList isect')
unifyTy (VariantT lTy) (VariantT rTy) = do
-- Take the union of possible variants. Make sure overlap matches!
let isect = Map.intersectionWith (,) (Map.fromList lTy) (Map.fromList rTy)
isect' <- mapM (uncurry unifyTy) isect
let union = Map.union (Map.fromList lTy) (Map.fromList rTy)
-- Overwrite with extra data we may have learned from unifying the types in
-- the intersection
let result = Map.union isect' union
return $ VariantT (Map.toList result)
unifyTy l r = left ("failed unification " ++ show (l, r))
check :: CheckTerm -> Type -> CheckCtx ()
check tm ty = case tm of
-- t1: infered, t2: infer -> check
Let t1 ty' body -> do
t1Ty <- infer t1
_ <- unifyTy t1Ty ty'
let bodyVal = body t1
check bodyVal ty
Neutral iTm -> do
iTy <- infer iTm
unifyTy ty iTy
return ()
Abs t' -> do
let Function domain codomain = ty
check t' codomain
Record fields -> do
-- Record [(String, CheckTerm)]
--
-- Here we define our notion of record subtyping -- we check that the
-- record we've been given has at least the fields expected of it and of
-- the right type.
let fieldMap = Map.fromList fields
case ty of
RecordT fieldTys -> mapM_
(\(name, subTy) -> do
case Map.lookup name fieldMap of
Just subTm -> check subTm subTy
Nothing -> left "failed to find required field in record"
)
fieldTys
_ -> left "failed to check a record against a non-record type"
Variant name t' -> do
-- Variant String CheckTerm
--
-- Here we define our notion of variant subtyping -- we check that the
-- variant we've been given is in the row
case ty of
VariantT fieldTys -> case Map.lookup name (Map.fromList fieldTys) of
Just expectedTy -> check t' expectedTy
Nothing -> left "failed to find required field in record"
_ -> left "failed to check a record against a non-record type"
Neutral tm' -> do
ty' <- infer tm'
_ <- unifyTy ty ty'
return ()
infer :: InferTerm -> CheckCtx Type
infer t = case t of
Annot _ ty -> pure ty
App t1 t2 -> do
Function domain codomain <- infer t1
check t2 domain
return codomain
-- k (rec.name : ty)
AccessField recTm name ty' kTm -> do
inspectTy <- infer recTm
case inspectTy of
RecordT parts -> case Map.lookup name (Map.fromList parts) of
Just subTy -> do
local (subTy:) (check kTm ty')
return ty'
Nothing -> left "didn't find the accessed key"
_ -> left "found non-record unexpectedly"
Case varTm ty cases -> do
varTmTy <- infer varTm
case varTmTy of
VariantT tyParts -> do
let tyMap = Map.fromList tyParts
caseMap = Map.fromList cases
bothMatch = (Map.null (tyMap Map.\\ caseMap))
&& (Map.null (caseMap Map.\\ tyMap))
when (not bothMatch) (left "case misalignment")
let mergedMap = Map.mergeWithKey
(\k a b -> Just (k, a, b))
(const (Map.fromList []))
(const (Map.fromList []))
tyMap
caseMap
mapM_
(\(_name, branchTy, rhs) -> local (branchTy:) (check rhs ty))
mergedMap
_ -> left "found non-variant in case"
return ty
main :: IO ()
main = do
let unit = Record []
unitTy = RecordT []
xy = Record
[ ("x", unit)
, ("y", unit)
]
xyTy = RecordT
[ ("x", unitTy)
, ("y", unitTy)
]
-- boring
print $ runChecker $
let tm = Abs (\x -> Neutral x)
ty = Function unitTy unitTy
in check tm ty
-- standard record
print $ runChecker $
let tm = Let
(Annot xy xyTy)
xyTy
(\x -> Neutral
(AccessField x "x" unitTy (Neutral x))
)
in check tm unitTy
-- record subtyping
print $ runChecker $
let xRecTy = RecordT [("x", unitTy)]
tm = Let
(Annot xy xRecTy)
xRecTy
(\x -> Neutral
(AccessField x "x" unitTy (Neutral x))
)
in check tm unitTy
-- variant subtyping
print $ runChecker $
let eitherTy = VariantT
[ ("left", unitTy)
, ("right", unitTy)
]
tm = Let
(Annot (Variant "left" unit) eitherTy)
eitherTy
(Abs (\x -> Neutral
(Case x unitTy
[ ("left", (Neutral x))
, ("right", (Neutral x))
]
)
))
in check tm unitTy
| joelburget/daily-typecheckers | src/Day17.hs | bsd-3-clause | 7,281 | 0 | 23 | 2,184 | 2,212 | 1,094 | 1,118 | 175 | 10 |
{-# LANGUAGE GADTs #-}
module Term where
data Term t where
Zero :: Term Int
Succ :: Term Int -> Term Int
Pred :: Term Int -> Term Int
IsZero :: Term Int -> Term Bool
If :: Term Bool -> Term a -> Term a -> Term a
eval :: Term t -> t
eval Zero = 0
eval (Succ e) = succ (eval e)
eval (Pred e) = pred (eval e)
eval (IsZero e) = eval e == 0
eval (If p t f) = if eval p then eval t else eval f
one = Succ Zero
true = IsZero Zero
false = IsZero one
| maoe/fop | 12-Fun-with-Phantom-Types/Term.hs | bsd-3-clause | 478 | 0 | 9 | 144 | 238 | 117 | 121 | 17 | 2 |
{-# OPTIONS_GHC -Wall #-}
module System.Console.ShSh.Builtins.Cmp ( cmp ) where
import System.Console.ShSh.Builtins.Args ( withArgs, flagOn, flag )
import System.Console.ShSh.Builtins.Util ( readFileOrStdin )
import System.Console.ShSh.Shell ( Shell )
import System.Exit ( ExitCode(..) )
{-# NOINLINE cmp #-}
cmp :: [String] -> Shell ExitCode
cmp = withArgs "cmp" header args run
where run [] = fail "missing operand"
run [s] = fail $ "missing operand after `"++s++"'"
run [a,b] = do aa <- filter (/='\r') `fmap` readFileOrStdin a
bb <- filter (/='\r') `fmap` readFileOrStdin b
if length aa == length bb && aa == bb
then return ExitSuccess
else fail' $ unwords ["files",a,"and",b,
"differ.",
show $ length aa,
show $ length bb]
run as = fail $ "too many arguments: "++ show (length as)
fail' msg = do silent <- flag 's'
if silent then return $ ExitFailure 1
else fail msg
args = [flagOn "s" ["quiet","silent"] 's'
"No output; only exitcode." ]
header = "Usage: cmp [OPTIONS...] FILE1 FILE2\n"++
"Compare two files byte by byte."
| shicks/shsh | System/Console/ShSh/Builtins/Cmp.hs | bsd-3-clause | 1,457 | 0 | 14 | 592 | 371 | 203 | 168 | 27 | 6 |
{-# LANGUAGE QuasiQuotes #-}
module LLVM.General.Quote.Test.DataLayout where
import Test.Tasty
import Test.Tasty.HUnit
import Test.HUnit
import Data.Maybe
import qualified Data.Set as Set
import qualified Data.Map as Map
import LLVM.General.Quote.LLVM
import LLVM.General.AST
import LLVM.General.AST.DataLayout
import LLVM.General.AST.AddrSpace
import qualified LLVM.General.AST.Global as G
m s = "; ModuleID = '<string>'\n" ++ s
t s = "target datalayout = \"" ++ s ++ "\"\n"
tests = testGroup "DataLayout" [
testCase name $ sdl @?= (Module "<string>" mdl Nothing [])
| (name, mdl, sdl) <- [
("none", Nothing, [llmod||]),
("little-endian", Just defaultDataLayout { endianness = Just LittleEndian }, [llmod|target datalayout = "e"|]),
("big-endian", Just defaultDataLayout { endianness = Just BigEndian }, [llmod|target datalayout = "E"|]),
("native", Just defaultDataLayout { nativeSizes = Just (Set.fromList [8,32]) }, [llmod|target datalayout = "n8:32"|]),
(
"no pref",
Just defaultDataLayout {
pointerLayouts =
Map.singleton
(AddrSpace 0)
(
8,
AlignmentInfo {
abiAlignment = 64,
preferredAlignment = Nothing
}
)
},
[llmod|target datalayout = "p:8:64"|]
), (
"no pref",
Just defaultDataLayout {
pointerLayouts =
Map.singleton
(AddrSpace 1)
(
8,
AlignmentInfo {
abiAlignment = 32,
preferredAlignment = Just 64
}
)
},
[llmod|target datalayout = "p1:8:32:64"|]
), (
"big",
Just DataLayout {
endianness = Just LittleEndian,
stackAlignment = Just 128,
pointerLayouts = Map.fromList [
(AddrSpace 0, (64, AlignmentInfo {abiAlignment = 64, preferredAlignment = Just 64}))
],
typeLayouts = Map.fromList [
((IntegerAlign, 1), AlignmentInfo {abiAlignment = 8, preferredAlignment = Just 8}),
((IntegerAlign, 8), AlignmentInfo {abiAlignment = 8, preferredAlignment = Just 8}),
((IntegerAlign, 16), AlignmentInfo {abiAlignment = 16, preferredAlignment = Just 16}),
((IntegerAlign, 32), AlignmentInfo {abiAlignment = 32, preferredAlignment = Just 32}),
((IntegerAlign, 64), AlignmentInfo {abiAlignment = 64, preferredAlignment = Just 64}),
((VectorAlign, 64), AlignmentInfo {abiAlignment = 64, preferredAlignment = Just 64}),
((VectorAlign, 128), AlignmentInfo {abiAlignment = 128, preferredAlignment = Just 128}),
((FloatAlign, 32), AlignmentInfo {abiAlignment = 32, preferredAlignment = Just 32}),
((FloatAlign, 64), AlignmentInfo {abiAlignment = 64, preferredAlignment = Just 64}),
((FloatAlign, 80), AlignmentInfo {abiAlignment = 128, preferredAlignment = Just 128}),
((AggregateAlign, 0), AlignmentInfo {abiAlignment = 0, preferredAlignment = Just 64}),
((StackAlign, 0), AlignmentInfo {abiAlignment = 64, preferredAlignment = Just 64})
],
nativeSizes = Just (Set.fromList [8,16,32,64])
},
[llmod|target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64-S128"|]
)
]
] | tvh/llvm-general-quote | test/LLVM/General/Quote/Test/DataLayout.hs | bsd-3-clause | 3,333 | 0 | 20 | 816 | 919 | 569 | 350 | 68 | 1 |
{-|
Module : Database.Relational.Project
Description : Definition of PROJECT and friends.
Copyright : (c) Alexander Vieth, 2015
Licence : BSD3
Maintainer : aovieth@gmail.com
Stability : experimental
Portability : non-portable (GHC only)
-}
{-# LANGUAGE AutoDeriveTypeable #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE PatternSynonyms #-}
module Database.Relational.Project (
PROJECT(..)
, type (:|:)
, pattern (:|:)
{-
, ProjectColumns
, ProjectTableNames
, ProjectAliases
, ProjectTypes
-}
) where
import Data.Proxy
import Database.Relational.Column
-- | Intended use: give a column and a table name for the left parameter, so as
-- to resolve a column within a query ("my_table.my_column"), and then give
-- an alias for this column.
-- The right parameter is either another PROJECT with the same contract, or
-- P.
data PROJECT left right where
PROJECT :: left -> right -> PROJECT left right
infixr 8 :|:
type (:|:) = PROJECT
pattern left :|: right = PROJECT left right
{-
type family ProjectColumns project where
ProjectColumns P = '[]
ProjectColumns (PROJECT '(tableName, column, alias) rest) = column ': (ProjectColumns rest)
type family ProjectTableNames project where
ProjectTableNames P = '[]
ProjectTableNames (PROJECT '(tableName, column, alias) rest) = tableName ': (ProjectTableNames rest)
type family ProjectAliases project where
ProjectAliases P = '[]
ProjectAliases (PROJECT '(tableName, column, alias) rest) = alias ': (ProjectAliases rest)
type family ProjectTypes project where
ProjectTypes P = '[]
ProjectTypes (PROJECT '(tableName, column, alias) rest) = ColumnType column ': ProjectTypes rest
-}
| avieth/Relational | Database/Relational/Project.hs | bsd-3-clause | 1,841 | 0 | 8 | 362 | 109 | 74 | 35 | -1 | -1 |
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE OverloadedStrings #-}
module Develop.Generate.Index
( toHtml
, getProject
, moveToRoot
)
where
import Control.Monad (filterM)
import Data.Aeson ((.=))
import qualified Data.Aeson as Json
import qualified Data.ByteString.Lazy.UTF8 as BSU8
import qualified Data.List as List
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import qualified System.Directory as Dir
import System.FilePath ((</>), joinPath, splitDirectories, takeExtension)
import qualified Text.Blaze.Html5 as H
import qualified Develop.Generate.Help as Help
import qualified Develop.StaticFiles as StaticFiles
-- PROJECT
data Project =
Project
{ _root :: FilePath
, _info :: PerhapsInfo
}
data PerhapsInfo
= Bad (Maybe FilePath)
| Good Info
data Info =
Info
{ _pwd :: [String]
, _dirs :: [FilePath]
, _files :: [(FilePath, Bool)]
, _readme :: Maybe String
, _config :: Text.Text
}
-- JSON
goodToJson :: FilePath -> Info -> String
goodToJson root info =
BSU8.toString $ Json.encode $ Json.object $
[ "root" .= root
, "pwd" .= _pwd info
, "dirs" .= _dirs info
, "files" .= _files info
, "readme" .= _readme info
, "config" .= _config info
]
badJson :: FilePath -> Maybe FilePath -> String
badJson root potentialRoot =
BSU8.toString $ Json.encode $ Json.object $
[ "root" .= root
, "suggestion" .= potentialRoot
]
-- GENERATE HTML
toHtml :: Project -> H.Html
toHtml (Project root perhapsInfo) =
case perhapsInfo of
Good info@(Info pwd _ _ _ _) ->
Help.makeHtml
(List.intercalate "/" ("~" : pwd))
("/" ++ StaticFiles.elmPath)
("Elm.Index.fullscreen(" ++ goodToJson root info ++ ");")
Bad suggestion ->
Help.makeHtml
(maybe "New Project!" (const "Existing Project?") suggestion)
("/" ++ StaticFiles.elmPath)
("Elm.Start.fullscreen(" ++ badJson root suggestion ++ ");")
-- GET PROJECT
getProject :: FilePath -> IO Project
getProject directory =
do root <- Dir.getCurrentDirectory
exists <- Dir.doesFileExist "elm.json"
Project root <$>
case exists of
False ->
Bad <$> findNearestConfig (splitDirectories root)
True ->
do json <- Text.readFile "elm.json"
Good <$> getInfo json directory
findNearestConfig :: [String] -> IO (Maybe FilePath)
findNearestConfig dirs =
if null dirs then
return Nothing
else
do exists <- Dir.doesFileExist (joinPath dirs </> "elm.json")
if exists
then return (Just (joinPath dirs))
else findNearestConfig (init dirs)
moveToRoot :: IO ()
moveToRoot =
do subDir <- Dir.getCurrentDirectory
maybeRoot <- findNearestConfig (splitDirectories subDir)
case maybeRoot of
Nothing ->
return ()
Just root ->
Dir.setCurrentDirectory root
-- GET INFO
getInfo :: Text.Text -> FilePath -> IO Info
getInfo config directory =
do (dirs, files) <- getDirectoryInfo directory
readme <- getReadme directory
return $
Info
{ _pwd = dropWhile ("." ==) (splitDirectories directory)
, _dirs = dirs
, _files = files
, _readme = readme
, _config = config
}
-- README
getReadme :: FilePath -> IO (Maybe String)
getReadme dir =
do let readmePath = dir </> "README.md"
exists <- Dir.doesFileExist readmePath
if exists
then Just <$> readFile readmePath
else return Nothing
-- DIRECTORIES / FILES
getDirectoryInfo :: FilePath -> IO ([FilePath], [(FilePath, Bool)])
getDirectoryInfo dir =
do contents <- Dir.getDirectoryContents dir
allDirs <- filterM (Dir.doesDirectoryExist . (dir </>)) contents
rawFiles <- filterM (Dir.doesFileExist . (dir </>)) contents
files <- mapM (inspectFile dir) rawFiles
return (allDirs, files)
inspectFile :: FilePath -> FilePath -> IO (FilePath, Bool)
inspectFile dir filePath =
if takeExtension filePath == ".elm" then
do source <- Text.readFile (dir </> filePath)
let hasMain = Text.isInfixOf "\nmain " source
return (filePath, hasMain)
else
return (filePath, False)
| evancz/cli | src/Develop/Generate/Index.hs | bsd-3-clause | 4,285 | 0 | 15 | 1,113 | 1,259 | 673 | 586 | 119 | 3 |
-- | Internal array type used by the B-tree types
{-# LANGUAGE BangPatterns, CPP, MagicHash, Rank2Types, UnboxedTuples #-}
module Data.BTree.Array
( -- * Types
Array
, MArray
-- * Creating arrays
, run
, new
, unsafeWrite
, unsafeCopy
-- * Inspecting arrays
, unsafeIndex
-- * Debugging
, fromList
, toList
) where
import GHC.ST (ST (..), runST)
import GHC.Exts
-- | Frozen array
data Array a = Array (Array# a)
-- | Mutable array
data MArray s a = MArray (MutableArray# s a)
-- | Create and freeze an array
run :: (forall s. ST s (MArray s a)) -> Array a
run act = runST $ act >>= unsafeFreeze
{-# INLINE run #-}
-- | Create a new array of the specified size
new :: Int -> ST s (MArray s a)
new (I# n#) = ST $ \s# -> case newArray# n# element s# of
(# s'#, mar# #) -> (# s'#, MArray mar# #)
where
element = error "Data.BTree.Array: unitialized element!"
{-# INLINE new #-}
-- | Freeze a mutable array
unsafeFreeze :: MArray s a -> ST s (Array a)
unsafeFreeze (MArray mar#) = ST $ \s# ->
case unsafeFreezeArray# mar# s# of (# s'#, ar# #) -> (# s'#, Array ar# #)
{-# INLINE unsafeFreeze #-}
-- | Write to a position in an array
unsafeWrite :: MArray s a -> Int -> a -> ST s ()
unsafeWrite (MArray mar#) (I# i#) x = ST $ \s# ->
case writeArray# mar# i# x s# of s'# -> (# s'#, () #)
{-# INLINE unsafeWrite #-}
-- | Copy a range from an array
unsafeCopy :: Array a -- ^ Array to copy from
-> Int -- ^ Source index
-> MArray s a -- ^ Destination to copy into
-> Int -- ^ Destination index
-> Int -- ^ Number of elements to copy
-> ST s () -- ^ No result
-- TODO: Check this!
#if __GLASGOW_HASKELL__ >= 702
unsafeCopy (Array ar#) (I# si#) (MArray mar#) (I# di#) (I# n#) = ST $ \s# ->
case copyArray# ar# si# mar# di# n# s# of s'# -> (# s'#, () #)
#else
unsafeCopy ar si mar di n = go si di 0
where
go !i !j !c
| c >= n = return ()
| otherwise = do
let x = unsafeIndex ar i
unsafeWrite mar j x
go (i + 1) (j + 1) (c + 1)
#endif
{-# INLINE unsafeCopy #-}
-- | Index an array, bounds are not checked
unsafeIndex :: Array a -> Int -> a
unsafeIndex (Array ar#) (I# i#)
| i# <# 0# = error "herp"
| otherwise = case indexArray# ar# i# of (# x #) -> x
{-# INLINE unsafeIndex #-}
-- | Convert a list to an array. For debugging purposes only.
fromList :: [a] -> Array a
fromList ls = run $ do
mar <- new (length ls)
let go _ [] = return mar
go i (x : xs) = do
unsafeWrite mar i x
go (i + 1) xs
go 0 ls
-- | Convert an array to a list. For debugging purposes only.
toList :: Int -- ^ Length
-> Array a -- ^ Array to convert to a list
-> [a] -- ^ Resulting list
toList n arr = go 0
where
go !i | i >= n = []
| otherwise = unsafeIndex arr i : go (i + 1)
| jaspervdj/b-tree | src/Data/BTree/Array.hs | bsd-3-clause | 2,991 | 0 | 15 | 930 | 823 | 432 | 391 | 65 | 2 |
{-# LANGUAGE RankNTypes, OverloadedStrings #-}
module Saturnin.Types
( MachineDescription
, Hostname
, BuildRequest (..)
, JobRequest (..)
, TestType (..)
, GitSource (..)
, YBServer
, YBServerState (..)
, YBSSharedState
, fst3
, TestResult (..)
, anyEither
, isPassed
, JobID (..)
, JobRequestListenerConnectionHandler
, logError
, logInfo
, logToConnection
, logToConnection'
)
where
import Control.Applicative hiding (empty)
import Control.Concurrent.STM
import Control.Monad.State
import Data.Text.Lazy hiding (empty)
import Data.Default
import Data.HashMap.Strict
import Data.Monoid
import Formatting
import Network.Socket
import System.IO
import Saturnin.Git
import Saturnin.Server.Config
data BuildRequest = GitBuildRequest
{ brUri :: String
, brHead :: String
}
type MachinesRegister = HashMap MachineDescription Hostname
-- | JobRequest specifies job to be run. This is what client send to the
-- job server.
data JobRequest = TestRequest
{ testType :: TestType
, dataSource :: GitSource
, testMachines :: [MachineDescription]
}
deriving (Show, Read)
data TestType = CabalTest | MakeCheckTest
deriving (Show, Read)
data YBServerState = YBServerState
{ ybssConfig :: ConfigServer
, pState :: YBServerPersistentState
, freeMachines :: MachinesRegister
, logHandle :: Handle
}
deriving (Show)
instance Default YBServerState where
def = YBServerState def def empty stderr
type YBSSharedState = TVar YBServerState
type YBServer a = StateT YBSSharedState IO a
logServer :: Text -> YBServer ()
logServer x = do
liftIO . hPutStr stderr $ unpack x
ts <- get
lh <- liftIO . atomically $ logHandle <$> readTVar ts
liftIO . hPutStr lh $ unpack x
logError :: Text -> YBServer ()
logError = logServer . format ("error: " % text % "\n")
logInfo :: Text -> YBServer ()
logInfo = logServer . format ("info: " % text % "\n")
type JobRequestListenerConnectionHandler a =
StateT (Socket, SockAddr) (StateT YBSSharedState IO) a
logToConnection :: Text -> JobRequestListenerConnectionHandler ()
logToConnection x = do
c <- (fst <$> get)
liftIO $ logToConnection' c x
logToConnection' :: Socket -> Text -> IO ()
logToConnection' c x =
void . send c $ unpack x <> "\n"
-- | fst for three-tuple
fst3 :: forall t t1 t2. (t, t1, t2) -> t
fst3 (x, _, _) = x
data TestResult = Passed | Failed | FailedSetup
deriving (Show, Read)
isPassed :: TestResult -> Bool
isPassed Passed = True
isPassed _ = False
-- | Returns any thing in Either. Be it Left or Right.
anyEither :: Either a a -> a
anyEither (Left x) = x
anyEither (Right x) = x
| yaccz/saturnin | library/Saturnin/Types.hs | bsd-3-clause | 2,738 | 0 | 10 | 618 | 766 | 433 | 333 | 83 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
import Data.String (fromString)
import System.Environment (getArgs)
import qualified Network.Wai.Handler.Warp as Warp
import qualified Network.Wai as Wai
import qualified Network.HTTP.Types as H
import qualified Network.Wai.Application.Static as Static
import Data.Maybe (fromJust)
import Data.FileEmbed (embedDir)
import WaiAppStatic.Types (toPieces)
import Data.Text as T
import Data.Text.Encoding (decodeUtf8)
import qualified Data.ByteString as BS
import Network.Transport.InMemory (createTransport)
import Control.Distributed.Process.Node (LocalNode,newLocalNode,initRemoteTable,forkProcess,runProcess)
import Control.Distributed.Process (Process,ProcessId,send,receiveWait,match)
import Control.Monad.Trans (liftIO)
import Data.Map.Strict as Map
import Network.Wai.Handler.WebSockets (websocketsOr)
import qualified Network.WebSockets as WS
import Data.Word8 (_question)
import Data.List (delete)
import Control.Monad.Reader(ReaderT,runReaderT,ask)
import GHC.Generics (Generic)
import Data.Typeable (Typeable)
import Data.Binary (Binary)
data MainMsg = RegistClient ProcessId String
| UnregistClient ProcessId
| StringData ProcessId String
deriving (Generic,Typeable)
instance Binary MainMsg
main :: IO ()
main = do
node <- createTransport >>= (\t -> newLocalNode t initRemoteTable)
mpid <- forkMain node
host:port:_ <- getArgs
return ()
Warp.runSettings (
Warp.setHost (fromString host) $
Warp.setPort (read port) $
Warp.defaultSettings
) $ websocketsOr WS.defaultConnectionOptions (wsRouterApp node mpid) staticApp
type IO' = ReaderT (LocalNode,ProcessId) IO
type WaiApplication' = Wai.Request -> (Wai.Response -> IO Wai.ResponseReceived) -> IO' Wai.ResponseReceived
type WSServerApp' = WS.PendingConnection -> IO' ()
staticApp :: Wai.Application
staticApp = Static.staticApp $ settings { Static.ssIndices = indices }
where
settings = Static.embeddedSettings $(embedDir "static")
indices = fromJust $ toPieces ["WaiChat.htm"] -- default content
wsRouterApp :: LocalNode -> ProcessId -> WS.ServerApp
wsRouterApp node mpid pconn = runReaderT (f pconn) (node,mpid)
where
f pconn
| ("/client" == path) = clientApp pconn
| otherwise = liftIO $ WS.rejectRequest pconn "endpoint not found"
requestPath = WS.requestPath $ WS.pendingRequest pconn
path = BS.takeWhile (/=_question) requestPath
clientApp :: WSServerApp'
clientApp pconn = do
conn <- liftIO $ WS.acceptRequest pconn
cpid <- forkClient conn
registClient cpid name
loop conn cpid
where
loop :: WS.Connection -> ProcessId -> IO' ()
loop conn cpid = do
msg <- liftIO $ WS.receive conn
case msg of
WS.ControlMessage (WS.Close _ _) -> do
unregistClient cpid
-- [TODO] kill process
liftIO $ putStrLn "close complete!!"
WS.DataMessage (WS.Text lbs) -> do
tellString cpid $ T.unpack $ WS.fromLazyByteString lbs
loop conn cpid
_ -> loop conn cpid
requestPath = WS.requestPath $ WS.pendingRequest pconn
query = BS.drop 1 $ BS.dropWhile (/=_question) requestPath
name = T.unpack $ decodeUtf8 $ H.urlDecode True query
registClient :: ProcessId -> String -> IO' ()
registClient pid name = do
(node,mnid) <- ask
liftIO $ runProcess node $ send mnid (RegistClient pid name)
-- [TODO] link or monitor nid
unregistClient :: ProcessId -> IO' ()
unregistClient pid = do
(node,mnid) <- ask
liftIO $ runProcess node $ send mnid (UnregistClient pid)
-- [TODO] kill pid
tellString :: ProcessId -> String -> IO' ()
tellString pid msg = do
(node,mnid) <- ask
liftIO $ runProcess node $ send mnid (StringData pid msg)
forkClient :: WS.Connection -> IO' ProcessId
forkClient conn = do
(node,_) <- ask
liftIO $ forkProcess node $ clientProcess conn
clientProcess :: WS.Connection -> Process ()
clientProcess conn = do
receiveWait [match (p conn)]
clientProcess conn
where
p :: WS.Connection-> String -> Process ()
p conn msg =
let
txt = T.pack $ msg
in
liftIO $ WS.sendTextData conn txt
forkMain :: LocalNode -> IO ProcessId
forkMain node = forkProcess node $ mainProcess Map.empty
type MainState = Map.Map ProcessId String
mainProcess :: MainState -> Process ()
mainProcess state = do
state' <- receiveWait [match (p state)]
mainProcess state'
where
p :: MainState -> MainMsg -> Process MainState
p state (RegistClient sender name) = return $ Map.insert sender name state
p state (UnregistClient sender) = return $ Map.delete sender state
p state (StringData sender msg) = do
let sname = case Map.lookup sender state of
Just name -> name
Nothing -> "[unknown]"
liftIO $ putStrLn $ "StringData " ++ sname ++ " " ++ msg
mapM_ (\(t,_)-> send t $ sname ++ ": " ++ msg) $ Map.toList state
return $ state
| mitsuji/exp-CloudHaskell | app/WaiChat.hs | bsd-3-clause | 5,093 | 2 | 14 | 1,060 | 1,652 | 848 | 804 | 121 | 4 |
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
import Language.JsonGrammar
import Types
import Prelude hiding (id, (.))
import Control.Category (Category(..))
import Data.Aeson.Types (Value, parseMaybe)
import Data.Char (toLower)
import Data.Monoid ((<>))
import Data.StackPrism (StackPrism)
import Data.StackPrism.TH (deriveStackPrismsWith)
import Language.TypeScript (renderDeclarationSourceFile)
import Test.Framework (Test, defaultMain)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit (assertBool)
-- Create stack prisms for our three datatypes (defined in module Types)
deriveStackPrismsWith (map toLower) ''Person
deriveStackPrismsWith (map toLower) ''Coords
deriveStackPrismsWith (map toLower) ''Gender
-- Write Json instances for the datatypes
instance Json Gender where
grammar = fromPrism male . literal "male"
<> fromPrism female . literal "female"
instance Json Person where
grammar = label "Person" $
fromPrism person . object
( prop "name"
. prop "gender"
. (prop "age" <> defaultValue 42)
. fromPrism coords
. property "coords" (array (el . el))
)
-- Create two example values
alice :: Person
alice = Person "Alice" Female 21 (Coords 52 5)
bob :: Person
bob = Person "Bob" Male 22 (Coords 53 6)
-- Two tests: one for lists, the other for tuples
test1, test2 :: Test
test1 = testCase "PersonList" $ assertBool "" (checkInverse [alice, bob])
test2 = testCase "PersonTuple" $ assertBool "" (checkInverse (alice, bob))
checkInverse :: (Json a, Eq a) => a -> Bool
checkInverse value = value == value'
where
Just json = serialize grammar value
Just value' = parseMaybe (parse grammar) json
-- Write the TypeScript definition to stdout and run the tests
main :: IO ()
main = do
printInterfaces [SomeGrammar personGrammar]
defaultMain [test1, test2]
personGrammar :: Grammar 'Val (Value :- t) (Person :- t)
personGrammar = grammar
printInterfaces :: [SomeGrammar 'Val] -> IO ()
printInterfaces gs = putStrLn (renderDeclarationSourceFile (interfaces gs))
| MedeaMelana/JsonGrammar2 | tests/Tests.hs | bsd-3-clause | 2,169 | 4 | 14 | 371 | 657 | 337 | 320 | -1 | -1 |
module Control.Monad.Syntax.Three where
(===<<) :: Monad m =>
(a -> b -> c -> m d)
-> m a
-> b -> c -> m d
(===<<) mf inp b c = inp >>= (\a -> mf a b c)
infixl 1 ===<<
(=.=<<) :: Monad m =>
(a -> b -> c -> m d)
-> m b
-> a -> c -> m d
(=.=<<) mf inp a c = inp >>= (\b -> mf a b c)
infixl 1 =.=<<
(==.<<) :: Monad m =>
(a -> b -> c -> m d)
-> m c
-> a -> b -> m d
(==.<<) mf inp a b = inp >>= mf a b
infixl 1 ==.<<
| athanclark/composition-extra | src/Control/Monad/Syntax/Three.hs | bsd-3-clause | 502 | 0 | 11 | 208 | 280 | 147 | 133 | 19 | 1 |
{-# LANGUAGE FlexibleContexts, UndecidableInstances, TypeSynonymInstances, FlexibleInstances, RankNTypes, TupleSections #-}
-- Ref.) https://stackoverflow.com/questions/13352205/what-are-free-monads/13352580
module Free where
import Control.Arrow
import Control.Monad.State
data Free f a = Pure a
| Roll (f (Free f a))
pure' = Pure
roll = Roll
-- In = [pure, roll]
-- Ta <-------------- a + F(Ta)
-- | |
-- | u | 1 + Fu
-- | |
-- v v
-- X <-------------- a + FX
-- [f, g]
cata (f, g) (Pure x) = f x
cata (f, g) (Roll x) = g (fmap (cata (f, g)) x) -- this fmap is over F not T (= Free f)
instance Functor f => Functor (Free f) where
fmap f = cata (pure' . f, roll)
-- fmap f (Pure x) = pure' (f x)
-- fmap f (Roll x) = roll (fmap (fmap f) x) -- 1st fmap is over F and 2nd fmap is the same as lhs (= Free f)
mu :: Functor f => Free f (Free f a) -> Free f a
mu = cata (id, roll)
-- mu (Pure x) = x
-- mu (Roll x) = roll (fmap mu x)
-- Ref.) https://stackoverflow.com/questions/22121960/applicative-instance-for-free-monad
instance Functor f => Applicative (Free f) where
pure = pure'
f <*> x = cata ((<$> x), roll) f -- cata ((`fmap` x), roll) f
-- (<*> x) (Pure f) = (<$> x) f
-- (<*> x) (Roll f) = roll (fmap (<*> x) f)
instance (Functor f, Applicative (Free f)) => Monad (Free f) where
return = pure
x >>= f = f =<< x where (=<<) = (mu.).fmap
-- example.
-- L(A) = F(GA, HA) where G,H are unary functor.
-- phi :: H <- L imples H <- TG where (alpha, T) is initial type over F(AOP exercise 2.39)
--
-- And then, consider the case when substituted G to Identity functor,and substitute H to `B'.
-- So, the initial F-Algebra of TA <- F(A, G(TA))) means Binary Tree(Leafy).
data B a = B a a deriving Show
instance Functor B where
fmap f (B x y) = B (f x) (f y)
type Tree a = Free B a
tip :: a -> Tree a
tip x = pure x
bin :: Tree a -> Tree a -> Tree a
bin l r = Roll (B l r)
instance Show a => Show (Tree a) where
show (Pure a) = "Pure " ++ show a
show (Roll (B x y)) = "Roll (B {" ++ show x ++ "," ++ show y ++ "})"
size :: Tree a -> Int
size = cata (const 1, plus)
where
plus (B x y) = x + y
depth :: Tree a -> Int
depth = cata (const 0, (+1).maxB)
where
maxB (B x y) = max x y
withDepth :: Tree a -> Tree (a, Int)
withDepth = sub 0
where
sub d (Pure x) = tip (x, d)
sub d (Roll (B x y)) = bin (sub (d+1) x) (sub (d+1) y)
data LR = L | R deriving (Show, Eq, Ord)
instance Semigroup LR where
(<>) = max
instance Monoid LR where
mempty = L
mappend = (<>)
-- cata
lr (l, r) L = l
lr (l, r) R = r
assocr :: ((a, b), c) -> (a, (b, c))
assocr ((x, y), z) = (x, (y, z))
withRoute :: Tree a -> Tree (a, [LR])
withRoute = sub []
where
sub lrs (Pure x) = tip (x, lrs)
sub lrs (Roll (B x y)) = bin (sub (L:lrs) x) (sub (R:lrs) y)
type Context = LR
trimR = sub "" ""
where
sub fix tmp [] = fix
sub fix tmp (' ':cs) = sub fix (' ':tmp) cs
sub fix tmp (c:cs) = sub (fix ++ tmp ++ [c]) "" cs
drawTree :: Show a => Tree a -> IO ()
drawTree = putStr . showTree
showTree :: (Show a) => Tree a -> String
showTree t = (draw . withRoute) t
where
branch L L = (" ", "+--")
branch L R = ("| ", "+--")
branch R L = ("| ", "+ ")
branch R R = (" ", " ")
sub :: Context -> [LR] -> ([String], [String]) -> ([String], [String])
sub _ [] (l1, l2) = (l1, l2)
sub c (x:xs) (l1, l2) = sub (c <> x) xs $ ((:l1) *** (:l2)) (branch c x)
draw (Pure (x, lrs)) = unlines [ trimR (concat l1s)
, concat l2s ++ " " ++ show x
]
where (l1s, l2s) = sub L lrs ([], [])
draw (Roll (B l r)) = draw l ++ draw r
tag :: (Int -> a -> b) -> Tree a -> Tree b
tag f tree = evalState (tagStep f tree) 0
tagStep :: (Int -> a -> b) -> Tree a -> State Int (Tree b)
tagStep f (Pure x) = do
c <- get
put (c+1)
return (tip (f c x))
tagStep f (Roll (B l r)) = do
l' <- tagStep f l
r' <- tagStep f r
return (bin l' r')
--
-- putStr $ showTree $ tag const test9
-- putStr $ showTree $ tag (,) test9
-- putStr $ showTree $ tag (,) $ fmap assocr . withRoute . withDepth $ test9
--
dup x = (x, x)
double = uncurry bin . dup
genNumTree n = tag const $ iterate double (tip ()) !! n
test = do
x <- tip 1
y <- tip 'a'
return (x, y)
test1 = do
x <- bin (tip 1) (tip 2)
y <- tip 3
return (x, y)
test2 = do
x <- tip 1
y <- bin (tip 2) (tip 3)
return (x, y)
test3 = do
x <- bin (tip 1) (tip 2)
y <- bin (tip 'a') (tip 'b')
return (x, y)
test4 = do
x <- bin (tip 1) (tip 2)
y <- bin (tip 'a') (bin (tip 'b') (tip 'c'))
return (x, y)
test5 = do
x <- bin (tip 1) (tip 2)
y <- bin (tip 'a') (bin (tip 'b') (tip 'c'))
return (y, x)
test6 = do
x <- bin (tip 'a') (bin (tip 'b') (tip 'c'))
y <- bin (tip 1) (tip 2)
return (x, y)
test7 = do
x <- bin (bin (tip 1) (tip 2)) (tip 3)
y <- bin (tip 'a') (bin (tip 'b') (tip 'c'))
return (x, y)
test8 = bin (tip 1) (bin (tip 2) (bin (tip 3) (bin (tip 4) (bin (tip 4) (tip 6)))))
test9 = bin (tip 0) (bin (bin (bin (bin (tip 1) (tip 2)) (bin (tip 3) (tip 4))) (bin (tip 5) (bin (tip 6) (tip 7)))) (tip 8))
-- >>> let tr = bin (tip 2) (tip 1)
-- >>> let tl = bin (tip 4) (tip 3)
-- >>> let t = bin (tip 5) (bin tl tr)
-- >>> let f1 = tip (*2)
-- >>> fmap (*2) t
-- >>> f1 <*> t
-- >>> let f2 = bin (tip (*2)) (tip (+2))
-- >>> f2 <*> tl
-- >>> f2 <*> t
monadTest = do
x <- bin (tip 'a') (bin (tip 'b') (tip 'c'))
y <- bin (bin (tip 1) (tip 2)) (tip 3)
return (x,y)
monadTest2 = do
f <- bin (tip (+2)) (bin (tip (*2)) (tip (^2)))
x <- bin (bin (tip 1) (tip 2)) (tip 3)
return (f x)
monadTest3 = do
f <- tip $ bin (tip (+2)) (bin (tip (*2)) (tip (^2)))
x <- tip $ bin (bin (tip 1) (tip 2)) (tip 3)
f <*> x
{-
-- the case of f is Identity
-- F(A, TA) = A + TA
data Free a = Pure a
| Roll (Free a)
deriving (Show, Eq)
pure' = Pure
roll = Roll
-- In = [pure, roll]
-- Ta <-------------- a + Ta
-- | |
-- | u | 1 + u
-- | |
-- v v
-- X <-------------- a + X
-- [f, g]
cata :: (a -> b, b -> b) -> Free a -> b
cata (f, g) (Pure x) = f x
cata (f, g) (Roll x) = g (cata (f, g) x)
-- T f = cata (alpha . F(f, id))
-- = cata ([pure, roll] . (f + id))
-- = cata (pure . f, roll)
freeMap :: (a -> b) -> Free a -> Free b
freeMap f = cata (pure' . f, roll)
instance Functor Free where
fmap = freeMap
instance Applicative Free where
pure = pure'
(<*>) = cata (fmap, (roll.))
mu :: Free (Free a) -> Free a
mu = cata (id, roll)
instance Monad Free where
return = pure
x >>= f = f =<< x where (=<<) = (mu.).fmap
-}
| cutsea110/aop | src/Free.hs | bsd-3-clause | 6,957 | 0 | 15 | 2,167 | 2,901 | 1,501 | 1,400 | 135 | 6 |
{-# LANGUAGE TemplateHaskell, OverloadedStrings #-}
module Monto.RegisterServiceRequest where
import Data.Aeson.TH
import Data.Aeson (Value)
import Data.Vector (Vector)
import qualified Data.Vector as V
import Data.Text (Text)
import qualified Data.Text as T
import Data.Maybe (fromMaybe)
import Monto.Types
data RegisterServiceRequest =
RegisterServiceRequest
{ serviceID :: ServiceID
, label :: Text
, description :: Text
, language :: Language
, product :: Product
, options :: Maybe Value
, dependencies :: Maybe (Vector String)
} deriving (Eq)
$(deriveJSON (defaultOptions {
fieldLabelModifier = \s -> case s of
"serviceID" -> "service_id"
label' -> label'
}) ''RegisterServiceRequest)
registerServiceRequestDependencies :: RegisterServiceRequest -> Vector String
registerServiceRequestDependencies = fromMaybe V.empty . dependencies
instance Show RegisterServiceRequest where
show (RegisterServiceRequest i _ _ l p _ _) =
concat [ "{", T.unpack i
, ",", T.unpack l
, ",", T.unpack p
, "}"
] | wpmp/monto-broker | src/Monto/RegisterServiceRequest.hs | bsd-3-clause | 1,180 | 0 | 14 | 315 | 289 | 165 | 124 | 33 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Unit.Service.CrawlerServiceTest (tests) where
import Control.Applicative ((<$>))
import Data.Text
import Service.CrawlerService
import Test.HUnit
import Text.HTML.TagSoup (Tag(..))
tests = [
"runs crawler" ~: test [
testIO (runCrawler fetcherMock1 "git.io" ["http://k.net"]) (@?= [("http://k.net",True)])
,testIO (runCrawler fetcherMock2 "git.io" ["http://k.net"]) (@?= [("http://k.net",True)])
,testIO (runCrawler fetcherMock3 "git.io" ["http://k.net"]) (@?= [("http://k.net",True)])
,testIO (runCrawler fetcherMock4 "git.io" ["http://k.net"]) (@?= [("http://k.net",False)])
]
]
fetcherMock1 "http://k.net" = return [TagOpen "a" [("href", "git.io")]]
fetcherMock2 "http://k.net" = return [TagOpen "a" [("href", "/a")]]
fetcherMock2 "http://k.net/a" = return [TagOpen "a" [("href", "git.io")]]
fetcherMock3 "http://k.net" = return [TagOpen "a" [("href", "/a")]]
fetcherMock3 "http://k.net/a" = return [TagOpen "a" [("href", "/b")]]
fetcherMock3 "http://k.net/b" = return [TagOpen "a" [("href", "git.io")]]
fetcherMock4 "http://k.net" = return [TagOpen "a" [("href", "/a")]]
fetcherMock4 "http://k.net/a" = return [TagOpen "a" [("href", "/b")]]
fetcherMock4 "http://k.net/b" = return [TagOpen "a" [("href", "/c")]]
fetcherMock4 "http://k.net/c" = return [TagOpen "a" [("href", "git.io")]]
testIO action assertion = assertion <$> action | ptek/sclent | tests/Unit/Service/CrawlerServiceTest.hs | bsd-3-clause | 1,416 | 0 | 12 | 184 | 500 | 281 | 219 | 24 | 1 |
{-# LANGUAGE FlexibleInstances #-}
module Network.SPDY.Internal.Serialize where
import Blaze.ByteString.Builder
import Data.Bits (setBit, shiftL, shiftR, (.&.))
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.List (foldl')
import Data.Monoid
import Data.Word (Word8, Word16, Word32)
import Network.SPDY.Compression (Deflate, compress)
import Network.SPDY.Flags
import Network.SPDY.Frames
import Network.SPDY.Internal.Constants
import Network.SPDY.Internal.ToWord8
rawFrameBuilder :: RawFrame -> Builder
rawFrameBuilder frame =
rawHeaderBuilder (frameHeader frame) `mappend`
fromWord8 (flagsByte frame) `mappend`
toBuilder (payloadLength frame) `mappend`
fromByteString (payload frame)
instance ToBuilder DataLength where
toBuilder (DataLength dl) = fromWord24be dl
fromWord24be :: Word32 -> Builder
fromWord24be w =
fromWord8 wHi8 `mappend`
fromWord16be wLo16
where wHi8 = fromIntegral $ (w `shiftR` 16) .&. 0xff
wLo16 = fromIntegral $ w .&. 0xffff
rawHeaderBuilder :: RawFrameHeader -> Builder
rawHeaderBuilder header =
case header of
ControlFrameHeader v ct ->
fromWord16be (setBit (rawSPDYVersion v) 15) `mappend`
fromWord16be ct
DataFrameHeader sid ->
fromWord32be (rawStreamID sid)
toRawFrameHeader :: Frame -> RawFrameHeader
toRawFrameHeader frame =
case frame of
AControlFrame v cf ->
ControlFrameHeader v $ toControlType cf
ADataFrame d ->
DataFrameHeader (streamID d)
toControlType :: ControlFrame -> Word16
toControlType details =
case details of
ASynStreamFrame _ -> cftSynStream
ASynReplyFrame _ -> cftSynReply
ARstStreamFrame _ -> cftRstStream
ASettingsFrame _ -> cftSettings
APingFrame _ -> cftPing
AGoAwayFrame _ -> cftGoAway
AHeadersFrame _ -> cftHeaders
AWindowUpdateFrame _ -> cftWindowUpdate
ACredentialFrame _ -> cftCredential
toFlagsByte :: Frame -> Word8
toFlagsByte frame =
case frame of
AControlFrame _ cf ->
case cf of
ASynStreamFrame ss -> toWord8 $ synStreamFlags ss
ASynReplyFrame sr -> toWord8 $ synReplyFlags sr
ASettingsFrame s -> toWord8 $ settingsFlags s
AHeadersFrame h -> toWord8 $ headersFlags h
_ -> 0x0
ADataFrame d -> toWord8 $ dataFlags d
toPayload :: Deflate -> Frame -> IO ByteString
toPayload deflate frame =
case frame of
AControlFrame _ cf ->
toControlPayload deflate cf
ADataFrame d ->
return $ dataBytes d
toControlPayload :: Deflate -> ControlFrame -> IO ByteString
toControlPayload deflate = fmap toByteString . toControlPayloadBuilder deflate
toControlPayloadBuilder :: Deflate -> ControlFrame -> IO Builder
toControlPayloadBuilder deflate cf =
case cf of
ASynStreamFrame ss ->
fmap (toBuilder (synStreamNewStreamID ss) `mappend`
toBuilder (synStreamAssociatedTo ss) `mappend`
toBuilder (synStreamPriority ss) `mappend`
toBuilder (synStreamSlot ss) `mappend`) $ compressHeaderBlock deflate $ synStreamHeaderBlock ss
ASynReplyFrame sr ->
fmap (toBuilder (synReplyNewStreamID sr) `mappend`) $ compressHeaderBlock deflate $ synReplyHeaderBlock sr
ARstStreamFrame rs ->
return $ toBuilder (rstStreamTermStreamID rs) `mappend` toBuilder (rstStreamTermStatus rs)
ASettingsFrame s ->
return $ toBuilder (settingsPairs s)
APingFrame p ->
return $ toBuilder (pingID p)
AGoAwayFrame g ->
return $ toBuilder (goAwayLastGoodStreamID g) `mappend` toBuilder (goAwayStatus g)
AHeadersFrame h ->
return $ toBuilder (headersStreamID h) `mappend` toBuilder (headersHeaderBlock h)
AWindowUpdateFrame w ->
return $ toBuilder (windowUpdateStreamID w) `mappend` toBuilder (windowUpdateDeltaWindowSize w)
ACredentialFrame c ->
return $ toBuilder (credentialSlot c) `mappend` toBuilder (credentialProof c) `mappend` toBuilder (credentialCertificates c)
compressHeaderBlock :: Deflate -> HeaderBlock -> IO Builder
compressHeaderBlock deflate hb =
compress deflate $ toByteString $ toBuilder hb
class ToBuilder a where
toBuilder :: a -> Builder
instance ToBuilder StreamID where
toBuilder (StreamID w) = fromWord32be w
instance ToBuilder (Maybe StreamID) where
toBuilder = maybe (fromWord32be 0x0) toBuilder
instance ToBuilder Priority where
toBuilder (Priority w) = fromWord8 (w `shiftL` 5)
instance ToBuilder Slot where
toBuilder (Slot w) = fromWord8 w
instance ToBuilder HeaderBlock where
toBuilder hb =
toBuilder (headerCount hb) `mappend` headerPairsBuilder (headerPairs hb)
instance ToBuilder HeaderCount where
toBuilder (HeaderCount w) = fromWord32be w
instance ToBuilder HeaderName where
toBuilder (HeaderName bs) = lengthAndBytes bs
instance ToBuilder HeaderValue where
toBuilder (HeaderValue bs) = lengthAndBytes bs
lengthAndBytes :: ByteString -> Builder
lengthAndBytes bs = fromWord32be (fromIntegral $ B.length bs) `mappend` fromByteString bs
headerPairsBuilder :: [(HeaderName, HeaderValue)] -> Builder
headerPairsBuilder =
foldl' mappend mempty . map fromPair
where fromPair (name, val) = toBuilder name `mappend` toBuilder val
instance ToBuilder PingID where
toBuilder (PingID w) = fromWord32be w
instance ToBuilder DeltaWindowSize where
toBuilder (DeltaWindowSize w) = fromWord32be w
instance ToBuilder TerminationStatus where
toBuilder ts = fromWord32be $ case ts of
ProtocolError -> tsProtocolError
InvalidStream -> tsInvalidStream
RefusedStream -> tsRefusedStream
UnsupportedVersion -> tsUnsupportedVersion
Cancel -> tsCancel
InternalError -> tsInternalError
FlowControlError -> tsFlowControlError
StreamInUse -> tsStreamInUse
StreamAlreadyClosed -> tsStreamAlreadyClosed
InvalidCredentials -> tsInvalidCredentials
FrameTooLarge -> tsFrameTooLarge
TerminationStatusUnknown w -> w
instance ToBuilder [(SettingIDAndFlags, SettingValue)] where
toBuilder pairs =
fromWord32be (fromIntegral $ length pairs) `mappend`
foldl' mappend mempty (map fromPair pairs)
where fromPair (idfs, v) = toBuilder idfs `mappend` toBuilder v
instance ToBuilder SettingIDAndFlags where
toBuilder stidfs =
toBuilder (settingIDFlags stidfs) `mappend`
toBuilder (settingID stidfs)
instance ToBuilder SettingID where
toBuilder stid = fromWord24be $ case stid of
SettingsUploadBandwidth -> stidSettingsUploadBandwidth
SettingsDownloadBandwidth -> stidSettingsDownloadBandwidth
SettingsRoundTripTime -> stidSettingsRoundTripTime
SettingsMaxConcurrentStreams -> stidSettingsMaxConcurrentStreams
SettingsCurrentCWND -> stidSettingsCurrentCWND
SettingsDownloadRetransRate -> stidSettingsDownloadRetransRate
SettingsInitialWindowSize -> stidSettingsInitialWindowSize
SettingsClientCertificateVectorSize -> stidSettingsClientCertificateVectorSize
SettingsOther w -> w
instance ToBuilder SettingValue where
toBuilder (SettingValue sv) = fromWord32be sv
instance ToBuilder GoAwayStatus where
toBuilder s = fromWord32be $ case s of
GoAwayOK -> gsGoAwayOK
GoAwayProtocolError -> gsGoAwayProtocolError
GoAwayInternalError -> gsGoAwayInternalError
GoAwayStatusUnknown w -> w
instance ToBuilder Slot16 where
toBuilder (Slot16 w) = fromWord16be w
instance ToBuilder Proof where
toBuilder (Proof bs) = lengthAndBytes bs
instance ToBuilder [Certificate] where
toBuilder = foldl' mappend mempty . map toBuilder
instance ToBuilder Certificate where
toBuilder (Certificate bs) = lengthAndBytes bs
instance ToBuilder (Flags f) where
toBuilder (Flags w) = fromWord8 w
| kcharter/spdy-base | src/Network/SPDY/Internal/Serialize.hs | bsd-3-clause | 7,641 | 0 | 17 | 1,383 | 2,102 | 1,055 | 1,047 | 183 | 9 |
module Problem16
( powerDigitSum
) where
import Lib (digits)
powerDigitSum :: Integer -> Integer -> Integer
powerDigitSum x pow = sum.digits $ x^pow
| candidtim/euler | src/Problem16.hs | bsd-3-clause | 157 | 0 | 7 | 31 | 50 | 28 | 22 | 5 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
-- | A @Trajectory@ instance based on a chronologically ordered
-- list of data. The start and end times are determined by the
-- first and last datum in the list.
module Astro.Trajectory.EphemTrajectory
( EphemTrajectory (ET)
) where
import Numeric.Units.Dimensional.Prelude
import Astro.Orbit.MEOE
import Astro.Orbit.Types
import Astro.Trajectory
import Astro.Time
import Astro.Time.At
import Astro.Orbit.Interpolate
import qualified Prelude
-- | Interpolate linearly in an ordered list of ephemeris to obtain
-- the MEOE at the given time. If the given time is outside the
-- range covered by the list the end element are extrapolated.
meoeAt :: (RealFloat a, Ord a) => [Datum t a] -> E t a -> MEOE Mean a
meoeAt [] _ = error "Can not interpolate an empty list"
meoeAt (x:[]) _ = value x
meoeAt (x1:x2:[]) t = linearPolateMEOEm x1 x2 t
meoeAt (x1:x2:xs) t = if t < epoch x2 then linearPolateMEOEm x1 x2 t
else meoeAt (x2:xs) t
-- | Interpolate linearly in an ordered list of ephemeris to obtain
-- the MEOE at the given time. If the given time is outside the
-- range covered by the list @Nothing@ is returned.
meoeAtMaybe :: (RealFloat a, Ord a) => [Datum t a] -> E t a -> Maybe (MEOE Mean a)
meoeAtMaybe [] _ = Nothing
meoeAtMaybe [m`At`t0] t = if t == t0 then Just m else Nothing
meoeAtMaybe (x1:x2:xs) t = if t > epoch x2 then meoeAtMaybe (x2:xs) t
else if t < epoch x1 then Nothing
else Just (linearPolateMEOEm x1 x2 t)
-- The input arrays must be chronologically ordered.
meoes :: (RealFloat a, Ord a) => [Datum t a] -> [E t a] -> [Datum t a]
meoes [] _ = []
meoes (x:xs) ts = go (x:xs) $ dropWhile (< epoch x) ts
where
-- We already know that @xs@ is non-empty and @t >= epoch x@.
go :: (RealFloat a, Ord a) => [Datum t a] -> [E t a] -> [Datum t a]
go _ [] = []
go [x] (t:_) = if t == epoch x then [x] else []
go (x0:x1:xs) (t:ts)
| t == epoch x0 = x0:go (x0:x1:xs) ts
| t >= epoch x1 = go (x1:xs) (t:ts)
| otherwise = linearPolateMEOEm x0 x1 t`At`t:go (x0:x1:xs) ts
newtype EphemTrajectory t a = ET [Datum t a]
-- Should I skip this newtype and just define an instance for the list??
instance (RealFloat a) => Trajectory EphemTrajectory t a
where
startTime (ET []) = mjd' 0
startTime (ET xs) = epoch (head xs)
endTime (ET []) = mjd' 0
endTime (ET xs) = epoch (last xs)
ephemeris (ET xs) ts = meoes xs ts
| bjornbm/astro-orbit | Astro/Trajectory/EphemTrajectory.hs | bsd-3-clause | 2,598 | 0 | 12 | 658 | 916 | 482 | 434 | 44 | 4 |
{-# OPTIONS_GHC -fno-warn-missing-fields #-}
{-# LANGUAGE TypeSynonymInstances, StandaloneDeriving, DeriveDataTypeable, FlexibleInstances, TypeOperators #-}
module Database.PostgreSQL.Simple.Tuple.Common
( groupJoin
, tuple2
, tuple3
, tuple4
, tuple5
, tuple6
, tuple7
, tuple8
, tuple9
, tuple10
, tuple11
, tuple1of3
, tuple2of3
, tuple1of4
, tuple2of4
, tuple3of4
, tuple1of5
, tuple2of5
, tuple3of5
, tuple4of5
, tuple1of6
, tuple2of6
, tuple3of6
, tuple4of6
, tuple5of6
, tuple1of7
, tuple2of7
, tuple3of7
, tuple4of7
, tuple5of7
, tuple6of7
, tuple1of8
, tuple2of8
, tuple3of8
, tuple4of8
, tuple5of8
, tuple6of8
, tuple7of8
, tuple1of9
, tuple2of9
, tuple3of9
, tuple4of9
, tuple5of9
, tuple6of9
, tuple7of9
, tuple8of9
, tuple1of10
, tuple2of10
, tuple3of10
, tuple4of10
, tuple5of10
, tuple6of10
, tuple7of10
, tuple8of10
, tuple9of10
, tuple1of11
, tuple2of11
, tuple3of11
, tuple4of11
, tuple5of11
, tuple6of11
, tuple7of11
, tuple8of11
, tuple9of11
, tuple10of11
)
where
import Control.Arrow (second)
import Data.Maybe (catMaybes, mapMaybe, isJust)
import Data.List (groupBy)
import Data.Function (on)
import Database.PostgreSQL.Simple ((:.)(..))
groupJoin :: Eq a => [(a, b)] -> [(a, [b])]
groupJoin xs = map reduce $ groupBy ((==) `on` fst) xs where
reduce xs' = (fst $ head xs', map snd xs')
{----------------------------------------------------------------------------------------------------{
| Simple Tuples
}----------------------------------------------------------------------------------------------------}
tuple2 :: (a :. b) -> (a, b)
tuple2 (a:.b) = (a,b)
tuple3 :: (a :. (b :. c)) -> (a, b, c)
tuple3 (a:.b:.c) = (a,b,c)
tuple4 :: (a :. (b :. (c :. d))) -> (a, b, c, d)
tuple4 (a:.b:.c:.d) = (a,b,c,d)
tuple5 :: (a :. (b :. (c :. (d :. e)))) -> (a, b, c, d, e)
tuple5 (a:.b:.c:.d:.e) = (a,b,c,d,e)
tuple6 :: (a :. (b :. (c :. (d :. (e :. f))))) -> (a, b, c, d, e, f)
tuple6 (a:.b:.c:.d:.e:.f) = (a,b,c,d,e,f)
tuple7 :: (a :. (b :. (c :. (d :. (e :. (f :. g)))))) -> (a, b, c, d, e, f, g)
tuple7 (a:.b:.c:.d:.e:.f:.g) = (a,b,c,d,e,f,g)
tuple8 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. h))))))) -> (a, b, c, d, e, f, g, h)
tuple8 (a:.b:.c:.d:.e:.f:.g:.h) = (a,b,c,d,e,f,g,h)
tuple9 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. i)))))))) -> (a, b, c, d, e, f, g, h, i)
tuple9 (a:.b:.c:.d:.e:.f:.g:.h:.i) = (a,b,c,d,e,f,g,h,i)
tuple10 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. j))))))))) -> (a, b, c, d, e, f, g, h, i, j)
tuple10 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j) = (a,b,c,d,e,f,g,h,i,j)
tuple11 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. (j :. k)))))))))) -> (a, b, c, d, e, f, g, h, i, j, k)
tuple11 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j:.k) = (a,b,c,d,e,f,g,h,i,j,k)
{----------------------------------------------------------------------------------------------------{
| Grouped Tuples
}----------------------------------------------------------------------------------------------------}
---------------------------------------------------------------------- | Groups of 3
tuple1of3 :: (a :. (b :. c)) -> (a, (b, c))
tuple1of3 (a:.b:.c) = (a,(b,c))
tuple2of3 :: (a :. (b :. c)) -> ((a, b), c)
tuple2of3 (a:.b:.c) = ((a,b),c)
---------------------------------------------------------------------- | Groups of 4
tuple1of4 :: (a :. (b :. (c :. d))) -> (a, (b, c, d))
tuple1of4 (a:.b:.c:.d) = (a,(b,c,d))
tuple2of4 :: (a :. (b :. (c :. d))) -> ((a, b), (c, d))
tuple2of4 (a:.b:.c:.d) = ((a,b),(c,d))
tuple3of4 :: (a :. (b :. (c :. d))) -> ((a, b, c), d)
tuple3of4 (a:.b:.c:.d) = ((a,b,c),d)
---------------------------------------------------------------------- | Groups of 5
tuple1of5 :: (a :. (b :. (c :. (d :. e)))) -> (a, (b, c, d, e))
tuple1of5 (a:.b:.c:.d:.e) = (a,(b,c,d,e))
tuple2of5 :: (a :. (b :. (c :. (d :. e)))) -> ((a, b), (c, d, e))
tuple2of5 (a:.b:.c:.d:.e) = ((a,b),(c,d,e))
tuple3of5 :: (a :. (b :. (c :. (d :. e)))) -> ((a, b, c), (d, e))
tuple3of5 (a:.b:.c:.d:.e) = ((a,b,c),(d,e))
tuple4of5 :: (a :. (b :. (c :. (d :. e)))) -> ((a, b, c, d), e)
tuple4of5 (a:.b:.c:.d:.e) = ((a,b,c,d),e)
---------------------------------------------------------------------- | Groups of 6
tuple1of6 :: (a :. (b :. (c :. (d :. (e :. f))))) -> (a, (b, c, d, e, f))
tuple1of6 (a:.b:.c:.d:.e:.f) = (a,(b,c,d,e,f))
tuple2of6 :: (a :. (b :. (c :. (d :. (e :. f))))) -> ((a, b), (c, d, e, f))
tuple2of6 (a:.b:.c:.d:.e:.f) = ((a,b),(c,d,e,f))
tuple3of6 :: (a :. (b :. (c :. (d :. (e :. f))))) -> ((a, b, c), (d, e, f))
tuple3of6 (a:.b:.c:.d:.e:.f) = ((a,b,c),(d,e,f))
tuple4of6 :: (a :. (b :. (c :. (d :. (e :. f))))) -> ((a, b, c, d), (e, f))
tuple4of6 (a:.b:.c:.d:.e:.f) = ((a,b,c,d),(e,f))
tuple5of6 :: (a :. (b :. (c :. (d :. (e :. f))))) -> ((a, b, c, d, e), f)
tuple5of6 (a:.b:.c:.d:.e:.f) = ((a,b,c,d,e),f)
---------------------------------------------------------------------- | Groups of 7
tuple1of7 :: (a :. (b :. (c :. (d :. (e :. (f :. g)))))) -> (a, (b, c, d, e, f, g))
tuple1of7 (a:.b:.c:.d:.e:.f:.g) = (a,(b,c,d,e,f,g))
tuple2of7 :: (a :. (b :. (c :. (d :. (e :. (f :. g)))))) -> ((a, b), (c, d, e, f, g))
tuple2of7 (a:.b:.c:.d:.e:.f:.g) = ((a,b),(c,d,e,f,g))
tuple3of7 :: (a :. (b :. (c :. (d :. (e :. (f :. g)))))) -> ((a, b, c), (d, e, f, g))
tuple3of7 (a:.b:.c:.d:.e:.f:.g) = ((a,b,c),(d,e,f,g))
tuple4of7 :: (a :. (b :. (c :. (d :. (e :. (f :. g)))))) -> ((a, b, c, d), (e, f, g))
tuple4of7 (a:.b:.c:.d:.e:.f:.g) = ((a,b,c,d),(e,f,g))
tuple5of7 :: (a :. (b :. (c :. (d :. (e :. (f :. g)))))) -> ((a, b, c, d, e), (f, g))
tuple5of7 (a:.b:.c:.d:.e:.f:.g) = ((a,b,c,d,e),(f,g))
tuple6of7 :: (a :. (b :. (c :. (d :. (e :. (f :. g)))))) -> ((a, b, c, d, e, f), g)
tuple6of7 (a:.b:.c:.d:.e:.f:.g) = ((a,b,c,d,e,f),g)
---------------------------------------------------------------------- | Groups of 8
tuple1of8 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. h))))))) -> (a, (b, c, d, e, f, g, h))
tuple1of8 (a:.b:.c:.d:.e:.f:.g:.h) = (a,(b,c,d,e,f,g,h))
tuple2of8 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. h))))))) -> ((a, b), (c, d, e, f, g, h))
tuple2of8 (a:.b:.c:.d:.e:.f:.g:.h) = ((a,b),(c,d,e,f,g,h))
tuple3of8 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. h))))))) -> ((a, b, c), (d, e, f, g, h))
tuple3of8 (a:.b:.c:.d:.e:.f:.g:.h) = ((a,b,c),(d,e,f,g,h))
tuple4of8 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. h))))))) -> ((a, b, c, d), (e, f, g, h))
tuple4of8 (a:.b:.c:.d:.e:.f:.g:.h) = ((a,b,c,d),(e,f,g,h))
tuple5of8 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. h))))))) -> ((a, b, c, d, e), (f, g, h))
tuple5of8 (a:.b:.c:.d:.e:.f:.g:.h) = ((a,b,c,d,e),(f,g,h))
tuple6of8 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. h))))))) -> ((a, b, c, d, e, f), (g, h))
tuple6of8 (a:.b:.c:.d:.e:.f:.g:.h) = ((a,b,c,d,e,f),(g,h))
tuple7of8 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. h))))))) -> ((a, b, c, d, e, f, g), h)
tuple7of8 (a:.b:.c:.d:.e:.f:.g:.h) = ((a,b,c,d,e,f,g),h)
---------------------------------------------------------------------- | Groups of 9
tuple1of9 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. i)))))))) -> (a, (b, c, d, e, f, g, h, i))
tuple1of9 (a:.b:.c:.d:.e:.f:.g:.h:.i) = (a,(b,c,d,e,f,g,h,i))
tuple2of9 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. i)))))))) -> ((a, b), (c, d, e, f, g, h, i))
tuple2of9 (a:.b:.c:.d:.e:.f:.g:.h:.i) = ((a,b),(c,d,e,f,g,h,i))
tuple3of9 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. i)))))))) -> ((a, b, c), (d, e, f, g, h, i))
tuple3of9 (a:.b:.c:.d:.e:.f:.g:.h:.i) = ((a,b,c),(d,e,f,g,h,i))
tuple4of9 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. i)))))))) -> ((a, b, c, d), (e, f, g, h, i))
tuple4of9 (a:.b:.c:.d:.e:.f:.g:.h:.i) = ((a,b,c,d),(e,f,g,h,i))
tuple5of9 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. i)))))))) -> ((a, b, c, d, e), (f, g, h, i))
tuple5of9 (a:.b:.c:.d:.e:.f:.g:.h:.i) = ((a,b,c,d,e),(f,g,h,i))
tuple6of9 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. i)))))))) -> ((a, b, c, d, e, f), (g, h, i))
tuple6of9 (a:.b:.c:.d:.e:.f:.g:.h:.i) = ((a,b,c,d,e,f),(g,h,i))
tuple7of9 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. i)))))))) -> ((a, b, c, d, e, f, g), (h, i))
tuple7of9 (a:.b:.c:.d:.e:.f:.g:.h:.i) = ((a,b,c,d,e,f,g),(h,i))
tuple8of9 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. i)))))))) -> ((a, b, c, d, e, f, g, h), i)
tuple8of9 (a:.b:.c:.d:.e:.f:.g:.h:.i) = ((a,b,c,d,e,f,g,h),i)
---------------------------------------------------------------------- | Groups of 10
tuple1of10 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. j))))))))) -> (a, (b, c, d, e, f, g, h, i, j))
tuple1of10 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j) = (a,(b,c,d,e,f,g,h,i,j))
tuple2of10 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. j))))))))) -> ((a, b), (c, d, e, f, g, h, i, j))
tuple2of10 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j) = ((a,b),(c,d,e,f,g,h,i,j))
tuple3of10 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. j))))))))) -> ((a, b, c), (d, e, f, g, h, i, j))
tuple3of10 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j) = ((a,b,c),(d,e,f,g,h,i,j))
tuple4of10 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. j))))))))) -> ((a, b, c, d), (e, f, g, h, i, j))
tuple4of10 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j) = ((a,b,c,d),(e,f,g,h,i,j))
tuple5of10 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. j))))))))) -> ((a, b, c, d, e), (f, g, h, i, j))
tuple5of10 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j) = ((a,b,c,d,e),(f,g,h,i,j))
tuple6of10 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. j))))))))) -> ((a, b, c, d, e, f), (g, h, i, j))
tuple6of10 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j) = ((a,b,c,d,e,f),(g,h,i,j))
tuple7of10 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. j))))))))) -> ((a, b, c, d, e, f, g), (h, i, j))
tuple7of10 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j) = ((a,b,c,d,e,f,g),(h,i,j))
tuple8of10 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. j))))))))) -> ((a, b, c, d, e, f, g, h), (i, j))
tuple8of10 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j) = ((a,b,c,d,e,f,g,h),(i,j))
tuple9of10 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. j))))))))) -> ((a, b, c, d, e, f, g, h, i), j)
tuple9of10 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j) = ((a,b,c,d,e,f,g,h,i),j)
---------------------------------------------------------------------- | Groups of 11
tuple1of11 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. (j :. k)))))))))) -> (a, (b, c, d, e, f, g, h, i, j, k))
tuple1of11 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j:.k) = (a,(b,c,d,e,f,g,h,i,j,k))
tuple2of11 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. (j :. k)))))))))) -> ((a, b), (c, d, e, f, g, h, i, j, k))
tuple2of11 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j:.k) = ((a,b),(c,d,e,f,g,h,i,j,k))
tuple3of11 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. (j :. k)))))))))) -> ((a, b, c), (d, e, f, g, h, i, j, k))
tuple3of11 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j:.k) = ((a,b,c),(d,e,f,g,h,i,j,k))
tuple4of11 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. (j :. k)))))))))) -> ((a, b, c, d), (e, f, g, h, i, j, k))
tuple4of11 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j:.k) = ((a,b,c,d),(e,f,g,h,i,j,k))
tuple5of11 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. (j :. k)))))))))) -> ((a, b, c, d, e), (f, g, h, i, j, k))
tuple5of11 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j:.k) = ((a,b,c,d,e),(f,g,h,i,j,k))
tuple6of11 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. (j :. k)))))))))) -> ((a, b, c, d, e, f), (g, h, i, j, k))
tuple6of11 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j:.k) = ((a,b,c,d,e,f),(g,h,i,j,k))
tuple7of11 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. (j :. k)))))))))) -> ((a, b, c, d, e, f, g), (h, i, j, k))
tuple7of11 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j:.k) = ((a,b,c,d,e,f,g),(h,i,j,k))
tuple8of11 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. (j :. k)))))))))) -> ((a, b, c, d, e, f, g, h), (i, j, k))
tuple8of11 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j:.k) = ((a,b,c,d,e,f,g,h),(i,j,k))
tuple9of11 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. (j :. k)))))))))) -> ((a, b, c, d, e, f, g, h, i), (j, k))
tuple9of11 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j:.k) = ((a,b,c,d,e,f,g,h,i),(j,k))
tuple10of11 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. (j :. k)))))))))) -> ((a, b, c, d, e, f, g, h, i, j), k)
tuple10of11 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j:.k) = ((a,b,c,d,e,f,g,h,i,j),k)
| cimmanon/postgresql-simple-tuple | src/Database/PostgreSQL/Simple/Tuple/Common.hs | bsd-3-clause | 12,425 | 4 | 25 | 2,431 | 10,049 | 5,956 | 4,093 | 204 | 1 |
{-# language FlexibleContexts #-}
module Graph.Util
( module Graph.Util
, module Autolib.Graph.Type
, module Autolib.Reporter
, module Autolib.Reporter.Set
, module Autolib.ToDoc
, module Autolib.FiniteMap
)
where
import Autolib.Graph.Type hiding ( iso )
import Autolib.Graph.Ops ( restrict , unlinks )
import Autolib.Graph.Util ( isZusammen , anzKnoten )
import Autolib.Graph.Adj ( AdjMatrix , adjazenz_matrix )
import Autolib.Reporter
import Autolib.Reporter.Set
import Autolib.FiniteMap
import Autolib.ToDoc
import Autolib.Schichten
import Autolib.Set
import Autolib.Util.Fix ( fixL )
validate :: GraphC a
=> Graph a
-> Reporter ()
validate g = do
let outs = do
k <- lkanten g
guard $ not ( von k `elementOf` knoten g
&& nach k `elementOf` knoten g
)
return k
when ( not $ null outs ) $ reject $ vcat
[ text "diese Kanten benutzen nicht deklarierte Knoten:"
, nest 4 $ toDoc outs
]
let loops = do
k <- lkanten g
guard $ von k == nach k
return k
when ( not $ null loops ) $ reject $ vcat
[ text "diese Kanten sind Schlingen:"
, nest 4 $ toDoc loops
]
equal_set :: ( Ord a, ToDoc [a] )
=> ( Doc, Set a )
-> ( Doc, Set a )
-> Reporter ()
equal_set = Autolib.Reporter.Set.eq
nachbarn :: GraphC a => Graph a -> a -> Set a
nachbarn g x = mkSet $ lnachbarn g x
lnachbarn :: GraphC a => Graph a -> a -> [ a ]
lnachbarn g x = do
k <- lkanten g
if x == von k then return $ nach k
else if x == nach k then return $ von k
else mzero
reachables :: GraphC a => Graph a -> a -> Set a
reachables g x = unionManySets $ schichten ( nachbarn g ) x
-------------------------------------------------------------------------------
-- | echte nachfolger (nicht reflexive nachfolger-hülle)
sucs :: GraphC a => Graph a -> a -> Set a
sucs g = last . fixL . scanl union emptySet . tail
. schichten_with_loops (nachbarn g)
-- | echte nachfolger, die genau n>0 schritte entfernt sind, n=0 -> keine!
sucsN :: GraphC a => Int -> Graph a -> a -> Set a
sucsN 0 _ _ = emptySet
sucsN n g x = schichten_with_loops (nachbarn g) x !! n
-- | gibt es nichtleeren pfad von x nach y?
path :: GraphC a => Graph a -> a -> a -> Bool
path g x y = y `elementOf` sucs g x
-- | gibt es pfad der länge n von x nach y
pathN :: GraphC a => Int -> Graph a -> a -> a -> Bool
pathN n g x y = y `elementOf` sucsN n g x
-- | erreichbarkeitsgraph: kanten zwischen allen knoten, zwischen
-- | denen ein nichtleerer pfad existiert
-- | es gilt: adjazenz_matrix . egraph == wegematrix
egraph :: GraphC a => Graph a -> Graph a
egraph g = gen_egraph (path g) g
wegematrix :: GraphC a => Graph a -> AdjMatrix
wegematrix = adjazenz_matrix . egraph
-- | erreichbarkeitsgraph: kanten zwischen allen knoten, zwischen
-- | denen ein Pfad der Länge n existiert
-- | es gilt: n>0 => adjazenz_matrix (egraphN n g) = sig (adjazenz_matrix g)^n
egraphN :: GraphC a => Int -> Graph a -> Graph a
egraphN n g = gen_egraph (pathN n g) g
gen_egraph :: GraphC a => ( a -> a -> Bool ) -> Graph a -> Graph a
gen_egraph f g = mkGraph (knoten g)
(mkSet $ do
(x,y) <- setToList $ cross (knoten g) (knoten g)
guard $ f x y
return $ kante x y
)
-------------------------------------------------------------------------------
degree :: GraphC a => Graph a -> a -> Int
degree g x = cardinality $ nachbarn g x
lkanten :: GraphC a => Graph a -> [Kante a]
lkanten = setToList . kanten
lknoten :: GraphC a => Graph a -> [a]
lknoten = setToList . knoten
is_clique :: ( ToDoc [a], GraphC a ) => Graph a -> Set a -> Bool
is_clique g s =
let h = restrict s g
n = cardinality $ knoten h
m = cardinality $ kanten h
in 2 * m == n * pred n
is_independent :: GraphC a => Graph a -> Set a -> Bool
is_independent g s =
let h = restrict s g
m = cardinality $ kanten h
in 0 == m
is_connected :: GraphC a => Graph a -> Bool
is_connected g =
let xs = reachables g ( head $ lknoten g )
in xs == knoten g
check_reg :: ( ToDoc a, ToDoc [a], GraphC a )
=> Graph a
-> Reporter ()
check_reg g = do
inform $ fsep [ text "ist der Graph", info g, text "regulär?" ]
let degs = fmToList $ addListToFM_C union emptyFM $ do
x <- lknoten g
return (degree g x, unitSet x)
if length degs > 1
then reject $ text "nein, die Knotengrade sind" $$ toDoc degs
else inform $ text "ja."
ist_clique :: GraphC a => Graph a -> Bool
ist_clique g =
let n = cardinality $ knoten g
m = cardinality $ kanten g
in 2 * m == n * pred n
no_fixed_layout :: GraphC a => Graph a -> Graph a
no_fixed_layout g = g { graph_layout = emptyFM
, layout_hints = []
}
-------------------------------------------------------------------------------
-- | radius und durchmesser in einem rutsch
rad_diam :: GraphC a => Graph a -> Maybe (Int,Int)
rad_diam g | not $ isZusammen g = Nothing
rad_diam g = let suc = nachbarn g
ls = map ( pred . length . schichten suc ) $ lknoten g
in Just ( minimum ls , maximum ls )
-- | radius
rad :: GraphC a => Graph a -> Maybe Int
rad g = rad_diam g >>= return . fst
-- | durchmesser
diam :: GraphC a => Graph a -> Maybe Int
diam g = rad_diam g >>= return . snd
-------------------------------------------------------------------------------
-- | artikulationspunkte: knoten, die durch entfernen zu einem
-- | nicht-zusammenhängenden graphen führen. beachte: wenn der
-- | ausgangsgraph nicht zusammenhängend ist, dann sind alle knoten
-- | artikulationspunkte!
artikulationen :: GraphC a => Graph a -> [a]
artikulationen g = filter ( \ n -> not $ isZusammen
$ restrict (delFromSet (knoten g) n) g
)
$ setToList $ knoten g
-------------------------------------------------------------------------------
-- | einfach zusammenhängende komponenten als liste von graphen
komponenten :: GraphC a => Graph a -> [Graph a]
komponenten g
| isEmptySet rs_quer = [g]
| otherwise = restrict rs g : komponenten (restrict rs_quer g)
where v = knoten g
x = head $ setToList v
rs = reachables g x
rs_quer = knoten g `minusSet` rs
-------------------------------------------------------------------------------
-- | bisektion: eine kantenmenge wird entfernt, sodass der
-- | resultierende graph in zwei teilgraphen (nicht komponenten!)
-- | zerfällt, die sich um höchstens eins in der knotenzahl
-- | unterscheiden und zwischen denen keine kanten verlaufen
bisektionen :: GraphC a => Graph a -> [ Set (Kante a) ]
bisektionen g = filter ( ist_bisektiert . unlinks g . setToList
) $ subsets $ kanten g
ist_bisektiert :: GraphC a => Graph a -> Bool
ist_bisektiert g = let n = anzKnoten g
ns = teilmengen (div n 2) (knoten g)
in any (bisektierend g) ns
bisektierend :: GraphC a => Graph a -> Set a -> Bool
bisektierend g ns = all ( \ k -> not $ or
[ and [ von k `elementOf` ns
, not $ nach k `elementOf` ns
]
, and [ nach k `elementOf` ns
, not $ von k `elementOf` ns
]
]
) $ lkanten g
-- | bisektionsweite: minimale anzahl kanten die zur bisektion
-- | entfernt werden muss -> maß für zuverlässigkeit von netzen
bisektionsweite :: GraphC a => Graph a -> Int
bisektionsweite = cardinality . head . bisektionen
| florianpilz/autotool | src/Graph/Util.hs | gpl-2.0 | 7,438 | 203 | 41 | 1,868 | 2,441 | 1,304 | 1,137 | 152 | 3 |
module GameLogic.Logic
( setCenterPosLimited
, setCenterPos
, doSelectCellAction
, doGameStep
, WorldAction
) where
import Debug.Trace
import Control.Lens hiding ((<|), (|>))
import Control.Conditional
import GameLogic.Data.Facade
import GameLogic.Util
import GameLogic.AI.Actions
import GameLogic.AI.PossibleAction
import GameLogic.Action.Defend
import GameLogic.Action.Attack
setCenterPosLimited :: WorldAction
setCenterPosLimited pos = do
pos' <- gets $ limitPosToWorld pos
centerPos .= pos' >> {- _traceTest pos' >> -} doSelectCellAction pos'
setCenterPos :: WorldAction
setCenterPos pos = whenM (isPosInGame pos)
$ (centerPos .= pos) >> doSelectCellAction pos
_traceTest :: WorldPos -> GameState ()
_traceTest pos = do
game <- get
traceShow (calcPossibleAction game 2 10 pos)
. traceShow (calcPossibleActions game 2)
$ return ()
doSelectCellAction :: WorldAction
doSelectCellAction pos = whenM (isPosInGame pos)
$ setSelectedPos pos activePlayerIndex
doGameStep :: GameState ()
doGameStep = unlessM (use paused)
$ updatePlayersStats
>> doHumanGameStep
>> doAIsGameStep
doHumanGameStep :: GameState ()
doHumanGameStep = do
pos <- use $ playerOfGame activePlayerIndex . selectedPos
whenM (use placementMode) $ doCellAction pos
updatePlayersStats :: GameState ()
updatePlayersStats = do
remainDiv <- gets calcRemainDiv
players . each %= updatePlayerStats remainDiv
calcRemainDiv :: GameData -> Int
calcRemainDiv game = maxnum * remainDivMult (game ^. gameSpeed)
where getPlayersNums = toListOf $ players . each . num
maxnum = maximum $ remainDivMin : getPlayersNums game
updatePlayerStats :: Int -> Player -> Player
updatePlayerStats remainDiv pl =
let d = view remain pl
d' = (+) d $ view num pl
(free1, remain') = d' `divMod` remainDiv
free2 = (+) free1 $ view free pl
free3 = toRange (-100, 9999) free2
in pl & set remain remain' . set free free3
doCellAction :: WorldAction
doCellAction pos = whenM (isPosInGame pos)
$ doCellAction' activePlayerIndex pos
doCellAction' :: Int -> WorldAction
doCellAction' playerInd pos = do
cell <- use $ cellOfGame pos
increaseCell pos playerInd
<| cell ^. playerIndex == playerInd || isFree cell |>
attackCell pos playerInd
| EPashkin/gamenumber-freegame | src_gl/GameLogic/Logic.hs | gpl-3.0 | 2,348 | 0 | 12 | 483 | 694 | 354 | 340 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-missing-fields #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-----------------------------------------------------------------
-- Autogenerated by Thrift
-- --
-- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
-- @generated
-----------------------------------------------------------------
module TestService_Client(init) where
import Data.IORef
import Prelude ( Bool(..), Enum, Float, IO, Double, String, Maybe(..),
Eq, Show, Ord,
concat, error, fromIntegral, fromEnum, length, map,
maybe, not, null, otherwise, return, show, toEnum,
enumFromTo, Bounded, minBound, maxBound, seq,
(.), (&&), (||), (==), (++), ($), (-), (>>=), (>>))
import qualified Control.Applicative as Applicative (ZipList(..))
import Control.Applicative ( (<*>) )
import qualified Control.DeepSeq as DeepSeq
import qualified Control.Exception as Exception
import qualified Control.Monad as Monad ( liftM, ap, when )
import qualified Data.ByteString.Lazy as BS
import Data.Functor ( (<$>) )
import qualified Data.Hashable as Hashable
import qualified Data.Int as Int
import qualified Data.Maybe as Maybe (catMaybes)
import qualified Data.Text.Lazy.Encoding as Encoding ( decodeUtf8, encodeUtf8 )
import qualified Data.Text.Lazy as LT
import qualified Data.Typeable as Typeable ( Typeable )
import qualified Data.HashMap.Strict as Map
import qualified Data.HashSet as Set
import qualified Data.Vector as Vector
import qualified Test.QuickCheck.Arbitrary as Arbitrary ( Arbitrary(..) )
import qualified Test.QuickCheck as QuickCheck ( elements )
import qualified Thrift
import qualified Thrift.Types as Types
import qualified Thrift.Serializable as Serializable
import qualified Thrift.Arbitraries as Arbitraries
import qualified Module_Types
import qualified TestService
seqid = newIORef 0
init (ip,op) arg_int1 arg_int2 arg_int3 arg_int4 arg_int5 arg_int6 arg_int7 arg_int8 arg_int9 arg_int10 arg_int11 arg_int12 arg_int13 arg_int14 arg_int15 arg_int16 = do
send_init op arg_int1 arg_int2 arg_int3 arg_int4 arg_int5 arg_int6 arg_int7 arg_int8 arg_int9 arg_int10 arg_int11 arg_int12 arg_int13 arg_int14 arg_int15 arg_int16
recv_init ip
send_init op arg_int1 arg_int2 arg_int3 arg_int4 arg_int5 arg_int6 arg_int7 arg_int8 arg_int9 arg_int10 arg_int11 arg_int12 arg_int13 arg_int14 arg_int15 arg_int16 = do
seq <- seqid
seqn <- readIORef seq
Thrift.writeMessage op ("init", Types.M_CALL, seqn) $
TestService.write_Init_args op (TestService.Init_args{TestService.init_args_int1=arg_int1,TestService.init_args_int2=arg_int2,TestService.init_args_int3=arg_int3,TestService.init_args_int4=arg_int4,TestService.init_args_int5=arg_int5,TestService.init_args_int6=arg_int6,TestService.init_args_int7=arg_int7,TestService.init_args_int8=arg_int8,TestService.init_args_int9=arg_int9,TestService.init_args_int10=arg_int10,TestService.init_args_int11=arg_int11,TestService.init_args_int12=arg_int12,TestService.init_args_int13=arg_int13,TestService.init_args_int14=arg_int14,TestService.init_args_int15=arg_int15,TestService.init_args_int16=arg_int16})
Thrift.tFlush (Thrift.getTransport op)
recv_init ip =
Thrift.readMessage ip $ \(fname,mtype,rseqid) -> do
Monad.when (mtype == Types.M_EXCEPTION) $ Thrift.readAppExn ip >>= Exception.throw
res <- TestService.read_Init_result ip
return $ TestService.init_result_success res
| Orvid/fbthrift | thrift/compiler/test/fixtures/service-fuzzer/gen-hs/TestService_Client.hs | apache-2.0 | 3,722 | 0 | 14 | 523 | 840 | 525 | 315 | 54 | 1 |
{-# LANGUAGE PackageImports #-}
module Propellor.Property where
import System.Directory
import Control.Monad
import Data.Monoid
import Control.Monad.IfElse
import "mtl" Control.Monad.Reader
import Propellor.Types
import Propellor.Info
import Propellor.Engine
import Utility.Monad
import System.FilePath
-- Constructs a Property.
property :: Desc -> Propellor Result -> Property
property d s = Property d s mempty
-- | Combines a list of properties, resulting in a single property
-- that when run will run each property in the list in turn,
-- and print out the description of each as it's run. Does not stop
-- on failure; does propigate overall success/failure.
propertyList :: Desc -> [Property] -> Property
propertyList desc ps = Property desc (ensureProperties ps) (combineInfos ps)
-- | Combines a list of properties, resulting in one property that
-- ensures each in turn. Does not stop on failure; does propigate
-- overall success/failure.
combineProperties :: Desc -> [Property] -> Property
combineProperties desc ps = Property desc (go ps NoChange) (combineInfos ps)
where
go [] rs = return rs
go (l:ls) rs = do
r <- ensureProperty l
case r of
FailedChange -> return FailedChange
_ -> go ls (r <> rs)
-- | Combines together two properties, resulting in one property
-- that ensures the first, and if the first succeeds, ensures the second.
-- The property uses the description of the first property.
before :: Property -> Property -> Property
p1 `before` p2 = p2 `requires` p1
`describe` (propertyDesc p1)
-- | Makes a perhaps non-idempotent Property be idempotent by using a flag
-- file to indicate whether it has run before.
-- Use with caution.
flagFile :: Property -> FilePath -> Property
flagFile p = flagFile' p . return
flagFile' :: Property -> IO FilePath -> Property
flagFile' p getflagfile = adjustProperty p $ \satisfy -> do
flagfile <- liftIO getflagfile
go satisfy flagfile =<< liftIO (doesFileExist flagfile)
where
go _ _ True = return NoChange
go satisfy flagfile False = do
r <- satisfy
when (r == MadeChange) $ liftIO $
unlessM (doesFileExist flagfile) $ do
createDirectoryIfMissing True (takeDirectory flagfile)
writeFile flagfile ""
return r
--- | Whenever a change has to be made for a Property, causes a hook
-- Property to also be run, but not otherwise.
onChange :: Property -> Property -> Property
p `onChange` hook = Property (propertyDesc p) satisfy (combineInfo p hook)
where
satisfy = do
r <- ensureProperty p
case r of
MadeChange -> do
r' <- ensureProperty hook
return $ r <> r'
_ -> return r
(==>) :: Desc -> Property -> Property
(==>) = flip describe
infixl 1 ==>
-- | Makes a Property only need to do anything when a test succeeds.
check :: IO Bool -> Property -> Property
check c p = adjustProperty p $ \satisfy -> ifM (liftIO c)
( satisfy
, return NoChange
)
-- | Marks a Property as trivial. It can only return FailedChange or
-- NoChange.
--
-- Useful when it's just as expensive to check if a change needs
-- to be made as it is to just idempotently assure the property is
-- satisfied. For example, chmodding a file.
trivial :: Property -> Property
trivial p = adjustProperty p $ \satisfy -> do
r <- satisfy
if r == MadeChange
then return NoChange
else return r
doNothing :: Property
doNothing = property "noop property" noChange
-- | Makes a property that is satisfied differently depending on the host's
-- operating system.
--
-- Note that the operating system may not be declared for some hosts.
withOS :: Desc -> (Maybe System -> Propellor Result) -> Property
withOS desc a = property desc $ a =<< getOS
boolProperty :: Desc -> IO Bool -> Property
boolProperty desc a = property desc $ ifM (liftIO a)
( return MadeChange
, return FailedChange
)
-- | Undoes the effect of a property.
revert :: RevertableProperty -> RevertableProperty
revert (RevertableProperty p1 p2) = RevertableProperty p2 p1
-- | Starts accumulating the properties of a Host.
--
-- > host "example.com"
-- > & someproperty
-- > ! oldproperty
-- > & otherproperty
host :: HostName -> Host
host hn = Host hn [] mempty
-- | Adds a property to a Host
--
-- Can add Properties and RevertableProperties
(&) :: IsProp p => Host -> p -> Host
(Host hn ps as) & p = Host hn (ps ++ [toProp p]) (as <> getInfo p)
infixl 1 &
-- | Adds a property to the Host in reverted form.
(!) :: Host -> RevertableProperty -> Host
h ! p = h & revert p
infixl 1 !
-- Changes the action that is performed to satisfy a property.
adjustProperty :: Property -> (Propellor Result -> Propellor Result) -> Property
adjustProperty p f = p { propertySatisfy = f (propertySatisfy p) }
-- Combines the Info of two properties.
combineInfo :: (IsProp p, IsProp q) => p -> q -> Info
combineInfo p q = getInfo p <> getInfo q
combineInfos :: IsProp p => [p] -> Info
combineInfos = mconcat . map getInfo
makeChange :: IO () -> Propellor Result
makeChange a = liftIO a >> return MadeChange
noChange :: Propellor Result
noChange = return NoChange
| abailly/propellor-test2 | src/Propellor/Property.hs | bsd-2-clause | 5,033 | 17 | 15 | 967 | 1,284 | 664 | 620 | 91 | 3 |
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-}
{-# OPTIONS -Wall #-}
module Main(main) where
import qualified Data.Text.IO as T
import Data.Typeable
import Hydro
import qualified Language.Paraiso.Annotation as Anot
import qualified Language.Paraiso.Annotation.Allocation as Alloc
import Language.Paraiso.Name
import Language.Paraiso.Generator (generateIO)
import qualified Language.Paraiso.Generator.Native as Native
import Language.Paraiso.OM
import Language.Paraiso.OM.Builder
import Language.Paraiso.OM.Builder.Boolean
import Language.Paraiso.OM.DynValue as DVal
import Language.Paraiso.OM.Graph
import Language.Paraiso.OM.PrettyPrint
import Language.Paraiso.OM.Realm
import qualified Language.Paraiso.OM.Reduce as Reduce
import Language.Paraiso.Optimization
import Language.Paraiso.Prelude
import Language.Paraiso.Tensor
import System.Directory (createDirectoryIfMissing)
realDV :: DynValue
realDV = DynValue{DVal.realm = Local, DVal.typeRep = typeOf (0::Real)}
intGDV :: DynValue
intGDV = DynValue{DVal.realm = Global, DVal.typeRep = typeOf (0::Int)}
realGDV :: DynValue
realGDV = DynValue{DVal.realm = Global, DVal.typeRep = typeOf (0::Real)}
-- the list of static variables for this machine
hydroVars :: [Named DynValue]
hydroVars =
[Named (mkName "generation") intGDV] ++
[Named (mkName "time") realGDV] ++
[Named (mkName "cfl") realGDV] ++
foldMap (\name0 -> [Named name0 realGDV]) dRNames ++
foldMap (\name0 -> [Named name0 realGDV]) extentNames ++
[Named (mkName "density") realDV] ++
foldMap (\name0 -> [Named name0 realDV]) velocityNames ++
[Named (mkName "pressure") realDV]
velocityNames :: Dim (Name)
velocityNames = compose (\axis -> mkName $ "velocity" ++ showT (axisIndex axis))
dRNames :: Dim (Name)
dRNames = compose (\axis -> mkName $ "dR" ++ showT (axisIndex axis))
extentNames :: Dim (Name)
extentNames = compose (\axis -> mkName $ "extent" ++ showT (axisIndex axis))
loadReal :: Name -> BR
loadReal = load TLocal (undefined::Real)
loadGReal :: Name -> BGR
loadGReal = load TGlobal (undefined::Real)
----------------------------------------------------------------
-- Hydro Implementations
----------------------------------------------------------------
buildInit :: B ()
buildInit = do
dRG <- mapM (bind . loadGReal) dRNames
extentG <- mapM (bind . loadGReal) extentNames
dR <- mapM (bind . broadcast) dRG
extent <- mapM (bind . broadcast) extentG
icoord <- sequenceA $ compose (\axis -> bind $ loadIndex (0::Real) axis)
coord <- mapM bind $ compose (\i -> dR!i * icoord!i)
let ex = Axis 0
ey = Axis 1
vplus, vminus :: Dim BR
vplus = Vec :~ ( 6) :~ 0
vminus = Vec :~ ( 0) :~ 0
region <- bind $ (coord!ey) `gt` (0.47*extent!ey) && (coord!ey) `lt` (0.53*extent!ey) && (coord!ex) `lt` 0
velo <- sequence $ compose (\i -> bind $ select region (vplus!i) (vminus!i))
factor <- bind $ 1 + 1e-3 * sin (6 * pi * coord ! ex)
store (mkName "density") $ factor * kGamma * (kGamma::BR) * (select region 1 10)
_ <- sequence $ compose(\i -> store (velocityNames!i) $ velo !i)
store (mkName "pressure") $ factor * 0.6
boundaryCondition :: Hydro BR -> B (Hydro BR)
boundaryCondition cell = do
dRG <- mapM (bind . loadGReal) dRNames
extentG <- mapM (bind . loadGReal) extentNames
dR <- mapM (bind . broadcast) dRG
extent <- mapM (bind . broadcast) extentG
icoord <- sequenceA $ compose (\axis -> bind $ loadIndex (0::Real) axis)
isize <- sequenceA $ compose (\axis -> bind $ loadSize TLocal (0::Real) axis)
coord <- mapM bind $ compose (\i -> dR!i * icoord!i)
let ex = Axis 0
ey = Axis 1
vplus, vminus :: Dim BR
vplus = Vec :~ ( 6) :~ 0
vminus = Vec :~ ( 0) :~ 0
region <- bind $ (coord!ey) `gt` (0.47*extent!ey) && (coord!ey) `lt` (0.53*extent!ey) && (coord!ex) `lt` 0
cell0 <- bindPrimitive
(kGamma * (kGamma::BR) * (select region 1 10))
(compose (\i -> select region (vplus!i) (vminus!i)))
(0.6)
outOf <- bind $
(foldl1 (||) $ compose (\i -> icoord !i `lt` 0)) ||
(foldl1 (||) $ compose (\i -> (icoord !i) `ge` (isize !i)))
return $ (\a b -> Anot.add Alloc.Manifest <?> (select outOf a b)) <$> cell0 <*> cell
buildProceed :: B ()
buildProceed = do
dens <- bind $ loadReal $ mkName "density"
velo <- mapM (bind . loadReal) velocityNames
pres <- bind $ loadReal $ mkName "pressure"
timeG <- bind $ loadGReal $ mkName "time"
cflG <- bind $ loadGReal $ mkName "cfl"
dRG <- mapM (bind . loadGReal) dRNames
dR <- mapM (bind . broadcast) dRG
cell0 <- bindPrimitive dens velo pres
cell <- boundaryCondition cell0
let timescale i = dR!i / (soundSpeed cell + abs (velocity cell !i))
dts <- bind $ foldl1 min $ compose timescale
dtG <- bind $ cflG * reduce Reduce.Min dts
dt <- bind $ broadcast dtG
cell2 <- proceedSingle 1 (dt/2) dR cell cell
cell3 <- proceedSingle 2 dt dR cell2 cell
store (mkName "time") $ timeG + dtG
store (mkName "density") $ density cell3
_ <- sequence $ compose(\i -> store (velocityNames!i) $ velocity cell3 !i)
store (mkName "pressure") $ pressure cell3
proceedSingle :: Int -> BR -> Dim BR -> Hydro BR -> Hydro BR -> B (Hydro BR)
proceedSingle order dt dR cellF cellS = do
let calcWall i = do
(lp,rp) <- interpolate order i cellF
hllc i lp rp
wall <- sequence $ compose calcWall
cellN <- foldl1 (.) (compose (\i -> (>>= addFlux dt dR wall i))) $ return cellS
bindPrimitive
(max 1e-2 $ density cellN)
(velocity cellN)
(max 1e-2 $ pressure cellN)
-- cx <- addFlux dt dR wall (Axis 0) cellS
-- addFlux dt dR wall (Axis 1) cx
addFlux :: BR -> Dim BR -> Dim (Hydro BR) -> Axis Dim -> Hydro BR -> B (Hydro BR)
addFlux dt dR wall ex cell = do
dtdx <- bind $ dt / dR!ex
leftWall <- mapM bind $ wall ! ex
rightWall <- mapM (bind . shift (negate $ unitVector ex)) $ wall!ex
dens1 <- bind $ density cell + dtdx * (densityFlux leftWall - densityFlux rightWall)!ex
mome1 <- sequence $ compose
(\j -> bind $ (momentum cell !j + dtdx *
(momentumFlux leftWall - momentumFlux rightWall) !j!ex))
enrg1 <- bind $ energy cell + dtdx * (energyFlux leftWall - energyFlux rightWall) !ex
bindConserved dens1 mome1 enrg1
interpolate :: Int -> Axis Dim -> Hydro BR -> B (Hydro BR, Hydro BR)
interpolate order i cell = do
let shifti n = shift $ compose (\j -> if i==j then n else 0)
a0 <- mapM (bind . shifti ( 2)) cell
a1 <- mapM (bind . shifti ( 1)) cell
a2 <- mapM (bind . shifti ( 0)) cell
a3 <- mapM (bind . shifti (-1)) cell
intp <- sequence $ interpolateSingle order <$> a0 <*> a1 <*> a2 <*> a3
let (l,r) = (fmap fst intp , fmap snd intp)
bp :: Hydro BR -> B (Hydro BR)
bp x = do
dens1 <- bind $ density x
velo1 <- mapM bind $ velocity x
pres1 <- bind $ pressure x
bindPrimitive dens1 velo1 pres1
lp <- bp l
rp <- bp r
return (lp,rp)
interpolateSingle :: Int -> BR -> BR -> BR -> BR -> B (BR,BR)
interpolateSingle order x0 x1 x2 x3 =
if order == 1
then do
return (x1, x2)
else if order == 2
then do
d01 <- bind $ x1-x0
d12 <- bind $ x2-x1
d23 <- bind $ x3-x2
let absmaller a b = select ((a*b) `le` 0) 0 $ select (abs a `lt` abs b) a b
d1 <- bind $ absmaller d01 d12
d2 <- bind $ absmaller d12 d23
l <- bind $ x1 + d1/2
r <- bind $ x2 - d2/2
return (l, r)
else error $ show order ++ "th order spatial interpolation is not yet implemented"
hllc :: Axis Dim -> Hydro BR -> Hydro BR -> B (Hydro BR)
hllc i left right = do
densMid <- bind $ (density left + density right ) / 2
soundMid <- bind $ (soundSpeed left + soundSpeed right) / 2
let
speedLeft = velocity left !i
speedRight = velocity right !i
presStar <- bind $ max 0 $ (pressure left + pressure right ) / 2 -
densMid * soundMid * (speedRight - speedLeft)
shockLeft <- bind $ velocity left !i -
soundSpeed left * hllcQ presStar (pressure left)
shockRight <- bind $ velocity right !i +
soundSpeed right * hllcQ presStar (pressure right)
shockStar <- bind $ (pressure right - pressure left
+ density left * speedLeft * (shockLeft - speedLeft)
- density right * speedRight * (shockRight - speedRight) )
/ (density left * (shockLeft - speedLeft ) -
density right * (shockRight - speedRight) )
lesta <- starState shockStar shockLeft left
rista <- starState shockStar shockRight right
let selector a b c d =
select (0 `lt` shockLeft) a $
select (0 `lt` shockStar) b $
select (0 `lt` shockRight) c d
mapM bind $ selector <$> left <*> lesta <*> rista <*> right
where
hllcQ sp p = select (p `le` sp) 1 $
sqrt(1 + (kGamma + 1)/(2*kGamma) * (sp / p - 1))
starState starShock shock x = do
let speed = velocity x !i
dens <- bind $ density x * (shock - speed) / (shock - starShock)
mome <- sequence $ compose
(\j -> bind $ dens * if i==j then starShock
else velocity x !j)
enrg <- bind $ dens *
(energy x / density x +
(starShock - speed) *
(starShock + pressure x/density x/(shock - speed)))
bindConserved dens mome enrg
-- compose the machine.
myOM :: OM Dim Int Anot.Annotation
myOM = optimize O3 $
makeOM (mkName "Hydro") [] hydroVars
[(mkName "init" , buildInit),
(mkName "proceed", buildProceed)]
cpuSetup :: Native.Setup Vec2 Int
cpuSetup =
(Native.defaultSetup $ Vec :~ 1024 :~ 1024)
{ Native.directory = "./dist/"
}
gpuSetup :: Native.Setup Vec2 Int
gpuSetup =
(Native.defaultSetup $ Vec :~ 1024 :~ 1024)
{ Native.directory = "./dist-cuda/" ,
Native.language = Native.CUDA
}
main :: IO ()
main = do
createDirectoryIfMissing True "output"
-- output the intermediate state.
T.writeFile "output/OM.txt" $ prettyPrintA1 $ myOM
-- generate the cpu library
_ <- generateIO cpuSetup myOM
-- generate the gpu library
_ <- generateIO gpuSetup myOM
return ()
| nushio3/Paraiso | examples-old/Hydro-exampled/HydroMain.hs | bsd-3-clause | 10,530 | 0 | 19 | 2,826 | 4,280 | 2,164 | 2,116 | 228 | 3 |
{-# LANGUAGE ScopedTypeVariables, PatternGuards, ViewPatterns #-}
{-
Copyright (C) 2012-2015 John MacFarlane <jgm@berkeley.edu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.Writers.Docx
Copyright : Copyright (C) 2012-2015 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley.edu>
Stability : alpha
Portability : portable
Conversion of 'Pandoc' documents to docx.
-}
module Text.Pandoc.Writers.Docx ( writeDocx ) where
import Data.List ( intercalate, isPrefixOf, isSuffixOf )
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Char8 as BL8
import qualified Data.Map as M
import qualified Data.Set as Set
import qualified Text.Pandoc.UTF8 as UTF8
import Codec.Archive.Zip
import Data.Time.Clock.POSIX
import Data.Time.Clock
import System.Environment
import Text.Pandoc.Compat.Time
import Text.Pandoc.Definition
import Text.Pandoc.Generic
import Text.Pandoc.ImageSize
import Text.Pandoc.Shared hiding (Element)
import Text.Pandoc.Writers.Shared (fixDisplayMath)
import Text.Pandoc.Options
import Text.Pandoc.Readers.TeXMath
import Text.Pandoc.Highlighting ( highlight )
import Text.Pandoc.Walk
import Text.Highlighting.Kate.Types ()
import Text.XML.Light as XML
import Text.TeXMath
import Text.Pandoc.Readers.Docx.StyleMap
import Text.Pandoc.Readers.Docx.Util (elemName)
import Control.Monad.State
import Text.Highlighting.Kate
import Data.Unique (hashUnique, newUnique)
import System.Random (randomRIO)
import Text.Printf (printf)
import qualified Control.Exception as E
import Text.Pandoc.Compat.Monoid ((<>))
import Text.Pandoc.MIME (MimeType, getMimeType, getMimeTypeDef,
extensionFromMimeType)
import Control.Applicative ((<|>))
import Data.Maybe (fromMaybe, mapMaybe, maybeToList)
import Data.Char (ord)
data ListMarker = NoMarker
| BulletMarker
| NumberMarker ListNumberStyle ListNumberDelim Int
deriving (Show, Read, Eq, Ord)
listMarkerToId :: ListMarker -> String
listMarkerToId NoMarker = "990"
listMarkerToId BulletMarker = "991"
listMarkerToId (NumberMarker sty delim n) =
'9' : '9' : styNum : delimNum : show n
where styNum = case sty of
DefaultStyle -> '2'
Example -> '3'
Decimal -> '4'
LowerRoman -> '5'
UpperRoman -> '6'
LowerAlpha -> '7'
UpperAlpha -> '8'
delimNum = case delim of
DefaultDelim -> '0'
Period -> '1'
OneParen -> '2'
TwoParens -> '3'
data WriterState = WriterState{
stTextProperties :: [Element]
, stParaProperties :: [Element]
, stFootnotes :: [Element]
, stSectionIds :: Set.Set String
, stExternalLinks :: M.Map String String
, stImages :: M.Map FilePath (String, String, Maybe MimeType, Element, B.ByteString)
, stListLevel :: Int
, stListNumId :: Int
, stLists :: [ListMarker]
, stInsId :: Int
, stDelId :: Int
, stInDel :: Bool
, stChangesAuthor :: String
, stChangesDate :: String
, stPrintWidth :: Integer
, stStyleMaps :: StyleMaps
, stFirstPara :: Bool
, stTocTitle :: [Inline]
}
defaultWriterState :: WriterState
defaultWriterState = WriterState{
stTextProperties = []
, stParaProperties = []
, stFootnotes = defaultFootnotes
, stSectionIds = Set.empty
, stExternalLinks = M.empty
, stImages = M.empty
, stListLevel = -1
, stListNumId = 1
, stLists = [NoMarker]
, stInsId = 1
, stDelId = 1
, stInDel = False
, stChangesAuthor = "unknown"
, stChangesDate = "1969-12-31T19:00:00Z"
, stPrintWidth = 1
, stStyleMaps = defaultStyleMaps
, stFirstPara = False
, stTocTitle = normalizeInlines [Str "Table of Contents"]
}
type WS a = StateT WriterState IO a
mknode :: Node t => String -> [(String,String)] -> t -> Element
mknode s attrs =
add_attrs (map (\(k,v) -> Attr (nodename k) v) attrs) . node (nodename s)
nodename :: String -> QName
nodename s = QName{ qName = name, qURI = Nothing, qPrefix = prefix }
where (name, prefix) = case break (==':') s of
(xs,[]) -> (xs, Nothing)
(ys, _:zs) -> (zs, Just ys)
toLazy :: B.ByteString -> BL.ByteString
toLazy = BL.fromChunks . (:[])
renderXml :: Element -> BL.ByteString
renderXml elt = BL8.pack "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" <>
UTF8.fromStringLazy (showElement elt)
renumIdMap :: Int -> [Element] -> M.Map String String
renumIdMap _ [] = M.empty
renumIdMap n (e:es)
| Just oldId <- findAttr (QName "Id" Nothing Nothing) e =
M.insert oldId ("rId" ++ (show n)) (renumIdMap (n+1) es)
| otherwise = renumIdMap n es
replaceAttr :: (QName -> Bool) -> String -> [XML.Attr] -> [XML.Attr]
replaceAttr _ _ [] = []
replaceAttr f val (a:as) | f (attrKey a) =
(XML.Attr (attrKey a) val) : (replaceAttr f val as)
| otherwise = a : (replaceAttr f val as)
renumId :: (QName -> Bool) -> (M.Map String String) -> Element -> Element
renumId f renumMap e
| Just oldId <- findAttrBy f e
, Just newId <- M.lookup oldId renumMap =
let attrs' = replaceAttr f newId (elAttribs e)
in
e { elAttribs = attrs' }
| otherwise = e
renumIds :: (QName -> Bool) -> (M.Map String String) -> [Element] -> [Element]
renumIds f renumMap = map (renumId f renumMap)
-- | Certain characters are invalid in XML even if escaped.
-- See #1992
stripInvalidChars :: String -> String
stripInvalidChars = filter isValidChar
-- | See XML reference
isValidChar :: Char -> Bool
isValidChar (ord -> c)
| c == 0x9 = True
| c == 0xA = True
| c == 0xD = True
| 0x20 <= c && c <= 0xD7FF = True
| 0xE000 <= c && c <= 0xFFFD = True
| 0x10000 <= c && c <= 0x10FFFF = True
| otherwise = False
metaValueToInlines :: MetaValue -> [Inline]
metaValueToInlines (MetaString s) = normalizeInlines [Str s]
metaValueToInlines (MetaInlines ils) = ils
metaValueToInlines (MetaBlocks bs) = query return bs
metaValueToInlines (MetaBool b) = [Str $ show b]
metaValueToInlines _ = []
-- | Produce an Docx file from a Pandoc document.
writeDocx :: WriterOptions -- ^ Writer options
-> Pandoc -- ^ Document to convert
-> IO BL.ByteString
writeDocx opts doc@(Pandoc meta _) = do
let datadir = writerUserDataDir opts
let doc' = walk fixDisplayMath $ doc
username <- lookup "USERNAME" <$> getEnvironment
utctime <- getCurrentTime
distArchive <- getDefaultReferenceDocx datadir
refArchive <- case writerReferenceDocx opts of
Just f -> liftM (toArchive . toLazy) $ B.readFile f
Nothing -> getDefaultReferenceDocx datadir
parsedDoc <- parseXml refArchive distArchive "word/document.xml"
let wname f qn = qPrefix qn == Just "w" && f (qName qn)
let mbsectpr = filterElementName (wname (=="sectPr")) parsedDoc
-- Gets the template size
let mbpgsz = mbsectpr >>= (filterElementName (wname (=="pgSz")))
let mbAttrSzWidth = (elAttribs <$> mbpgsz) >>= (lookupAttrBy ((=="w") . qName))
let mbpgmar = mbsectpr >>= (filterElementName (wname (=="pgMar")))
let mbAttrMarLeft = (elAttribs <$> mbpgmar) >>= (lookupAttrBy ((=="left") . qName))
let mbAttrMarRight = (elAttribs <$> mbpgmar) >>= (lookupAttrBy ((=="right") . qName))
-- Get the avaible area (converting the size and the margins to int and
-- doing the difference
let pgContentWidth = (-) <$> (read <$> mbAttrSzWidth ::Maybe Integer)
<*> (
(+) <$> (read <$> mbAttrMarRight ::Maybe Integer)
<*> (read <$> mbAttrMarLeft ::Maybe Integer)
)
-- styles
let stylepath = "word/styles.xml"
styledoc <- parseXml refArchive distArchive stylepath
-- parse styledoc for heading styles
let styleMaps = getStyleMaps styledoc
let tocTitle = fromMaybe (stTocTitle defaultWriterState) $
metaValueToInlines <$> lookupMeta "toc-title" meta
((contents, footnotes), st) <- runStateT (writeOpenXML opts{writerWrapText = WrapNone} doc')
defaultWriterState{ stChangesAuthor = fromMaybe "unknown" username
, stChangesDate = formatTime defaultTimeLocale "%FT%XZ" utctime
, stPrintWidth = (maybe 420 (\x -> quot x 20) pgContentWidth)
, stStyleMaps = styleMaps
, stTocTitle = tocTitle
}
let epochtime = floor $ utcTimeToPOSIXSeconds utctime
let imgs = M.elems $ stImages st
-- create entries for images in word/media/...
let toImageEntry (_,path,_,_,img) = toEntry ("word/" ++ path) epochtime $ toLazy img
let imageEntries = map toImageEntry imgs
let stdAttributes =
[("xmlns:w","http://schemas.openxmlformats.org/wordprocessingml/2006/main")
,("xmlns:m","http://schemas.openxmlformats.org/officeDocument/2006/math")
,("xmlns:r","http://schemas.openxmlformats.org/officeDocument/2006/relationships")
,("xmlns:o","urn:schemas-microsoft-com:office:office")
,("xmlns:v","urn:schemas-microsoft-com:vml")
,("xmlns:w10","urn:schemas-microsoft-com:office:word")
,("xmlns:a","http://schemas.openxmlformats.org/drawingml/2006/main")
,("xmlns:pic","http://schemas.openxmlformats.org/drawingml/2006/picture")
,("xmlns:wp","http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing")]
parsedRels <- parseXml refArchive distArchive "word/_rels/document.xml.rels"
let isHeaderNode e = findAttr (QName "Type" Nothing Nothing) e == Just "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header"
let isFooterNode e = findAttr (QName "Type" Nothing Nothing) e == Just "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer"
let headers = filterElements isHeaderNode parsedRels
let footers = filterElements isFooterNode parsedRels
let extractTarget = findAttr (QName "Target" Nothing Nothing)
-- we create [Content_Types].xml and word/_rels/document.xml.rels
-- from scratch rather than reading from reference.docx,
-- because Word sometimes changes these files when a reference.docx is modified,
-- e.g. deleting the reference to footnotes.xml or removing default entries
-- for image content types.
-- [Content_Types].xml
let mkOverrideNode (part', contentType') = mknode "Override"
[("PartName",part'),("ContentType",contentType')] ()
let mkImageOverride (_, imgpath, mbMimeType, _, _) =
mkOverrideNode ("/word/" ++ imgpath,
fromMaybe "application/octet-stream" mbMimeType)
let mkMediaOverride imgpath =
mkOverrideNode ('/':imgpath, getMimeTypeDef imgpath)
let overrides = map mkOverrideNode (
[("/word/webSettings.xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml")
,("/word/numbering.xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml")
,("/word/settings.xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml")
,("/word/theme/theme1.xml",
"application/vnd.openxmlformats-officedocument.theme+xml")
,("/word/fontTable.xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml")
,("/docProps/app.xml",
"application/vnd.openxmlformats-officedocument.extended-properties+xml")
,("/docProps/core.xml",
"application/vnd.openxmlformats-package.core-properties+xml")
,("/word/styles.xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml")
,("/word/document.xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml")
,("/word/footnotes.xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml")
] ++
map (\x -> (maybe "" ("/word/" ++) $ extractTarget x,
"application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml")) headers ++
map (\x -> (maybe "" ("/word/" ++) $ extractTarget x,
"application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml")) footers) ++
map mkImageOverride imgs ++
map mkMediaOverride [ eRelativePath e | e <- zEntries refArchive
, "word/media/" `isPrefixOf` eRelativePath e ]
let defaultnodes = [mknode "Default"
[("Extension","xml"),("ContentType","application/xml")] (),
mknode "Default"
[("Extension","rels"),("ContentType","application/vnd.openxmlformats-package.relationships+xml")] ()]
let contentTypesDoc = mknode "Types" [("xmlns","http://schemas.openxmlformats.org/package/2006/content-types")] $ defaultnodes ++ overrides
let contentTypesEntry = toEntry "[Content_Types].xml" epochtime
$ renderXml contentTypesDoc
-- word/_rels/document.xml.rels
let toBaseRel (url', id', target') = mknode "Relationship"
[("Type",url')
,("Id",id')
,("Target",target')] ()
let baserels' = map toBaseRel
[("http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering",
"rId1",
"numbering.xml")
,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",
"rId2",
"styles.xml")
,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings",
"rId3",
"settings.xml")
,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings",
"rId4",
"webSettings.xml")
,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable",
"rId5",
"fontTable.xml")
,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",
"rId6",
"theme/theme1.xml")
,("http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes",
"rId7",
"footnotes.xml")
]
let idMap = renumIdMap (length baserels' + 1) (headers ++ footers)
let renumHeaders = renumIds (\q -> qName q == "Id") idMap headers
let renumFooters = renumIds (\q -> qName q == "Id") idMap footers
let baserels = baserels' ++ renumHeaders ++ renumFooters
let toImgRel (ident,path,_,_,_) = mknode "Relationship" [("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"),("Id",ident),("Target",path)] ()
let imgrels = map toImgRel imgs
let toLinkRel (src,ident) = mknode "Relationship" [("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"),("Id",ident),("Target",src),("TargetMode","External") ] ()
let linkrels = map toLinkRel $ M.toList $ stExternalLinks st
let reldoc = mknode "Relationships" [("xmlns","http://schemas.openxmlformats.org/package/2006/relationships")] $ baserels ++ imgrels ++ linkrels
let relEntry = toEntry "word/_rels/document.xml.rels" epochtime
$ renderXml reldoc
-- adjust contents to add sectPr from reference.docx
let sectpr = case mbsectpr of
Just sectpr' -> let cs = renumIds
(\q -> qName q == "id" && qPrefix q == Just "r")
idMap
(elChildren sectpr')
in
add_attrs (elAttribs sectpr') $ mknode "w:sectPr" [] cs
Nothing -> (mknode "w:sectPr" [] ())
-- let sectpr = fromMaybe (mknode "w:sectPr" [] ()) mbsectpr'
let contents' = contents ++ [sectpr]
let docContents = mknode "w:document" stdAttributes
$ mknode "w:body" [] contents'
-- word/document.xml
let contentEntry = toEntry "word/document.xml" epochtime
$ renderXml docContents
-- footnotes
let notes = mknode "w:footnotes" stdAttributes footnotes
let footnotesEntry = toEntry "word/footnotes.xml" epochtime $ renderXml notes
-- footnote rels
let footnoteRelEntry = toEntry "word/_rels/footnotes.xml.rels" epochtime
$ renderXml $ mknode "Relationships" [("xmlns","http://schemas.openxmlformats.org/package/2006/relationships")]
linkrels
-- styles
let newstyles = styleToOpenXml styleMaps $ writerHighlightStyle opts
let styledoc' = styledoc{ elContent = modifyContent (elContent styledoc) }
where
modifyContent
| writerHighlight opts = (++ map Elem newstyles)
| otherwise = filter notTokStyle
notTokStyle (Elem el) = notStyle el || notTokId el
notTokStyle _ = True
notStyle = (/= elemName' "style") . elName
notTokId = maybe True (`notElem` tokStys) . findAttr (elemName' "styleId")
tokStys = "SourceCode" : map show (enumFromTo KeywordTok NormalTok)
elemName' = elemName (sNameSpaces styleMaps) "w"
let styleEntry = toEntry stylepath epochtime $ renderXml styledoc'
-- construct word/numbering.xml
let numpath = "word/numbering.xml"
numbering <- parseXml refArchive distArchive numpath
newNumElts <- mkNumbering (stLists st)
let allElts = onlyElems (elContent numbering) ++ newNumElts
let numEntry = toEntry numpath epochtime $ renderXml numbering{ elContent =
-- we want all the abstractNums first, then the nums,
-- otherwise things break:
[Elem e | e <- allElts
, qName (elName e) == "abstractNum" ] ++
[Elem e | e <- allElts
, qName (elName e) == "num" ] }
let docPropsPath = "docProps/core.xml"
let docProps = mknode "cp:coreProperties"
[("xmlns:cp","http://schemas.openxmlformats.org/package/2006/metadata/core-properties")
,("xmlns:dc","http://purl.org/dc/elements/1.1/")
,("xmlns:dcterms","http://purl.org/dc/terms/")
,("xmlns:dcmitype","http://purl.org/dc/dcmitype/")
,("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance")]
$ mknode "dc:title" [] (stringify $ docTitle meta)
: mknode "dc:creator" [] (intercalate "; " (map stringify $ docAuthors meta))
: maybe []
(\x -> [ mknode "dcterms:created" [("xsi:type","dcterms:W3CDTF")] x
, mknode "dcterms:modified" [("xsi:type","dcterms:W3CDTF")] x
]) (normalizeDate $ stringify $ docDate meta)
let docPropsEntry = toEntry docPropsPath epochtime $ renderXml docProps
let relsPath = "_rels/.rels"
let rels = mknode "Relationships" [("xmlns", "http://schemas.openxmlformats.org/package/2006/relationships")]
$ map (\attrs -> mknode "Relationship" attrs ())
[ [("Id","rId1")
,("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument")
,("Target","word/document.xml")]
, [("Id","rId4")
,("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties")
,("Target","docProps/app.xml")]
, [("Id","rId3")
,("Type","http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties")
,("Target","docProps/core.xml")]
]
let relsEntry = toEntry relsPath epochtime $ renderXml rels
-- we use dist archive for settings.xml, because Word sometimes
-- adds references to footnotes or endnotes we don't have...
-- we do, however, copy some settings over from reference
let settingsPath = "word/settings.xml"
settingsList = [ "w:autoHyphenation"
, "w:consecutiveHyphenLimit"
, "w:hyphenationZone"
, "w:doNotHyphenateCap"
]
settingsEntry <- copyChildren refArchive distArchive settingsPath epochtime settingsList
let entryFromArchive arch path =
maybe (fail $ path ++ " missing in reference docx")
return
(findEntryByPath path arch `mplus` findEntryByPath path distArchive)
docPropsAppEntry <- entryFromArchive refArchive "docProps/app.xml"
themeEntry <- entryFromArchive refArchive "word/theme/theme1.xml"
fontTableEntry <- entryFromArchive refArchive "word/fontTable.xml"
webSettingsEntry <- entryFromArchive refArchive "word/webSettings.xml"
headerFooterEntries <- mapM (entryFromArchive refArchive) $
mapMaybe (fmap ("word/" ++) . extractTarget)
(headers ++ footers)
let miscRelEntries = [ e | e <- zEntries refArchive
, "word/_rels/" `isPrefixOf` (eRelativePath e)
, ".xml.rels" `isSuffixOf` (eRelativePath e)
, eRelativePath e /= "word/_rels/document.xml.rels"
, eRelativePath e /= "word/_rels/footnotes.xml.rels" ]
let otherMediaEntries = [ e | e <- zEntries refArchive
, "word/media/" `isPrefixOf` eRelativePath e ]
-- Create archive
let archive = foldr addEntryToArchive emptyArchive $
contentTypesEntry : relsEntry : contentEntry : relEntry :
footnoteRelEntry : numEntry : styleEntry : footnotesEntry :
docPropsEntry : docPropsAppEntry : themeEntry :
fontTableEntry : settingsEntry : webSettingsEntry :
imageEntries ++ headerFooterEntries ++
miscRelEntries ++ otherMediaEntries
return $ fromArchive archive
styleToOpenXml :: StyleMaps -> Style -> [Element]
styleToOpenXml sm style =
maybeToList parStyle ++ mapMaybe toStyle alltoktypes
where alltoktypes = enumFromTo KeywordTok NormalTok
toStyle toktype | hasStyleName (show toktype) (sCharStyleMap sm) = Nothing
| otherwise = Just $
mknode "w:style" [("w:type","character"),
("w:customStyle","1"),("w:styleId",show toktype)]
[ mknode "w:name" [("w:val",show toktype)] ()
, mknode "w:basedOn" [("w:val","VerbatimChar")] ()
, mknode "w:rPr" [] $
[ mknode "w:color" [("w:val",tokCol toktype)] ()
| tokCol toktype /= "auto" ] ++
[ mknode "w:shd" [("w:val","clear"),("w:fill",tokBg toktype)] ()
| tokBg toktype /= "auto" ] ++
[ mknode "w:b" [] () | tokFeature tokenBold toktype ] ++
[ mknode "w:i" [] () | tokFeature tokenItalic toktype ] ++
[ mknode "w:u" [] () | tokFeature tokenUnderline toktype ]
]
tokStyles = tokenStyles style
tokFeature f toktype = maybe False f $ lookup toktype tokStyles
tokCol toktype = maybe "auto" (drop 1 . fromColor)
$ (tokenColor =<< lookup toktype tokStyles)
`mplus` defaultColor style
tokBg toktype = maybe "auto" (drop 1 . fromColor)
$ (tokenBackground =<< lookup toktype tokStyles)
`mplus` backgroundColor style
parStyle | hasStyleName "Source Code" (sParaStyleMap sm) = Nothing
| otherwise = Just $
mknode "w:style" [("w:type","paragraph"),
("w:customStyle","1"),("w:styleId","SourceCode")]
[ mknode "w:name" [("w:val","Source Code")] ()
, mknode "w:basedOn" [("w:val","Normal")] ()
, mknode "w:link" [("w:val","VerbatimChar")] ()
, mknode "w:pPr" []
$ mknode "w:wordWrap" [("w:val","off")] ()
: ( maybe [] (\col -> [mknode "w:shd" [("w:val","clear"),("w:fill",drop 1 $ fromColor col)] ()])
$ backgroundColor style )
]
copyChildren :: Archive -> Archive -> String -> Integer -> [String] -> IO Entry
copyChildren refArchive distArchive path timestamp elNames = do
ref <- parseXml refArchive distArchive path
dist <- parseXml distArchive distArchive path
return $ toEntry path timestamp $ renderXml dist{
elContent = elContent dist ++ copyContent ref
}
where
strName QName{qName=name, qPrefix=prefix}
| Just p <- prefix = p++":"++name
| otherwise = name
shouldCopy = (`elem` elNames) . strName
cleanElem el@Element{elName=name} = Elem el{elName=name{qURI=Nothing}}
copyContent = map cleanElem . filterChildrenName shouldCopy
-- this is the lowest number used for a list numId
baseListId :: Int
baseListId = 1000
mkNumbering :: [ListMarker] -> IO [Element]
mkNumbering lists = do
elts <- mapM mkAbstractNum (ordNub lists)
return $ elts ++ zipWith mkNum lists [baseListId..(baseListId + length lists - 1)]
mkNum :: ListMarker -> Int -> Element
mkNum marker numid =
mknode "w:num" [("w:numId",show numid)]
$ mknode "w:abstractNumId" [("w:val",listMarkerToId marker)] ()
: case marker of
NoMarker -> []
BulletMarker -> []
NumberMarker _ _ start ->
map (\lvl -> mknode "w:lvlOverride" [("w:ilvl",show (lvl :: Int))]
$ mknode "w:startOverride" [("w:val",show start)] ()) [0..6]
mkAbstractNum :: ListMarker -> IO Element
mkAbstractNum marker = do
nsid <- randomRIO (0x10000000 :: Integer, 0xFFFFFFFF :: Integer)
return $ mknode "w:abstractNum" [("w:abstractNumId",listMarkerToId marker)]
$ mknode "w:nsid" [("w:val", printf "%8x" nsid)] ()
: mknode "w:multiLevelType" [("w:val","multilevel")] ()
: map (mkLvl marker) [0..6]
mkLvl :: ListMarker -> Int -> Element
mkLvl marker lvl =
mknode "w:lvl" [("w:ilvl",show lvl)] $
[ mknode "w:start" [("w:val",start)] ()
| marker /= NoMarker && marker /= BulletMarker ] ++
[ mknode "w:numFmt" [("w:val",fmt)] ()
, mknode "w:lvlText" [("w:val",lvltxt)] ()
, mknode "w:lvlJc" [("w:val","left")] ()
, mknode "w:pPr" []
[ mknode "w:tabs" []
$ mknode "w:tab" [("w:val","num"),("w:pos",show $ lvl * step)] ()
, mknode "w:ind" [("w:left",show $ lvl * step + hang),("w:hanging",show hang)] ()
]
]
where (fmt, lvltxt, start) =
case marker of
NoMarker -> ("bullet"," ","1")
BulletMarker -> ("bullet",bulletFor lvl,"1")
NumberMarker st de n -> (styleFor st lvl
,patternFor de ("%" ++ show (lvl + 1))
,show n)
step = 720
hang = 480
bulletFor 0 = "\x2022" -- filled circle
bulletFor 1 = "\x2013" -- en dash
bulletFor 2 = "\x2022" -- hyphen bullet
bulletFor 3 = "\x2013"
bulletFor 4 = "\x2022"
bulletFor 5 = "\x2013"
bulletFor _ = "\x2022"
styleFor UpperAlpha _ = "upperLetter"
styleFor LowerAlpha _ = "lowerLetter"
styleFor UpperRoman _ = "upperRoman"
styleFor LowerRoman _ = "lowerRoman"
styleFor Decimal _ = "decimal"
styleFor DefaultStyle 1 = "decimal"
styleFor DefaultStyle 2 = "lowerLetter"
styleFor DefaultStyle 3 = "lowerRoman"
styleFor DefaultStyle 4 = "decimal"
styleFor DefaultStyle 5 = "lowerLetter"
styleFor DefaultStyle 6 = "lowerRoman"
styleFor _ _ = "decimal"
patternFor OneParen s = s ++ ")"
patternFor TwoParens s = "(" ++ s ++ ")"
patternFor _ s = s ++ "."
getNumId :: WS Int
getNumId = (((baseListId - 1) +) . length) `fmap` gets stLists
makeTOC :: WriterOptions -> WS [Element]
makeTOC opts | writerTableOfContents opts = do
let depth = "1-"++(show (writerTOCDepth opts))
let tocCmd = "TOC \\o \""++depth++"\" \\h \\z \\u"
tocTitle <- gets stTocTitle
title <- withParaPropM (pStyleM "TOC Heading") (blocksToOpenXML opts [Para tocTitle])
return $
[mknode "w:sdt" [] ([
mknode "w:sdtPr" [] (
mknode "w:docPartObj" [] (
[mknode "w:docPartGallery" [("w:val","Table of Contents")] (),
mknode "w:docPartUnique" [] ()]
) -- w:docPartObj
), -- w:sdtPr
mknode "w:sdtContent" [] (title++[
mknode "w:p" [] (
mknode "w:r" [] ([
mknode "w:fldChar" [("w:fldCharType","begin"),("w:dirty","true")] (),
mknode "w:instrText" [("xml:space","preserve")] tocCmd,
mknode "w:fldChar" [("w:fldCharType","separate")] (),
mknode "w:fldChar" [("w:fldCharType","end")] ()
]) -- w:r
) -- w:p
])
])] -- w:sdt
makeTOC _ = return []
-- | Convert Pandoc document to two lists of
-- OpenXML elements (the main document and footnotes).
writeOpenXML :: WriterOptions -> Pandoc -> WS ([Element], [Element])
writeOpenXML opts (Pandoc meta blocks) = do
let tit = docTitle meta ++ case lookupMeta "subtitle" meta of
Just (MetaBlocks [Plain xs]) -> LineBreak : xs
_ -> []
let auths = docAuthors meta
let dat = docDate meta
let abstract' = case lookupMeta "abstract" meta of
Just (MetaBlocks bs) -> bs
Just (MetaInlines ils) -> [Plain ils]
_ -> []
let subtitle' = case lookupMeta "subtitle" meta of
Just (MetaBlocks [Plain xs]) -> xs
Just (MetaBlocks [Para xs]) -> xs
Just (MetaInlines xs) -> xs
_ -> []
title <- withParaPropM (pStyleM "Title") $ blocksToOpenXML opts [Para tit | not (null tit)]
subtitle <- withParaPropM (pStyleM "Subtitle") $ blocksToOpenXML opts [Para subtitle' | not (null subtitle')]
authors <- withParaProp (pCustomStyle "Author") $ blocksToOpenXML opts $
map Para auths
date <- withParaPropM (pStyleM "Date") $ blocksToOpenXML opts [Para dat | not (null dat)]
abstract <- if null abstract'
then return []
else withParaProp (pCustomStyle "Abstract") $ blocksToOpenXML opts abstract'
let convertSpace (Str x : Space : Str y : xs) = Str (x ++ " " ++ y) : xs
convertSpace (Str x : Str y : xs) = Str (x ++ y) : xs
convertSpace xs = xs
let blocks' = bottomUp convertSpace blocks
doc' <- (setFirstPara >> blocksToOpenXML opts blocks')
notes' <- reverse `fmap` gets stFootnotes
toc <- makeTOC opts
let meta' = title ++ subtitle ++ authors ++ date ++ abstract ++ toc
return (meta' ++ doc', notes')
-- | Convert a list of Pandoc blocks to OpenXML.
blocksToOpenXML :: WriterOptions -> [Block] -> WS [Element]
blocksToOpenXML opts bls = concat `fmap` mapM (blockToOpenXML opts) bls
pCustomStyle :: String -> Element
pCustomStyle sty = mknode "w:pStyle" [("w:val",sty)] ()
pStyleM :: String -> WS XML.Element
pStyleM styleName = do
styleMaps <- gets stStyleMaps
let sty' = getStyleId styleName $ sParaStyleMap styleMaps
return $ mknode "w:pStyle" [("w:val",sty')] ()
rCustomStyle :: String -> Element
rCustomStyle sty = mknode "w:rStyle" [("w:val",sty)] ()
rStyleM :: String -> WS XML.Element
rStyleM styleName = do
styleMaps <- gets stStyleMaps
let sty' = getStyleId styleName $ sCharStyleMap styleMaps
return $ mknode "w:rStyle" [("w:val",sty')] ()
getUniqueId :: MonadIO m => m String
-- the + 20 is to ensure that there are no clashes with the rIds
-- already in word/document.xml.rel
getUniqueId = liftIO $ (show . (+ 20) . hashUnique) `fmap` newUnique
-- | Convert a Pandoc block element to OpenXML.
blockToOpenXML :: WriterOptions -> Block -> WS [Element]
blockToOpenXML _ Null = return []
blockToOpenXML opts (Div (_,["references"],_) bs) = do
let (hs, bs') = span isHeaderBlock bs
header <- blocksToOpenXML opts hs
-- We put the Bibliography style on paragraphs after the header
rest <- withParaPropM (pStyleM "Bibliography") $ blocksToOpenXML opts bs'
return (header ++ rest)
blockToOpenXML opts (Div _ bs) = blocksToOpenXML opts bs
blockToOpenXML opts (Header lev (ident,_,_) lst) = do
setFirstPara
paraProps <- withParaPropM (pStyleM ("Heading "++show lev)) $
getParaProps False
contents <- inlinesToOpenXML opts lst
usedIdents <- gets stSectionIds
let bookmarkName = if null ident
then uniqueIdent lst usedIdents
else ident
modify $ \s -> s{ stSectionIds = Set.insert bookmarkName $ stSectionIds s }
id' <- getUniqueId
let bookmarkStart = mknode "w:bookmarkStart" [("w:id", id')
,("w:name",bookmarkName)] ()
let bookmarkEnd = mknode "w:bookmarkEnd" [("w:id", id')] ()
return [mknode "w:p" [] (paraProps ++ [bookmarkStart, bookmarkEnd] ++ contents)]
blockToOpenXML opts (Plain lst) = withParaProp (pCustomStyle "Compact")
$ blockToOpenXML opts (Para lst)
-- title beginning with fig: indicates that the image is a figure
blockToOpenXML opts (Para [Image attr alt (src,'f':'i':'g':':':tit)]) = do
setFirstPara
pushParaProp $ pCustomStyle $
if null alt
then "Figure"
else "FigureWithCaption"
paraProps <- getParaProps False
popParaProp
contents <- inlinesToOpenXML opts [Image attr alt (src,tit)]
captionNode <- withParaProp (pCustomStyle "ImageCaption")
$ blockToOpenXML opts (Para alt)
return $ mknode "w:p" [] (paraProps ++ contents) : captionNode
-- fixDisplayMath sometimes produces a Para [] as artifact
blockToOpenXML _ (Para []) = return []
blockToOpenXML opts (Para lst) = do
isFirstPara <- gets stFirstPara
paraProps <- getParaProps $ case lst of
[Math DisplayMath _] -> True
_ -> False
bodyTextStyle <- pStyleM "Body Text"
let paraProps' = case paraProps of
[] | isFirstPara -> [mknode "w:pPr" [] [pCustomStyle "FirstParagraph"]]
[] -> [mknode "w:pPr" [] [bodyTextStyle]]
ps -> ps
modify $ \s -> s { stFirstPara = False }
contents <- inlinesToOpenXML opts lst
return [mknode "w:p" [] (paraProps' ++ contents)]
blockToOpenXML _ (RawBlock format str)
| format == Format "openxml" = return [ x | Elem x <- parseXML str ]
| otherwise = return []
blockToOpenXML opts (BlockQuote blocks) = do
p <- withParaPropM (pStyleM "Block Text") $ blocksToOpenXML opts blocks
setFirstPara
return p
blockToOpenXML opts (CodeBlock attrs str) = do
p <- withParaProp (pCustomStyle "SourceCode") (blockToOpenXML opts $ Para [Code attrs str])
setFirstPara
return p
blockToOpenXML _ HorizontalRule = do
setFirstPara
return [
mknode "w:p" [] $ mknode "w:r" [] $ mknode "w:pict" []
$ mknode "v:rect" [("style","width:0;height:1.5pt"),
("o:hralign","center"),
("o:hrstd","t"),("o:hr","t")] () ]
blockToOpenXML opts (Table caption aligns widths headers rows) = do
setFirstPara
let captionStr = stringify caption
caption' <- if null caption
then return []
else withParaProp (pCustomStyle "TableCaption")
$ blockToOpenXML opts (Para caption)
let alignmentFor al = mknode "w:jc" [("w:val",alignmentToString al)] ()
let cellToOpenXML (al, cell) = withParaProp (alignmentFor al)
$ blocksToOpenXML opts cell
headers' <- mapM cellToOpenXML $ zip aligns headers
rows' <- mapM (mapM cellToOpenXML . zip aligns) rows
let borderProps = mknode "w:tcPr" []
[ mknode "w:tcBorders" []
$ mknode "w:bottom" [("w:val","single")] ()
, mknode "w:vAlign" [("w:val","bottom")] () ]
let emptyCell = [mknode "w:p" [] [pCustomStyle "Compact"]]
let mkcell border contents = mknode "w:tc" []
$ [ borderProps | border ] ++
if null contents
then emptyCell
else contents
let mkrow border cells = mknode "w:tr" [] $
[mknode "w:trPr" [] [
mknode "w:cnfStyle" [("w:firstRow","1")] ()] | border]
++ map (mkcell border) cells
let textwidth = 7920 -- 5.5 in in twips, 1/20 pt
let fullrow = 5000 -- 100% specified in pct
let rowwidth = fullrow * sum widths
let mkgridcol w = mknode "w:gridCol"
[("w:w", show (floor (textwidth * w) :: Integer))] ()
let hasHeader = not (all null headers)
return $
caption' ++
[mknode "w:tbl" []
( mknode "w:tblPr" []
( mknode "w:tblStyle" [("w:val","TableNormal")] () :
mknode "w:tblW" [("w:type", "pct"), ("w:w", show rowwidth)] () :
mknode "w:tblLook" [("w:firstRow","1") | hasHeader ] () :
[ mknode "w:tblCaption" [("w:val", captionStr)] ()
| not (null caption) ] )
: mknode "w:tblGrid" []
(if all (==0) widths
then []
else map mkgridcol widths)
: [ mkrow True headers' | hasHeader ] ++
map (mkrow False) rows'
)]
blockToOpenXML opts (BulletList lst) = do
let marker = BulletMarker
addList marker
numid <- getNumId
l <- asList $ concat `fmap` mapM (listItemToOpenXML opts numid) lst
setFirstPara
return l
blockToOpenXML opts (OrderedList (start, numstyle, numdelim) lst) = do
let marker = NumberMarker numstyle numdelim start
addList marker
numid <- getNumId
l <- asList $ concat `fmap` mapM (listItemToOpenXML opts numid) lst
setFirstPara
return l
blockToOpenXML opts (DefinitionList items) = do
l <- concat `fmap` mapM (definitionListItemToOpenXML opts) items
setFirstPara
return l
definitionListItemToOpenXML :: WriterOptions -> ([Inline],[[Block]]) -> WS [Element]
definitionListItemToOpenXML opts (term,defs) = do
term' <- withParaProp (pCustomStyle "DefinitionTerm")
$ blockToOpenXML opts (Para term)
defs' <- withParaProp (pCustomStyle "Definition")
$ concat `fmap` mapM (blocksToOpenXML opts) defs
return $ term' ++ defs'
addList :: ListMarker -> WS ()
addList marker = do
lists <- gets stLists
modify $ \st -> st{ stLists = lists ++ [marker] }
listItemToOpenXML :: WriterOptions -> Int -> [Block] -> WS [Element]
listItemToOpenXML _ _ [] = return []
listItemToOpenXML opts numid (first:rest) = do
first' <- withNumId numid $ blockToOpenXML opts first
-- baseListId is the code for no list marker:
rest' <- withNumId baseListId $ blocksToOpenXML opts rest
return $ first' ++ rest'
alignmentToString :: Alignment -> [Char]
alignmentToString alignment = case alignment of
AlignLeft -> "left"
AlignRight -> "right"
AlignCenter -> "center"
AlignDefault -> "left"
-- | Convert a list of inline elements to OpenXML.
inlinesToOpenXML :: WriterOptions -> [Inline] -> WS [Element]
inlinesToOpenXML opts lst = concat `fmap` mapM (inlineToOpenXML opts) lst
withNumId :: Int -> WS a -> WS a
withNumId numid p = do
origNumId <- gets stListNumId
modify $ \st -> st{ stListNumId = numid }
result <- p
modify $ \st -> st{ stListNumId = origNumId }
return result
asList :: WS a -> WS a
asList p = do
origListLevel <- gets stListLevel
modify $ \st -> st{ stListLevel = stListLevel st + 1 }
result <- p
modify $ \st -> st{ stListLevel = origListLevel }
return result
getTextProps :: WS [Element]
getTextProps = do
props <- gets stTextProperties
return $ if null props
then []
else [mknode "w:rPr" [] props]
pushTextProp :: Element -> WS ()
pushTextProp d = modify $ \s -> s{ stTextProperties = d : stTextProperties s }
popTextProp :: WS ()
popTextProp = modify $ \s -> s{ stTextProperties = drop 1 $ stTextProperties s }
withTextProp :: Element -> WS a -> WS a
withTextProp d p = do
pushTextProp d
res <- p
popTextProp
return res
withTextPropM :: WS Element -> WS a -> WS a
withTextPropM = (. flip withTextProp) . (>>=)
getParaProps :: Bool -> WS [Element]
getParaProps displayMathPara = do
props <- gets stParaProperties
listLevel <- gets stListLevel
numid <- gets stListNumId
let listPr = if listLevel >= 0 && not displayMathPara
then [ mknode "w:numPr" []
[ mknode "w:numId" [("w:val",show numid)] ()
, mknode "w:ilvl" [("w:val",show listLevel)] () ]
]
else []
return $ case props ++ listPr of
[] -> []
ps -> [mknode "w:pPr" [] ps]
pushParaProp :: Element -> WS ()
pushParaProp d = modify $ \s -> s{ stParaProperties = d : stParaProperties s }
popParaProp :: WS ()
popParaProp = modify $ \s -> s{ stParaProperties = drop 1 $ stParaProperties s }
withParaProp :: Element -> WS a -> WS a
withParaProp d p = do
pushParaProp d
res <- p
popParaProp
return res
withParaPropM :: WS Element -> WS a -> WS a
withParaPropM = (. flip withParaProp) . (>>=)
formattedString :: String -> WS [Element]
formattedString str = do
props <- getTextProps
inDel <- gets stInDel
return [ mknode "w:r" [] $
props ++
[ mknode (if inDel then "w:delText" else "w:t")
[("xml:space","preserve")] (stripInvalidChars str) ] ]
setFirstPara :: WS ()
setFirstPara = modify $ \s -> s { stFirstPara = True }
-- | Convert an inline element to OpenXML.
inlineToOpenXML :: WriterOptions -> Inline -> WS [Element]
inlineToOpenXML _ (Str str) = formattedString str
inlineToOpenXML opts Space = inlineToOpenXML opts (Str " ")
inlineToOpenXML opts SoftBreak = inlineToOpenXML opts (Str " ")
inlineToOpenXML opts (Span (_,classes,kvs) ils)
| "insertion" `elem` classes = do
defaultAuthor <- gets stChangesAuthor
defaultDate <- gets stChangesDate
let author = fromMaybe defaultAuthor (lookup "author" kvs)
date = fromMaybe defaultDate (lookup "date" kvs)
insId <- gets stInsId
modify $ \s -> s{stInsId = (insId + 1)}
x <- inlinesToOpenXML opts ils
return [ mknode "w:ins" [("w:id", (show insId)),
("w:author", author),
("w:date", date)]
x ]
| "deletion" `elem` classes = do
defaultAuthor <- gets stChangesAuthor
defaultDate <- gets stChangesDate
let author = fromMaybe defaultAuthor (lookup "author" kvs)
date = fromMaybe defaultDate (lookup "date" kvs)
delId <- gets stDelId
modify $ \s -> s{stDelId = (delId + 1)}
modify $ \s -> s{stInDel = True}
x <- inlinesToOpenXML opts ils
modify $ \s -> s{stInDel = False}
return [ mknode "w:del" [("w:id", (show delId)),
("w:author", author),
("w:date", date)]
x ]
| otherwise = do
let off x = withTextProp (mknode x [("w:val","0")] ())
((if "csl-no-emph" `elem` classes then off "w:i" else id) .
(if "csl-no-strong" `elem` classes then off "w:b" else id) .
(if "csl-no-smallcaps" `elem` classes then off "w:smallCaps" else id))
$ inlinesToOpenXML opts ils
inlineToOpenXML opts (Strong lst) =
withTextProp (mknode "w:b" [] ()) $ inlinesToOpenXML opts lst
inlineToOpenXML opts (Emph lst) =
withTextProp (mknode "w:i" [] ()) $ inlinesToOpenXML opts lst
inlineToOpenXML opts (Subscript lst) =
withTextProp (mknode "w:vertAlign" [("w:val","subscript")] ())
$ inlinesToOpenXML opts lst
inlineToOpenXML opts (Superscript lst) =
withTextProp (mknode "w:vertAlign" [("w:val","superscript")] ())
$ inlinesToOpenXML opts lst
inlineToOpenXML opts (SmallCaps lst) =
withTextProp (mknode "w:smallCaps" [] ())
$ inlinesToOpenXML opts lst
inlineToOpenXML opts (Strikeout lst) =
withTextProp (mknode "w:strike" [] ())
$ inlinesToOpenXML opts lst
inlineToOpenXML _ LineBreak = return [br]
inlineToOpenXML _ (RawInline f str)
| f == Format "openxml" = return [ x | Elem x <- parseXML str ]
| otherwise = return []
inlineToOpenXML opts (Quoted quoteType lst) =
inlinesToOpenXML opts $ [Str open] ++ lst ++ [Str close]
where (open, close) = case quoteType of
SingleQuote -> ("\x2018", "\x2019")
DoubleQuote -> ("\x201C", "\x201D")
inlineToOpenXML opts (Math mathType str) = do
let displayType = if mathType == DisplayMath
then DisplayBlock
else DisplayInline
case writeOMML displayType <$> readTeX str of
Right r -> return [r]
Left _ -> inlinesToOpenXML opts (texMathToInlines mathType str)
inlineToOpenXML opts (Cite _ lst) = inlinesToOpenXML opts lst
inlineToOpenXML opts (Code attrs str) = do
let unhighlighted = intercalate [br] `fmap`
(mapM formattedString $ lines str)
formatOpenXML _fmtOpts = intercalate [br] . map (map toHlTok)
toHlTok (toktype,tok) = mknode "w:r" []
[ mknode "w:rPr" []
[ rCustomStyle (show toktype) ]
, mknode "w:t" [("xml:space","preserve")] tok ]
withTextProp (rCustomStyle "VerbatimChar")
$ if writerHighlight opts
then case highlight formatOpenXML attrs str of
Nothing -> unhighlighted
Just h -> return h
else unhighlighted
inlineToOpenXML opts (Note bs) = do
notes <- gets stFootnotes
notenum <- getUniqueId
footnoteStyle <- rStyleM "Footnote Reference"
let notemarker = mknode "w:r" []
[ mknode "w:rPr" [] footnoteStyle
, mknode "w:footnoteRef" [] () ]
let notemarkerXml = RawInline (Format "openxml") $ ppElement notemarker
let insertNoteRef (Plain ils : xs) = Plain (notemarkerXml : Space : ils) : xs
insertNoteRef (Para ils : xs) = Para (notemarkerXml : Space : ils) : xs
insertNoteRef xs = Para [notemarkerXml] : xs
oldListLevel <- gets stListLevel
oldParaProperties <- gets stParaProperties
oldTextProperties <- gets stTextProperties
modify $ \st -> st{ stListLevel = -1, stParaProperties = [], stTextProperties = [] }
contents <- withParaPropM (pStyleM "Footnote Text") $ blocksToOpenXML opts
$ insertNoteRef bs
modify $ \st -> st{ stListLevel = oldListLevel, stParaProperties = oldParaProperties,
stTextProperties = oldTextProperties }
let newnote = mknode "w:footnote" [("w:id", notenum)] $ contents
modify $ \s -> s{ stFootnotes = newnote : notes }
return [ mknode "w:r" []
[ mknode "w:rPr" [] footnoteStyle
, mknode "w:footnoteReference" [("w:id", notenum)] () ] ]
-- internal link:
inlineToOpenXML opts (Link _ txt ('#':xs,_)) = do
contents <- withTextPropM (rStyleM "Hyperlink") $ inlinesToOpenXML opts txt
return [ mknode "w:hyperlink" [("w:anchor",xs)] contents ]
-- external link:
inlineToOpenXML opts (Link _ txt (src,_)) = do
contents <- withTextPropM (rStyleM "Hyperlink") $ inlinesToOpenXML opts txt
extlinks <- gets stExternalLinks
id' <- case M.lookup src extlinks of
Just i -> return i
Nothing -> do
i <- ("rId"++) `fmap` getUniqueId
modify $ \st -> st{ stExternalLinks =
M.insert src i extlinks }
return i
return [ mknode "w:hyperlink" [("r:id",id')] contents ]
inlineToOpenXML opts (Image attr alt (src, _)) = do
-- first, check to see if we've already done this image
pageWidth <- gets stPrintWidth
imgs <- gets stImages
case M.lookup src imgs of
Just (_,_,_,elt,_) -> return [elt]
Nothing -> do
res <- liftIO $
fetchItem' (writerMediaBag opts) (writerSourceURL opts) src
case res of
Left (_ :: E.SomeException) -> do
liftIO $ warn $ "Could not find image `" ++ src ++ "', skipping..."
-- emit alt text
inlinesToOpenXML opts alt
Right (img, mt) -> do
ident <- ("rId"++) `fmap` getUniqueId
let (xpt,ypt) = desiredSizeInPoints opts attr
(either (const def) id (imageSize img))
-- 12700 emu = 1 pt
let (xemu,yemu) = fitToPage (xpt * 12700, ypt * 12700) (pageWidth * 12700)
let cNvPicPr = mknode "pic:cNvPicPr" [] $
mknode "a:picLocks" [("noChangeArrowheads","1"),("noChangeAspect","1")] ()
let nvPicPr = mknode "pic:nvPicPr" []
[ mknode "pic:cNvPr"
[("descr",src),("id","0"),("name","Picture")] ()
, cNvPicPr ]
let blipFill = mknode "pic:blipFill" []
[ mknode "a:blip" [("r:embed",ident)] ()
, mknode "a:stretch" [] $ mknode "a:fillRect" [] () ]
let xfrm = mknode "a:xfrm" []
[ mknode "a:off" [("x","0"),("y","0")] ()
, mknode "a:ext" [("cx",show xemu),("cy",show yemu)] () ]
let prstGeom = mknode "a:prstGeom" [("prst","rect")] $
mknode "a:avLst" [] ()
let ln = mknode "a:ln" [("w","9525")]
[ mknode "a:noFill" [] ()
, mknode "a:headEnd" [] ()
, mknode "a:tailEnd" [] () ]
let spPr = mknode "pic:spPr" [("bwMode","auto")]
[xfrm, prstGeom, mknode "a:noFill" [] (), ln]
let graphic = mknode "a:graphic" [] $
mknode "a:graphicData" [("uri","http://schemas.openxmlformats.org/drawingml/2006/picture")]
[ mknode "pic:pic" []
[ nvPicPr
, blipFill
, spPr ] ]
let imgElt = mknode "w:r" [] $
mknode "w:drawing" [] $
mknode "wp:inline" []
[ mknode "wp:extent" [("cx",show xemu),("cy",show yemu)] ()
, mknode "wp:effectExtent" [("b","0"),("l","0"),("r","0"),("t","0")] ()
, mknode "wp:docPr" [("descr",stringify alt),("id","1"),("name","Picture")] ()
, graphic ]
let imgext = case mt >>= extensionFromMimeType of
Just x -> '.':x
Nothing -> case imageType img of
Just Png -> ".png"
Just Jpeg -> ".jpeg"
Just Gif -> ".gif"
Just Pdf -> ".pdf"
Just Eps -> ".eps"
Nothing -> ""
if null imgext
then -- without an extension there is no rule for content type
inlinesToOpenXML opts alt -- return alt to avoid corrupted docx
else do
let imgpath = "media/" ++ ident ++ imgext
let mbMimeType = mt <|> getMimeType imgpath
-- insert mime type to use in constructing [Content_Types].xml
modify $ \st -> st{ stImages =
M.insert src (ident, imgpath, mbMimeType, imgElt, img)
$ stImages st }
return [imgElt]
br :: Element
br = mknode "w:r" [] [mknode "w:br" [("w:type","textWrapping")] () ]
-- Word will insert these footnotes into the settings.xml file
-- (whether or not they're visible in the document). If they're in the
-- file, but not in the footnotes.xml file, it will produce
-- problems. So we want to make sure we insert them into our document.
defaultFootnotes :: [Element]
defaultFootnotes = [ mknode "w:footnote"
[("w:type", "separator"), ("w:id", "-1")] $
[ mknode "w:p" [] $
[mknode "w:r" [] $
[ mknode "w:separator" [] ()]]]
, mknode "w:footnote"
[("w:type", "continuationSeparator"), ("w:id", "0")] $
[ mknode "w:p" [] $
[ mknode "w:r" [] $
[ mknode "w:continuationSeparator" [] ()]]]]
parseXml :: Archive -> Archive -> String -> IO Element
parseXml refArchive distArchive relpath =
case findEntryByPath relpath refArchive `mplus`
findEntryByPath relpath distArchive of
Nothing -> fail $ relpath ++ " missing in reference docx"
Just e -> case parseXMLDoc . UTF8.toStringLazy . fromEntry $ e of
Nothing -> fail $ relpath ++ " corrupt in reference docx"
Just d -> return d
-- | Scales the image to fit the page
-- sizes are passed in emu
fitToPage :: (Double, Double) -> Integer -> (Integer, Integer)
fitToPage (x, y) pageWidth
-- Fixes width to the page width and scales the height
| x > fromIntegral pageWidth =
(pageWidth, floor $ ((fromIntegral pageWidth) / x) * y)
| otherwise = (floor x, floor y)
| infotroph/pandoc | src/Text/Pandoc/Writers/Docx.hs | gpl-2.0 | 55,702 | 0 | 28 | 16,583 | 15,592 | 8,025 | 7,567 | 1,014 | 22 |
-- | Miscellaneous utilities for various parts of the library
module Reddit.Utilities
( unescape ) where
import Data.Text (Text)
import qualified Data.Text as Text
-- | Quick-'n'-dirty unescaping function for posts / wiki pages etc..
unescape :: Text -> Text
unescape = replace ">" ">" . replace "<" "<" . replace "&" "&"
-- | Swap all instances of a certain string in another string
replace :: Text -- ^ String to replace
-> Text -- ^ String to replace with
-> Text -- ^ String to search
-> Text
replace s r = Text.intercalate r . Text.splitOn s
| intolerable/reddit | src/Reddit/Utilities.hs | bsd-2-clause | 586 | 0 | 7 | 128 | 113 | 63 | 50 | 11 | 1 |
{-# LANGUAGE CPP, BangPatterns #-}
module Aws.S3.Core where
import Aws.Core
import Control.Arrow ((***))
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Resource (MonadThrow, throwM)
import Crypto.Hash
import Data.Byteable
import Data.Conduit (($$+-))
import Data.Function
import Data.Functor ((<$>))
import Data.IORef
import Data.List
import Data.Maybe
import Data.Monoid
import Control.Applicative ((<|>))
import Data.Time
import Data.Typeable
#if MIN_VERSION_time(1,5,0)
import Data.Time.Format
#else
import System.Locale
#endif
import Text.XML.Cursor (($/), (&|))
import qualified Blaze.ByteString.Builder as Blaze
import qualified Blaze.ByteString.Builder.Char8 as Blaze8
import qualified Control.Exception as C
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Base64 as Base64
import qualified Data.CaseInsensitive as CI
import qualified Data.Conduit as C
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Network.HTTP.Conduit as HTTP
import qualified Network.HTTP.Types as HTTP
import qualified Text.XML as XML
import qualified Text.XML.Cursor as Cu
data S3Authorization
= S3AuthorizationHeader
| S3AuthorizationQuery
deriving (Show)
data RequestStyle
= PathStyle -- ^ Requires correctly setting region endpoint, but allows non-DNS compliant bucket names in the US standard region.
| BucketStyle -- ^ Bucket name must be DNS compliant.
| VHostStyle
deriving (Show)
data S3Configuration qt
= S3Configuration {
s3Protocol :: Protocol
, s3Endpoint :: B.ByteString
, s3RequestStyle :: RequestStyle
, s3Port :: Int
, s3ServerSideEncryption :: Maybe ServerSideEncryption
, s3UseUri :: Bool
, s3DefaultExpiry :: NominalDiffTime
}
deriving (Show)
instance DefaultServiceConfiguration (S3Configuration NormalQuery) where
defServiceConfig = s3 HTTPS s3EndpointUsClassic False
debugServiceConfig = s3 HTTP s3EndpointUsClassic False
instance DefaultServiceConfiguration (S3Configuration UriOnlyQuery) where
defServiceConfig = s3 HTTPS s3EndpointUsClassic True
debugServiceConfig = s3 HTTP s3EndpointUsClassic True
s3EndpointUsClassic :: B.ByteString
s3EndpointUsClassic = "s3.amazonaws.com"
s3EndpointUsWest :: B.ByteString
s3EndpointUsWest = "s3-us-west-1.amazonaws.com"
s3EndpointUsWest2 :: B.ByteString
s3EndpointUsWest2 = "s3-us-west-2.amazonaws.com"
s3EndpointEu :: B.ByteString
s3EndpointEu = "s3-eu-west-1.amazonaws.com"
s3EndpointApSouthEast :: B.ByteString
s3EndpointApSouthEast = "s3-ap-southeast-1.amazonaws.com"
s3EndpointApSouthEast2 :: B.ByteString
s3EndpointApSouthEast2 = "s3-ap-southeast-2.amazonaws.com"
s3EndpointApNorthEast :: B.ByteString
s3EndpointApNorthEast = "s3-ap-northeast-1.amazonaws.com"
s3 :: Protocol -> B.ByteString -> Bool -> S3Configuration qt
s3 protocol endpoint uri
= S3Configuration {
s3Protocol = protocol
, s3Endpoint = endpoint
, s3RequestStyle = BucketStyle
, s3Port = defaultPort protocol
, s3ServerSideEncryption = Nothing
, s3UseUri = uri
, s3DefaultExpiry = 15*60
}
type ErrorCode = T.Text
data S3Error
= S3Error {
s3StatusCode :: HTTP.Status
, s3ErrorCode :: ErrorCode -- Error/Code
, s3ErrorMessage :: T.Text -- Error/Message
, s3ErrorResource :: Maybe T.Text -- Error/Resource
, s3ErrorHostId :: Maybe T.Text -- Error/HostId
, s3ErrorAccessKeyId :: Maybe T.Text -- Error/AWSAccessKeyId
, s3ErrorStringToSign :: Maybe B.ByteString -- Error/StringToSignBytes (hexadecimal encoding)
, s3ErrorBucket :: Maybe T.Text -- Error/Bucket
, s3ErrorEndpointRaw :: Maybe T.Text -- Error/Endpoint (i.e. correct bucket location)
, s3ErrorEndpoint :: Maybe B.ByteString -- Error/Endpoint without the bucket prefix
}
deriving (Show, Typeable)
instance C.Exception S3Error
data S3Metadata
= S3Metadata {
s3MAmzId2 :: Maybe T.Text
, s3MRequestId :: Maybe T.Text
}
deriving (Show, Typeable)
instance Monoid S3Metadata where
mempty = S3Metadata Nothing Nothing
S3Metadata a1 r1 `mappend` S3Metadata a2 r2 = S3Metadata (a1 `mplus` a2) (r1 `mplus` r2)
instance Loggable S3Metadata where
toLogText (S3Metadata id2 rid) = "S3: request ID=" `mappend`
fromMaybe "<none>" rid `mappend`
", x-amz-id-2=" `mappend`
fromMaybe "<none>" id2
data S3Query
= S3Query {
s3QMethod :: Method
, s3QBucket :: Maybe B.ByteString
, s3QObject :: Maybe B.ByteString
, s3QSubresources :: HTTP.Query
, s3QQuery :: HTTP.Query
, s3QContentType :: Maybe B.ByteString
, s3QContentMd5 :: Maybe (Digest MD5)
, s3QAmzHeaders :: HTTP.RequestHeaders
, s3QOtherHeaders :: HTTP.RequestHeaders
#if MIN_VERSION_http_conduit(2, 0, 0)
, s3QRequestBody :: Maybe HTTP.RequestBody
#else
, s3QRequestBody :: Maybe (HTTP.RequestBody (C.ResourceT IO))
#endif
}
instance Show S3Query where
show S3Query{..} = "S3Query [" ++
" method: " ++ show s3QMethod ++
" ; bucket: " ++ show s3QBucket ++
" ; subresources: " ++ show s3QSubresources ++
" ; query: " ++ show s3QQuery ++
" ; request body: " ++ (case s3QRequestBody of Nothing -> "no"; _ -> "yes") ++
"]"
s3SignQuery :: S3Query -> S3Configuration qt -> SignatureData -> SignedQuery
s3SignQuery S3Query{..} S3Configuration{..} SignatureData{..}
= SignedQuery {
sqMethod = s3QMethod
, sqProtocol = s3Protocol
, sqHost = B.intercalate "." $ catMaybes host
, sqPort = s3Port
, sqPath = mconcat $ catMaybes path
, sqQuery = sortedSubresources ++ s3QQuery ++ authQuery :: HTTP.Query
, sqDate = Just signatureTime
, sqAuthorization = authorization
, sqContentType = s3QContentType
, sqContentMd5 = s3QContentMd5
, sqAmzHeaders = amzHeaders
, sqOtherHeaders = s3QOtherHeaders
, sqBody = s3QRequestBody
, sqStringToSign = stringToSign
}
where
amzHeaders = merge $ sortBy (compare `on` fst) (s3QAmzHeaders ++ (fmap (\(k, v) -> (CI.mk k, v)) iamTok))
where merge (x1@(k1,v1):x2@(k2,v2):xs) | k1 == k2 = merge ((k1, B8.intercalate "," [v1, v2]) : xs)
| otherwise = x1 : merge (x2 : xs)
merge xs = xs
urlEncodedS3QObject = HTTP.urlEncode False <$> s3QObject
(host, path) = case s3RequestStyle of
PathStyle -> ([Just s3Endpoint], [Just "/", fmap (`B8.snoc` '/') s3QBucket, urlEncodedS3QObject])
BucketStyle -> ([s3QBucket, Just s3Endpoint], [Just "/", urlEncodedS3QObject])
VHostStyle -> ([Just $ fromMaybe s3Endpoint s3QBucket], [Just "/", urlEncodedS3QObject])
sortedSubresources = sort s3QSubresources
canonicalizedResource = Blaze8.fromChar '/' `mappend`
maybe mempty (\s -> Blaze.copyByteString s `mappend` Blaze8.fromChar '/') s3QBucket `mappend`
maybe mempty Blaze.copyByteString urlEncodedS3QObject `mappend`
HTTP.renderQueryBuilder True sortedSubresources
ti = case (s3UseUri, signatureTimeInfo) of
(False, ti') -> ti'
(True, AbsoluteTimestamp time) -> AbsoluteExpires $ s3DefaultExpiry `addUTCTime` time
(True, AbsoluteExpires time) -> AbsoluteExpires time
sig = signature signatureCredentials HmacSHA1 stringToSign
iamTok = maybe [] (\x -> [("x-amz-security-token", x)]) (iamToken signatureCredentials)
stringToSign = Blaze.toByteString . mconcat . intersperse (Blaze8.fromChar '\n') . concat $
[[Blaze.copyByteString $ httpMethod s3QMethod]
, [maybe mempty (Blaze.copyByteString . Base64.encode . toBytes) s3QContentMd5]
, [maybe mempty Blaze.copyByteString s3QContentType]
, [Blaze.copyByteString $ case ti of
AbsoluteTimestamp time -> fmtRfc822Time time
AbsoluteExpires time -> fmtTimeEpochSeconds time]
, map amzHeader amzHeaders
, [canonicalizedResource]
]
where amzHeader (k, v) = Blaze.copyByteString (CI.foldedCase k) `mappend` Blaze8.fromChar ':' `mappend` Blaze.copyByteString v
(authorization, authQuery) = case ti of
AbsoluteTimestamp _ -> (Just $ return $ B.concat ["AWS ", accessKeyID signatureCredentials, ":", sig], [])
AbsoluteExpires time -> (Nothing, HTTP.toQuery $ makeAuthQuery time)
makeAuthQuery time
= [("Expires" :: B8.ByteString, fmtTimeEpochSeconds time)
, ("AWSAccessKeyId", accessKeyID signatureCredentials)
, ("SignatureMethod", "HmacSHA256")
, ("Signature", sig)] ++ iamTok
s3ResponseConsumer :: HTTPResponseConsumer a
-> IORef S3Metadata
-> HTTPResponseConsumer a
s3ResponseConsumer inner metadataRef = s3BinaryResponseConsumer inner' metadataRef
where inner' resp =
do
!res <- inner resp
C.closeResumableSource (HTTP.responseBody resp)
return res
s3BinaryResponseConsumer :: HTTPResponseConsumer a
-> IORef S3Metadata
-> HTTPResponseConsumer a
s3BinaryResponseConsumer inner metadata resp = do
let headerString = fmap T.decodeUtf8 . flip lookup (HTTP.responseHeaders resp)
let amzId2 = headerString "x-amz-id-2"
let requestId = headerString "x-amz-request-id"
let m = S3Metadata { s3MAmzId2 = amzId2, s3MRequestId = requestId }
liftIO $ tellMetadataRef metadata m
if HTTP.responseStatus resp >= HTTP.status300
then s3ErrorResponseConsumer resp
else inner resp
s3XmlResponseConsumer :: (Cu.Cursor -> Response S3Metadata a)
-> IORef S3Metadata
-> HTTPResponseConsumer a
s3XmlResponseConsumer parse metadataRef =
s3ResponseConsumer (xmlCursorConsumer parse metadataRef) metadataRef
s3ErrorResponseConsumer :: HTTPResponseConsumer a
s3ErrorResponseConsumer resp
= do doc <- HTTP.responseBody resp $$+- XML.sinkDoc XML.def
let cursor = Cu.fromDocument doc
liftIO $ case parseError cursor of
Right err -> throwM err
Left otherErr -> throwM otherErr
where
parseError :: Cu.Cursor -> Either C.SomeException S3Error
parseError root = do code <- force "Missing error Code" $ root $/ elContent "Code"
message <- force "Missing error Message" $ root $/ elContent "Message"
let resource = listToMaybe $ root $/ elContent "Resource"
hostId = listToMaybe $ root $/ elContent "HostId"
accessKeyId = listToMaybe $ root $/ elContent "AWSAccessKeyId"
bucket = listToMaybe $ root $/ elContent "Bucket"
endpointRaw = listToMaybe $ root $/ elContent "Endpoint"
endpoint = T.encodeUtf8 <$> (T.stripPrefix (fromMaybe "" bucket <> ".") =<< endpointRaw)
stringToSign = do unprocessed <- listToMaybe $ root $/ elCont "StringToSignBytes"
bytes <- mapM readHex2 $ words unprocessed
return $ B.pack bytes
return S3Error {
s3StatusCode = HTTP.responseStatus resp
, s3ErrorCode = code
, s3ErrorMessage = message
, s3ErrorResource = resource
, s3ErrorHostId = hostId
, s3ErrorAccessKeyId = accessKeyId
, s3ErrorStringToSign = stringToSign
, s3ErrorBucket = bucket
, s3ErrorEndpointRaw = endpointRaw
, s3ErrorEndpoint = endpoint
}
type CanonicalUserId = T.Text
data UserInfo
= UserInfo {
userId :: CanonicalUserId
, userDisplayName :: T.Text
}
deriving (Show)
parseUserInfo :: MonadThrow m => Cu.Cursor -> m UserInfo
parseUserInfo el = do id_ <- force "Missing user ID" $ el $/ elContent "ID"
displayName <- force "Missing user DisplayName" $ el $/ elContent "DisplayName"
return UserInfo { userId = id_, userDisplayName = displayName }
data CannedAcl
= AclPrivate
| AclPublicRead
| AclPublicReadWrite
| AclAuthenticatedRead
| AclBucketOwnerRead
| AclBucketOwnerFullControl
| AclLogDeliveryWrite
deriving (Show)
writeCannedAcl :: CannedAcl -> T.Text
writeCannedAcl AclPrivate = "private"
writeCannedAcl AclPublicRead = "public-read"
writeCannedAcl AclPublicReadWrite = "public-read-write"
writeCannedAcl AclAuthenticatedRead = "authenticated-read"
writeCannedAcl AclBucketOwnerRead = "bucket-owner-read"
writeCannedAcl AclBucketOwnerFullControl = "bucket-owner-full-control"
writeCannedAcl AclLogDeliveryWrite = "log-delivery-write"
data StorageClass
= Standard
| StandardInfrequentAccess
| ReducedRedundancy
| Glacier
| OtherStorageClass T.Text
deriving (Show)
parseStorageClass :: T.Text -> StorageClass
parseStorageClass "STANDARD" = Standard
parseStorageClass "STANDARD_IA" = StandardInfrequentAccess
parseStorageClass "REDUCED_REDUNDANCY" = ReducedRedundancy
parseStorageClass "GLACIER" = Glacier
parseStorageClass s = OtherStorageClass s
writeStorageClass :: StorageClass -> T.Text
writeStorageClass Standard = "STANDARD"
writeStorageClass StandardInfrequentAccess = "STANDARD_IA"
writeStorageClass ReducedRedundancy = "REDUCED_REDUNDANCY"
writeStorageClass Glacier = "GLACIER"
writeStorageClass (OtherStorageClass s) = s
data ServerSideEncryption
= AES256
deriving (Show)
parseServerSideEncryption :: MonadThrow m => T.Text -> m ServerSideEncryption
parseServerSideEncryption "AES256" = return AES256
parseServerSideEncryption s = throwM . XmlException $ "Invalid Server Side Encryption: " ++ T.unpack s
writeServerSideEncryption :: ServerSideEncryption -> T.Text
writeServerSideEncryption AES256 = "AES256"
type Bucket = T.Text
data BucketInfo
= BucketInfo {
bucketName :: Bucket
, bucketCreationDate :: UTCTime
}
deriving (Show)
type Object = T.Text
data ObjectId
= ObjectId {
oidBucket :: Bucket
, oidObject :: Object
, oidVersion :: Maybe T.Text
}
deriving (Show)
data ObjectInfo
= ObjectInfo {
objectKey :: T.Text
, objectLastModified :: UTCTime
, objectETag :: T.Text
, objectSize :: Integer
, objectStorageClass :: StorageClass
, objectOwner :: Maybe UserInfo
}
deriving (Show)
parseObjectInfo :: MonadThrow m => Cu.Cursor -> m ObjectInfo
parseObjectInfo el
= do key <- force "Missing object Key" $ el $/ elContent "Key"
let time s = case (parseTime defaultTimeLocale "%Y-%m-%dT%H:%M:%S%QZ" $ T.unpack s) <|>
(parseTime defaultTimeLocale "%Y-%m-%dT%H:%M:%S%Q%Z" $ T.unpack s) of
Nothing -> throwM $ XmlException "Invalid time"
Just v -> return v
lastModified <- forceM "Missing object LastModified" $ el $/ elContent "LastModified" &| time
eTag <- force "Missing object ETag" $ el $/ elContent "ETag"
size <- forceM "Missing object Size" $ el $/ elContent "Size" &| textReadInt
storageClass <- forceM "Missing object StorageClass" $ el $/ elContent "StorageClass" &| return . parseStorageClass
owner <- case el $/ Cu.laxElement "Owner" &| parseUserInfo of
(x:_) -> fmap' Just x
[] -> return Nothing
return ObjectInfo{
objectKey = key
, objectLastModified = lastModified
, objectETag = eTag
, objectSize = size
, objectStorageClass = storageClass
, objectOwner = owner
}
where
fmap' :: Monad m => (a -> b) -> m a -> m b
fmap' f ma = ma >>= return . f
data ObjectMetadata
= ObjectMetadata {
omDeleteMarker :: Bool
, omETag :: T.Text
, omLastModified :: UTCTime
, omVersionId :: Maybe T.Text
-- TODO:
-- , omExpiration :: Maybe (UTCTime, T.Text)
, omUserMetadata :: [(T.Text, T.Text)]
, omMissingUserMetadata :: Maybe T.Text
, omServerSideEncryption :: Maybe ServerSideEncryption
}
deriving (Show)
parseObjectMetadata :: MonadThrow m => HTTP.ResponseHeaders -> m ObjectMetadata
parseObjectMetadata h = ObjectMetadata
`liftM` deleteMarker
`ap` etag
`ap` lastModified
`ap` return versionId
-- `ap` expiration
`ap` return userMetadata
`ap` return missingUserMetadata
`ap` serverSideEncryption
where deleteMarker = case B8.unpack `fmap` lookup "x-amz-delete-marker" h of
Nothing -> return False
Just "true" -> return True
Just "false" -> return False
Just x -> throwM $ HeaderException ("Invalid x-amz-delete-marker " ++ x)
etag = case T.decodeUtf8 `fmap` lookup "ETag" h of
Just x -> return x
Nothing -> throwM $ HeaderException "ETag missing"
lastModified = case B8.unpack `fmap` lookup "Last-Modified" h of
Just ts -> case parseHttpDate ts of
Just t -> return t
Nothing -> throwM $ HeaderException ("Invalid Last-Modified: " ++ ts)
Nothing -> throwM $ HeaderException "Last-Modified missing"
versionId = T.decodeUtf8 `fmap` lookup "x-amz-version-id" h
-- expiration = return undefined
userMetadata = flip mapMaybe ht $
\(k, v) -> do i <- T.stripPrefix "x-amz-meta-" k
return (i, v)
missingUserMetadata = T.decodeUtf8 `fmap` lookup "x-amz-missing-meta" h
serverSideEncryption = case T.decodeUtf8 `fmap` lookup "x-amz-server-side-encryption" h of
Just x -> return $ parseServerSideEncryption x
Nothing -> return Nothing
ht = map ((T.decodeUtf8 . CI.foldedCase) *** T.decodeUtf8) h
type LocationConstraint = T.Text
locationUsClassic, locationUsWest, locationUsWest2, locationEu, locationEuFrankfurt, locationApSouthEast, locationApSouthEast2, locationApNorthEast, locationSA :: LocationConstraint
locationUsClassic = ""
locationUsWest = "us-west-1"
locationUsWest2 = "us-west-2"
locationEu = "EU"
locationEuFrankfurt = "eu-central-1"
locationApSouthEast = "ap-southeast-1"
locationApSouthEast2 = "ap-southeast-2"
locationApNorthEast = "ap-northeast-1"
locationSA = "sa-east-1"
normaliseLocation :: LocationConstraint -> LocationConstraint
normaliseLocation location
| location == "eu-west-1" = locationEu
| otherwise = location
| romanb/aws | Aws/S3/Core.hs | bsd-3-clause | 20,800 | 0 | 18 | 6,661 | 4,490 | 2,434 | 2,056 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
module Stack.ConfigSpec where
import Data.Aeson.Extended
import Data.Yaml
import Path
import Path.IO hiding (withSystemTempDir)
import Stack.Config
import Stack.Prelude
import Stack.Types.Config
import Stack.Types.Runner
import System.Directory
import System.Environment
import System.IO (writeFile)
import Test.Hspec
sampleConfig :: String
sampleConfig =
"resolver: lts-2.10\n" ++
"packages: ['.']\n"
buildOptsConfig :: String
buildOptsConfig =
"resolver: lts-2.10\n" ++
"packages: ['.']\n" ++
"build:\n" ++
" library-profiling: true\n" ++
" executable-profiling: true\n" ++
" haddock: true\n" ++
" haddock-deps: true\n" ++
" copy-bins: true\n" ++
" prefetch: true\n" ++
" force-dirty: true\n" ++
" keep-going: true\n" ++
" test: true\n" ++
" test-arguments:\n" ++
" rerun-tests: true\n" ++
" additional-args: ['-fprof']\n" ++
" coverage: true\n" ++
" no-run-tests: true\n" ++
" bench: true\n" ++
" benchmark-opts:\n" ++
" benchmark-arguments: -O2\n" ++
" no-run-benchmarks: true\n" ++
" reconfigure: true\n" ++
" cabal-verbose: true\n"
hpackConfig :: String
hpackConfig =
"resolver: lts-2.10\n" ++
"with-hpack: /usr/local/bin/hpack\n" ++
"packages: ['.']\n"
stackDotYaml :: Path Rel File
stackDotYaml = $(mkRelFile "stack.yaml")
setup :: IO ()
setup = unsetEnv "STACK_YAML"
noException :: Selector SomeException
noException = const False
spec :: Spec
spec = beforeAll setup $ do
let logLevel = LevelDebug
-- TODO(danburton): not use inTempDir
let inTempDir action = do
currentDirectory <- getCurrentDirectory
withSystemTempDirectory "Stack_ConfigSpec" $ \tempDir -> do
let enterDir = setCurrentDirectory tempDir
let exitDir = setCurrentDirectory currentDirectory
bracket_ enterDir exitDir action
-- TODO(danburton): a safer version of this?
let withEnvVar name newValue action = do
originalValue <- fromMaybe "" <$> lookupEnv name
let setVar = setEnv name newValue
let resetVar = setEnv name originalValue
bracket_ setVar resetVar action
describe "loadConfig" $ do
let loadConfig' inner =
withRunner logLevel True False ColorAuto Nothing False $ \runner -> do
lc <- runRIO runner $ loadConfig mempty Nothing SYLDefault
inner lc
-- TODO(danburton): make sure parent dirs also don't have config file
it "works even if no config file exists" $ example $
loadConfig' $ const $ return ()
it "works with a blank config file" $ inTempDir $ do
writeFile (toFilePath stackDotYaml) ""
-- TODO(danburton): more specific test for exception
loadConfig' (const (return ())) `shouldThrow` anyException
it "parses config option with-hpack" $ inTempDir $ do
writeFile (toFilePath stackDotYaml) hpackConfig
loadConfig' $ \lc -> do
let Config{..} = lcConfig lc
configOverrideHpack `shouldBe` HpackCommand "/usr/local/bin/hpack"
it "parses config bundled hpack" $ inTempDir $ do
writeFile (toFilePath stackDotYaml) sampleConfig
loadConfig' $ \lc -> do
let Config{..} = lcConfig lc
configOverrideHpack `shouldBe` HpackBundled
it "parses build config options" $ inTempDir $ do
writeFile (toFilePath stackDotYaml) buildOptsConfig
loadConfig' $ \lc -> do
let BuildOpts{..} = configBuild $ lcConfig lc
boptsLibProfile `shouldBe` True
boptsExeProfile `shouldBe` True
boptsHaddock `shouldBe` True
boptsHaddockDeps `shouldBe` Just True
boptsInstallExes `shouldBe` True
boptsPreFetch `shouldBe` True
boptsKeepGoing `shouldBe` Just True
boptsForceDirty `shouldBe` True
boptsTests `shouldBe` True
boptsTestOpts `shouldBe` TestOpts {toRerunTests = True
,toAdditionalArgs = ["-fprof"]
,toCoverage = True
,toDisableRun = True}
boptsBenchmarks `shouldBe` True
boptsBenchmarkOpts `shouldBe` BenchmarkOpts {beoAdditionalArgs = Just "-O2"
,beoDisableRun = True}
boptsReconfigure `shouldBe` True
boptsCabalVerbose `shouldBe` True
it "finds the config file in a parent directory" $ inTempDir $ do
writeFile (toFilePath stackDotYaml) sampleConfig
parentDir <- getCurrentDirectory >>= parseAbsDir
let childDir = "child"
createDirectory childDir
setCurrentDirectory childDir
loadConfig' $ \LoadConfig{..} -> do
bc <- liftIO (lcLoadBuildConfig Nothing)
view projectRootL bc `shouldBe` parentDir
it "respects the STACK_YAML env variable" $ inTempDir $ do
withSystemTempDir "config-is-here" $ \dir -> do
let stackYamlFp = toFilePath (dir </> stackDotYaml)
writeFile stackYamlFp sampleConfig
withEnvVar "STACK_YAML" stackYamlFp $ loadConfig' $ \LoadConfig{..} -> do
BuildConfig{..} <- lcLoadBuildConfig Nothing
bcStackYaml `shouldBe` dir </> stackDotYaml
parent bcStackYaml `shouldBe` dir
it "STACK_YAML can be relative" $ inTempDir $ do
parentDir <- getCurrentDirectory >>= parseAbsDir
let childRel = $(mkRelDir "child")
yamlRel = childRel </> $(mkRelFile "some-other-name.config")
yamlAbs = parentDir </> yamlRel
createDirectoryIfMissing True $ toFilePath $ parent yamlAbs
writeFile (toFilePath yamlAbs) "resolver: ghc-7.8"
withEnvVar "STACK_YAML" (toFilePath yamlRel) $ loadConfig' $ \LoadConfig{..} -> do
BuildConfig{..} <- lcLoadBuildConfig Nothing
bcStackYaml `shouldBe` yamlAbs
describe "defaultConfigYaml" $
it "is parseable" $ \_ -> do
curDir <- getCurrentDir
let parsed :: Either String (Either String (WithJSONWarnings ConfigMonoid))
parsed = parseEither (parseConfigMonoid curDir) <$> decodeEither defaultConfigYaml
case parsed of
Right (Right _) -> return () :: IO ()
_ -> fail "Failed to parse default config yaml"
| MichielDerhaeg/stack | src/test/Stack/ConfigSpec.hs | bsd-3-clause | 6,310 | 0 | 26 | 1,588 | 1,478 | 719 | 759 | 148 | 2 |
module GetContents where
import qualified Github.Repos as Github
import Data.List
import Prelude hiding (truncate, getContents)
main = do
putStrLn "Root"
putStrLn "===="
getContents ""
putStrLn "LICENSE"
putStrLn "======="
getContents "LICENSE"
getContents path = do
contents <- Github.contentsFor "mike-burns" "ohlaunch" path Nothing
putStrLn $ either (("Error: " ++) . show) formatContents contents
formatContents (Github.ContentFile fileData) =
formatContentInfo (Github.contentFileInfo fileData) ++
unlines
[ show (Github.contentFileSize fileData) ++ " bytes"
, "encoding: " ++ Github.contentFileEncoding fileData
, "data: " ++ truncate (Github.contentFileContent fileData)
]
formatContents (Github.ContentDirectory items) =
intercalate "\n\n" $ map formatItem items
formatContentInfo contentInfo =
unlines
[ "name: " ++ Github.contentName contentInfo
, "path: " ++ Github.contentPath contentInfo
, "sha: " ++ Github.contentSha contentInfo
, "url: " ++ Github.contentUrl contentInfo
, "git url: " ++ Github.contentGitUrl contentInfo
, "html url: " ++ Github.contentHtmlUrl contentInfo
]
formatItem item =
"type: " ++ show (Github.contentItemType item) ++ "\n" ++
formatContentInfo (Github.contentItemInfo item)
truncate str = take 40 str ++ "... (truncated)"
| bitemyapp/github | samples/Repos/Contents.hs | bsd-3-clause | 1,346 | 0 | 12 | 241 | 373 | 182 | 191 | 34 | 1 |
module Parse.Binop (binops, OpTable) where
import qualified Data.List as List
import qualified Data.Map as Map
import Text.Parsec ((<|>), choice, getState, try)
import AST.Declaration (Assoc(L, N, R))
import AST.Expression.General (Expr'(Binop))
import qualified AST.Expression.Source as Source
import qualified AST.Variable as Var
import Parse.Helpers (IParser, OpTable, commitIf, failure, whitespace)
import qualified Reporting.Annotation as A
opLevel :: OpTable -> String -> Int
opLevel table op =
fst $ Map.findWithDefault (9,L) op table
opAssoc :: OpTable -> String -> Assoc
opAssoc table op =
snd $ Map.findWithDefault (9,L) op table
hasLevel :: OpTable -> Int -> (String, Source.Expr) -> Bool
hasLevel table n (op,_) =
opLevel table op == n
binops
:: IParser Source.Expr
-> IParser Source.Expr
-> IParser String
-> IParser Source.Expr
binops term last anyOp =
do e <- term
table <- getState
split table 0 e =<< nextOps
where
nextOps =
choice
[ commitIf (whitespace >> anyOp) $
do whitespace
op <- anyOp
whitespace
expr <- Left <$> try term <|> Right <$> last
case expr of
Left t -> (:) (op,t) <$> nextOps
Right e -> return [(op,e)]
, return []
]
split
:: OpTable
-> Int
-> Source.Expr
-> [(String, Source.Expr)]
-> IParser Source.Expr
split _ _ e [] = return e
split table n e eops =
do assoc <- getAssoc table n eops
es <- sequence (splitLevel table n e eops)
let ops = map fst (filter (hasLevel table n) eops)
case assoc of
R -> joinR es ops
_ -> joinL es ops
splitLevel
:: OpTable
-> Int
-> Source.Expr
-> [(String, Source.Expr)]
-> [IParser Source.Expr]
splitLevel table n e eops =
case break (hasLevel table n) eops of
(lops, (_op,e'):rops) ->
split table (n+1) e lops : splitLevel table n e' rops
(lops, []) ->
[ split table (n+1) e lops ]
joinL :: [Source.Expr] -> [String] -> IParser Source.Expr
joinL exprs ops =
case (exprs, ops) of
([expr], []) ->
return expr
(a:b:remainingExprs, op:remainingOps) ->
let binop = A.merge a b (Binop (Var.Raw op) a b)
in
joinL (binop : remainingExprs) remainingOps
(_, _) ->
failure "Ill-formed binary expression. Report a compiler bug."
joinR :: [Source.Expr] -> [String] -> IParser Source.Expr
joinR exprs ops =
case (exprs, ops) of
([expr], []) ->
return expr
(a:b:remainingExprs, op:remainingOps) ->
do e <- joinR (b:remainingExprs) remainingOps
return (A.merge a e (Binop (Var.Raw op) a e))
(_, _) ->
failure "Ill-formed binary expression. Report a compiler bug."
getAssoc :: OpTable -> Int -> [(String,Source.Expr)] -> IParser Assoc
getAssoc table n eops
| all (==L) assocs = return L
| all (==R) assocs = return R
| all (==N) assocs =
case assocs of
[_] -> return N
_ -> failure (msg "precedence")
| otherwise = failure (msg "associativity")
where
levelOps = filter (hasLevel table n) eops
assocs = map (opAssoc table . fst) levelOps
msg problem =
concat
[ "Conflicting " ++ problem ++ " for binary operators ("
, List.intercalate ", " (map fst eops), "). "
, "Consider adding parentheses to disambiguate."
]
| laszlopandy/elm-compiler | src/Parse/Binop.hs | bsd-3-clause | 3,497 | 0 | 17 | 1,027 | 1,338 | 701 | 637 | 101 | 3 |
module T16114 where
data T a
instance Eq a => Eq a => Eq (T a) where (==) = undefined
| sdiehl/ghc | testsuite/tests/rename/should_fail/T16114.hs | bsd-3-clause | 87 | 1 | 7 | 21 | 44 | 24 | 20 | -1 | -1 |
{-# htermination enumFromTo :: Int -> Int -> [Int] #-}
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Prelude_enumFromTo_4.hs | mit | 55 | 0 | 2 | 10 | 3 | 2 | 1 | 1 | 0 |
{-# LANGUAGE LambdaCase, ConstraintKinds #-}
------------------------------------------------------------------------------
-- |
-- Module : RemindHelpers
-- Copyright : (C) 2014 Samuli Thomasson
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Samuli Thomasson <samuli.thomasson@paivola.fi>
-- Stability : experimental
-- Portability : non-portable
------------------------------------------------------------------------------
module RemindHelpers where
import Prelude
import Yesod
import Model
import Control.Applicative
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Database.Persist.Sql
import qualified System.Process as P
import System.Exit (ExitCode(..))
import System.IO (hClose)
type RemindRes = Either Text Text
type RemindCtx site = (Yesod site, YesodPersist site, YesodPersistBackend site ~ SqlBackend)
-- | Run a remind command
remindRun :: MonadIO m => [String] -> Text -> m RemindRes
remindRun ps ctx = liftIO $ do
(Just inp, Just out, Just err, pid) <- P.createProcess
( (P.proc "remind" (ps ++ ["-"]))
{ P.std_in = P.CreatePipe
, P.std_out = P.CreatePipe
, P.std_err = P.CreatePipe
}
)
T.hPutStr inp ctx >> hClose inp
out' <- T.hGetContents out
err' <- T.hGetContents err
P.waitForProcess pid >>= return . \case
ExitSuccess -> Right out'
ExitFailure _ -> Left err'
-- | Print a reminder line formatted inside an <i> element.
prettyRemindI :: Text -> WidgetT site IO ()
prettyRemindI txt = case T.words txt of
date : _ : _ : _ : _ : time : msg -> [whamlet|<i>#{date} #{time} - #{T.unwords msg}|]
_ -> [whamlet|error: no parse: #{txt}|]
-- | <li> entries for next reminders.
remindListS :: RemindCtx site => Text -> WidgetT site IO ()
remindListS txt = do
res <- fmap T.lines <$> remindRun ["-r", "-s+2"] txt
[whamlet|
$case res
$of Right xs
$forall x <- xs
<li.light>^{prettyRemindI x}
$of Left err
<li.alert-error>err
|]
-- | Combine all remind entries from DB to a single text that can be fed to
-- 'remind'.
combineReminds :: RemindCtx site => HandlerT site IO Text
combineReminds = do
txts <- runDB (selectList [] [])
return $ T.unlines . concat $ map (T.lines . T.replace "\r\n" "\n" . calendarRemind . entityVal) txts
remindNextWeeks :: RemindCtx site => WidgetT site IO ()
remindNextWeeks = remindListS =<< handlerToWidget combineReminds
-- | A simple ascii calendar (remind -c)
remindAsciiCalendar :: RemindCtx site => HandlerT site IO RemindRes
remindAsciiCalendar = remindRun
["-c+4" -- generate four week calendar
, "-b1" -- 24h time format
, "-m" -- week begins at monday
, "-r" -- disable RUN and shell()
, "-w110,0,0" -- 110 character cells
] =<< combineReminds
| TK009/loyly | RemindHelpers.hs | mit | 2,973 | 0 | 16 | 718 | 669 | 363 | 306 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE QuasiQuotes #-}
import Control.Applicative ((<$>), (<*>))
import Control.Monad (mzero)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Logger (runNoLoggingT, NoLoggingT)
import Control.Monad.Trans.Resource (runResourceT, ResourceT)
import Control.Monad.Trans.Either
import Data.Aeson
import Data.Maybe (fromMaybe)
import qualified Data.Text as Text
import Data.Proxy
import qualified Database.Persist.Class as DB
import qualified Database.Persist.Sqlite as Sqlite
import Database.Persist.TH
import Network.HTTP.Types
import Network.Wai
import Network.Wai.Handler.Warp (run)
import Network.Wai.Middleware.AddHeaders
import Servant
import System.Environment
import Web.PathPieces
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Todo
title String
completed Bool
order Int
deriving Show
|]
runDb :: Sqlite.SqlPersistT (ResourceT (NoLoggingT IO)) a -> IO a
runDb = runNoLoggingT . runResourceT . Sqlite.withSqliteConn "dev.sqlite3" . Sqlite.runSqlConn
instance ToJSON (Sqlite.Entity Todo) where
toJSON entity = object
[ "id" .= key
, "url" .= ("http://127.0.0.1:3000/todos/" ++ keyText)
, "title" .= todoTitle val
, "completed" .= todoCompleted val
, "order" .= todoOrder val
]
where
key = Sqlite.entityKey entity
val = Sqlite.entityVal entity
keyText = Text.unpack $ toPathPiece key
data TodoAction = TodoAction
{ actTitle :: Maybe String
, actCompleted :: Maybe Bool
, actOrder :: Maybe Int
} deriving Show
instance FromJSON TodoAction where
parseJSON (Object o) = TodoAction
<$> o .:? "title"
<*> o .:? "completed"
<*> o .:? "order"
parseJSON _ = mzero
instance ToJSON TodoAction where
toJSON (TodoAction mTitle mCompl mOrder) = noNullsObject
[ "title" .= mTitle
, "completed" .= mCompl
, "order" .= mOrder
]
where
noNullsObject = object . filter notNull
notNull (_, Null) = False
notNull _ = True
actionToTodo :: TodoAction -> Todo
actionToTodo (TodoAction mTitle mCompleted mOrder) = Todo title completed order
where
title = fromMaybe "" mTitle
completed = fromMaybe False mCompleted
order = fromMaybe 0 mOrder
actionToUpdates :: TodoAction -> [Sqlite.Update Todo]
actionToUpdates act = updateTitle
++ updateCompl
++ updateOrd
where
updateTitle = maybe [] (\title -> [TodoTitle Sqlite.=. title])
(actTitle act)
updateCompl = maybe [] (\compl -> [TodoCompleted Sqlite.=. compl])
(actCompleted act)
updateOrd = maybe [] (\ord -> [TodoOrder Sqlite.=. ord])
(actOrder act)
allowCors :: Middleware
allowCors = addHeaders [
("Access-Control-Allow-Origin", "*"),
("Access-Control-Allow-Headers", "Accept, Content-Type"),
("Access-Control-Allow-Methods", "GET, HEAD, POST, DELETE, OPTIONS, PUT, PATCH")
]
allowOptions :: Middleware
allowOptions app req resp = case requestMethod req of
"OPTIONS" -> resp $ responseLBS status200 [] "Ok"
_ -> app req resp
type TodoApi = "todos" :> Get '[JSON] [Sqlite.Entity Todo]
:<|> "todos" :> Delete '[JSON] ()
:<|> "todos" :> ReqBody '[JSON] TodoAction :> Post '[JSON] (Sqlite.Entity Todo)
:<|> "todos" :> Capture "todoid" Integer :> Get '[JSON] (Sqlite.Entity Todo)
:<|> "todos" :> Capture "todoid" Integer :> Delete '[JSON] ()
:<|> "todos" :> Capture "todoid" Integer :> ReqBody '[JSON] TodoAction :> Patch '[JSON] (Sqlite.Entity Todo)
todoApi :: Proxy TodoApi
todoApi = Proxy
getTodos :: EitherT ServantErr IO [Sqlite.Entity Todo]
getTodos = liftIO $ runDb $ DB.selectList [] ([] :: [Sqlite.SelectOpt Todo])
deleteTodos :: EitherT ServantErr IO ()
deleteTodos = liftIO $ runDb $ DB.deleteWhere ([] :: [Sqlite.Filter Todo])
getTodo :: Integer -> EitherT ServantErr IO (Sqlite.Entity Todo)
getTodo tid = do
let tKey = Sqlite.toSqlKey (fromIntegral tid)
Just todo <- liftIO $ runDb $ DB.get tKey
return $ Sqlite.Entity tKey todo
deleteTodo :: Integer -> EitherT ServantErr IO ()
deleteTodo tid = do
let tKey = Sqlite.toSqlKey (fromIntegral tid)
liftIO $ runDb $ DB.delete (tKey :: Sqlite.Key Todo)
postTodo :: TodoAction -> EitherT ServantErr IO (Sqlite.Entity Todo)
postTodo todoAct = do
let todo = actionToTodo todoAct
tid <- liftIO $ runDb $ DB.insert todo
return $ Sqlite.Entity tid todo
patchTodo :: Integer -> TodoAction -> EitherT ServantErr IO (Sqlite.Entity Todo)
patchTodo tid todoAct = do
let tKey = Sqlite.toSqlKey (fromIntegral tid)
updates = actionToUpdates todoAct
todo <- liftIO $ runDb $ DB.updateGet tKey updates
return $ Sqlite.Entity tKey todo
server :: Server TodoApi
server = getTodos
:<|> deleteTodos
:<|> postTodo
:<|> getTodo
:<|> deleteTodo
:<|> patchTodo
waiApp :: Application
waiApp = allowCors $ allowOptions $ serve todoApi server
main :: IO ()
main = do
runDb $ Sqlite.runMigration migrateAll
port <- read <$> getEnv "PORT"
run port waiApp
| jhedev/todobackend-servant | src/Main.hs | mit | 5,848 | 0 | 24 | 1,583 | 1,626 | 851 | 775 | 132 | 2 |
{-# OPTIONS_GHC -XTypeFamilies -XRank2Types #-}
{-| This library provides a collection of monad transformers that
can be combined to produce various monads.
-}
module MonadLib (
-- * Types
-- $Types
Id, Lift, IdT, ReaderT, WriterT, StateT, ExceptionT, ChoiceT, ContT,
-- * Lifting
-- $Lifting
MonadT(..), HasBase(..),
-- * Effect Classes
-- $Effects
ReaderM(..), WriterM(..), StateM(..), ExceptionM(..), ContM(..),
Label, labelCC, jump,
-- * Execution
-- ** Eliminating Effects
-- $Execution
runId, runLift,
runIdT, runReaderT, runWriterT, runStateT, runExceptionT, runContT,
runChoiceT, findOne, findAll,
-- ** Nested Execution
-- $Nested_Exec
RunReaderM(..), RunWriterM(..), RunExceptionM(..),
-- * Deriving functions
Iso(..), derive_fmap, derive_return, derive_bind, derive_fail, derive_mfix,
derive_ask, derive_put, derive_get, derive_set, derive_raise, derive_callCC,
derive_local, derive_collect, derive_try,
derive_mzero, derive_mplus,
derive_lift, derive_inBase,
-- * Miscellaneous
version,
module Control.Monad
) where
import Control.Monad
import Control.Monad.Fix
import Data.Monoid
import Prelude hiding (Ordering(..))
-- | The current version of the library.
version :: (Int,Int,Int)
version = (3,4,0)
-- $Types
--
-- The following types define the representations of the
-- computation types supported by the library.
-- Each type adds support for a different effect.
-- | Computations with no effects.
newtype Id a = I a
-- | Computation with no effects (strict).
data Lift a = L a
-- | Add nothing. Useful as a placeholder.
newtype IdT m a = IT (m a)
-- | Add support for propagating a context.
newtype ReaderT i m a = R (i -> m a)
-- | Add support for collecting values.
newtype WriterT i m a = W (m (a,i))
-- | Add support for threading state.
newtype StateT i m a = S (i -> m (a,i))
-- | Add support for exceptions.
newtype ExceptionT i m a = X (m (Either i a))
-- | Add support for multiple answers.
data ChoiceT m a = NoAnswer
| Answer a
| Choice (ChoiceT m a) (ChoiceT m a)
| ChoiceEff (m (ChoiceT m a))
-- | Add support for jumps.
newtype ContT i m a = C ((a -> m i) -> m i)
-- $Execution
--
-- The following functions eliminate the outermost effect
-- of a computation by translating a computation into an
-- equivalent computation in the underlying monad.
-- (The exceptions are 'Id' and 'Lift' which are not transformers
-- but ordinary monas and so, their run operations simply
-- eliminate the monad.)
-- | Get the result of a pure computation.
runId :: Id a -> a
runId (I a) = a
-- | Get the result of a pure strict computation.
runLift :: Lift a -> a
runLift (L a) = a
-- | Remove an identity layer.
runIdT :: IdT m a -> m a
runIdT (IT a) = a
-- | Execute a reader computation in the given context.
runReaderT :: i -> ReaderT i m a -> m a
runReaderT i (R m) = m i
-- | Execute a writer computation.
-- Returns the result and the collected output.
runWriterT :: WriterT i m a -> m (a,i)
runWriterT (W m) = m
-- | Execute a stateful computation in the given initial state.
-- The second component of the result is the final state.
runStateT :: i -> StateT i m a -> m (a,i)
runStateT i (S m) = m i
-- | Execute a computation with exceptions.
-- Successful results are tagged with 'Right',
-- exceptional results are tagged with 'Left'.
runExceptionT :: ExceptionT i m a -> m (Either i a)
runExceptionT (X m) = m
-- | Execute a computation that may return multiple answers.
-- The resulting computation computation returns 'Nothing'
-- if no answers were found, or @Just (answer,new_comp)@,
-- where @answer@ is an answer, and @new_comp@ is a computation
-- that may produce more answers.
-- The search is depth-first and left-biased with respect to the
-- 'mplus' operation.
runChoiceT :: (Monad m) => ChoiceT m a -> m (Maybe (a,ChoiceT m a))
runChoiceT (Answer a) = return (Just (a,NoAnswer))
runChoiceT NoAnswer = return Nothing
runChoiceT (Choice l r) = do x <- runChoiceT l
case x of
Nothing -> runChoiceT r
Just (a,l1) -> return (Just (a,Choice l1 r))
runChoiceT (ChoiceEff m) = runChoiceT =<< m
-- | Execute a computation that may return multiple answers,
-- returning at most one answer.
findOne :: (Monad m) => ChoiceT m a -> m (Maybe a)
findOne m = fmap fst `liftM` runChoiceT m
-- | Executie a computation that may return multiple answers,
-- collecting all possible answers.
findAll :: (Monad m) => ChoiceT m a -> m [a]
findAll m = all =<< runChoiceT m
where all Nothing = return []
all (Just (a,as)) = (a:) `liftM` findAll as
-- | Execute a computation with the given continuation.
runContT :: (a -> m i) -> ContT i m a -> m i
runContT i (C m) = m i
-- $Lifting
--
-- The following operations allow us to promote computations
-- in the underlying monad to computations that support an extra
-- effect. Computations defined in this way do not make use of
-- the new effect but can be combined with other operations that
-- utilize the effect.
class MonadT t where
-- | Promote a computation from the underlying monad.
lift :: (Monad m) => m a -> t m a
-- It is interesting to note that these use something the resembles
-- the non-transformer 'return's.
instance MonadT IdT where lift m = IT m
instance MonadT (ReaderT i) where lift m = R (\_ -> m)
instance MonadT (StateT i) where lift m = S (\s -> liftM (\a -> (a,s)) m)
instance (Monoid i) =>
MonadT (WriterT i) where lift m = W (liftM (\a -> (a,mempty)) m)
instance MonadT (ExceptionT i) where lift m = X (liftM Right m)
instance MonadT ChoiceT where lift m = ChoiceEff (liftM Answer m)
instance MonadT (ContT i) where lift m = C (m >>=)
class Monad m => HasBase m where
type BaseM m :: * -> * -- How to specify: Monad (Base m)
-- | Promote a computation from the base monad.
inBase :: BaseM m a -> m a
instance HasBase IO where type BaseM IO = IO; inBase = id
instance HasBase Maybe where type BaseM Maybe = Maybe; inBase = id
instance HasBase [] where type BaseM [] = []; inBase = id
instance HasBase Id where type BaseM Id = Id; inBase = id
instance HasBase Lift where type BaseM Lift = Lift; inBase = id
instance HasBase m => HasBase (IdT m) where
type BaseM (IdT m) = BaseM m
inBase m = lift (inBase m)
instance (HasBase m) => HasBase (ReaderT i m) where
type BaseM (ReaderT i m) = BaseM m
inBase m = lift (inBase m)
instance (HasBase m) => HasBase (StateT i m) where
type BaseM (StateT i m) = BaseM m
inBase m = lift (inBase m)
instance (HasBase m,Monoid i) => HasBase (WriterT i m) where
type BaseM (WriterT i m) = BaseM m
inBase m = lift (inBase m)
instance (HasBase m) => HasBase (ExceptionT i m) where
type BaseM (ExceptionT i m) = BaseM m
inBase m = lift (inBase m)
instance (HasBase m) => HasBase (ChoiceT m) where
type BaseM (ChoiceT m) = BaseM m
inBase m = lift (inBase m)
instance (HasBase m) => HasBase (ContT i m) where
type BaseM (ContT i m) = BaseM m
inBase m = lift (inBase m)
instance Monad Id where
return x = I x
fail x = error x
m >>= k = k (runId m)
instance Monad Lift where
return x = L x
fail x = error x
L x >>= k = k x
-- For the monad transformers, the definition of 'return'
-- is completely determined by the 'lift' operations.
-- None of the transformers make essential use of the 'fail' method.
-- Instead they delegate its behavior to the underlying monad.
instance (Monad m) => Monad (IdT m) where
return x = lift (return x)
fail x = lift (fail x)
m >>= k = IT (runIdT m >>= (runIdT . k))
instance (Monad m) => Monad (ReaderT i m) where
return x = lift (return x)
fail x = lift (fail x)
m >>= k = R (\r -> runReaderT r m >>= \a -> runReaderT r (k a))
instance (Monad m) => Monad (StateT i m) where
return x = lift (return x)
fail x = lift (fail x)
m >>= k = S (\s -> runStateT s m >>= \ ~(a,s') -> runStateT s' (k a))
instance (Monad m,Monoid i) => Monad (WriterT i m) where
return x = lift (return x)
fail x = lift (fail x)
m >>= k = W $ runWriterT m >>= \ ~(a,w1) ->
runWriterT (k a) >>= \ ~(b,w2) ->
return (b,mappend w1 w2)
instance (Monad m) => Monad (ExceptionT i m) where
return x = lift (return x)
fail x = lift (fail x)
m >>= k = X $ runExceptionT m >>= \a ->
case a of
Left x -> return (Left x)
Right a -> runExceptionT (k a)
instance (Monad m) => Monad (ChoiceT m) where
return x = Answer x
fail x = lift (fail x)
Answer a >>= k = k a
NoAnswer >>= _ = NoAnswer
Choice m1 m2 >>= k = Choice (m1 >>= k) (m2 >>= k)
ChoiceEff m >>= k = ChoiceEff (liftM (>>= k) m)
instance (Monad m) => Monad (ContT i m) where
return x = lift (return x)
fail x = lift (fail x)
m >>= k = C $ \c -> runContT (\a -> runContT c (k a)) m
instance Functor Id where fmap = liftM
instance Functor Lift where fmap = liftM
instance (Monad m) => Functor (IdT m) where fmap = liftM
instance (Monad m) => Functor (ReaderT i m) where fmap = liftM
instance (Monad m) => Functor (StateT i m) where fmap = liftM
instance (Monad m,Monoid i) => Functor (WriterT i m) where fmap = liftM
instance (Monad m) => Functor (ExceptionT i m) where fmap = liftM
instance (Monad m) => Functor (ChoiceT m) where fmap = liftM
instance (Monad m) => Functor (ContT i m) where fmap = liftM
-- $Monadic_Value_Recursion
--
-- Recursion that does not duplicate side-effects.
-- For details see Levent Erkok's dissertation.
--
-- Monadic types built with 'ContT' do not support
-- monadic value recursion.
instance MonadFix Id where
mfix f = let m = f (runId m) in m
instance MonadFix Lift where
mfix f = let m = f (runLift m) in m
instance (MonadFix m) => MonadFix (IdT m) where
mfix f = IT (mfix (runIdT . f))
instance (MonadFix m) => MonadFix (ReaderT i m) where
mfix f = R $ \r -> mfix (runReaderT r . f)
instance (MonadFix m) => MonadFix (StateT i m) where
mfix f = S $ \s -> mfix (runStateT s . f . fst)
instance (MonadFix m,Monoid i) => MonadFix (WriterT i m) where
mfix f = W $ mfix (runWriterT . f . fst)
-- No instance for ChoiceT
instance (MonadFix m) => MonadFix (ExceptionT i m) where
mfix f = X $ mfix (runExceptionT . f . fromRight)
where fromRight (Right a) = a
fromRight _ = error "ExceptionT: mfix looped."
-- No instance for ContT
instance (MonadPlus m) => MonadPlus (IdT m) where
mzero = lift mzero
mplus (IT m) (IT n) = IT (mplus m n)
instance (MonadPlus m) => MonadPlus (ReaderT i m) where
mzero = lift mzero
mplus (R m) (R n) = R (\r -> mplus (m r) (n r))
instance (MonadPlus m) => MonadPlus (StateT i m) where
mzero = lift mzero
mplus (S m) (S n) = S (\s -> mplus (m s) (n s))
instance (MonadPlus m,Monoid i) => MonadPlus (WriterT i m) where
mzero = lift mzero
mplus (W m) (W n) = W (mplus m n)
instance (MonadPlus m) => MonadPlus (ExceptionT i m) where
mzero = lift mzero
mplus (X m) (X n) = X (mplus m n)
instance (Monad m) => MonadPlus (ChoiceT m) where
mzero = NoAnswer
mplus m n = Choice m n
-- Alternatives share the continuation.
instance (MonadPlus m) => MonadPlus (ContT i m) where
mzero = lift mzero
mplus (C m) (C n) = C (\k -> m k `mplus` n k)
-- $Effects
--
-- The following classes define overloaded operations
-- that can be used to define effectful computations.
-- | Classifies monads that provide access to a context of type @i@.
class (Monad m) => ReaderM m where
type Reads m
-- | Get the context.
ask :: m (Reads m)
instance (Monad m) => ReaderM (ReaderT i m) where
type Reads (ReaderT i m) = i
ask = R return
instance (ReaderM m) => ReaderM (IdT m) where
type Reads (IdT m) = Reads m
ask = lift ask
instance (ReaderM m, Monoid i) => ReaderM (WriterT i m) where
type Reads (WriterT i m) = Reads m
ask = lift ask
instance (ReaderM m) => ReaderM (StateT i m) where
type Reads (StateT i m) = Reads m
ask = lift ask
instance (ReaderM m) => ReaderM (ExceptionT i m) where
type Reads (ExceptionT i m) = Reads m
ask = lift ask
instance (ReaderM m) => ReaderM (ChoiceT m) where
type Reads (ChoiceT m) = Reads m
ask = lift ask
instance (ReaderM m) => ReaderM (ContT i m) where
type Reads (ContT i m) = Reads m
ask = lift ask
-- t
-- | Classifies monads that can collect values.
class (Monad m) => WriterM m where
-- | The types of the collection that we modify.
type Writes m
-- | Add a value to the collection.
put :: Writes m -> m ()
instance (Monad m,Monoid i) => WriterM (WriterT i m) where
type Writes (WriterT i m) = i
put x = W (return ((),x))
instance (WriterM m) => WriterM (IdT m) where
type Writes (IdT m) = Writes m
put x = lift (put x)
instance (WriterM m) => WriterM (ReaderT i m) where
type Writes (ReaderT i m) = Writes m
put x = lift (put x)
instance (WriterM m) => WriterM (StateT i m) where
type Writes (StateT i m) = Writes m
put x = lift (put x)
instance (WriterM m) => WriterM (ExceptionT i m) where
type Writes (ExceptionT i m) = Writes m
put x = lift (put x)
instance (WriterM m) => WriterM (ChoiceT m) where
type Writes (ChoiceT m) = Writes m
put x = lift (put x)
instance (WriterM m) => WriterM (ContT i m) where
type Writes (ContT i m) = Writes m
put x = lift (put x)
-- | Classifies monads that propagate a state component.
class (Monad m) => StateM m where
-- | The type of the state.
type State m
-- | Get the state.
get :: m (State m)
-- | Set the state.
set :: State m -> m ()
instance (Monad m) => StateM (StateT i m) where
type State (StateT i m) = i
get = S (\s -> return (s,s))
set s = S (\_ -> return ((),s))
instance (StateM m) => StateM (IdT m) where
type State (IdT m) = State m
get = lift get
set s = lift (set s)
instance (StateM m) => StateM (ReaderT i m) where
type State (ReaderT i m) = State m
get = lift get
set s = lift (set s)
instance (StateM m,Monoid i) => StateM (WriterT i m) where
type State (WriterT i m) = State m
get = lift get
set s = lift (set s)
instance (StateM m) => StateM (ExceptionT i m) where
type State (ExceptionT i m) = State m
get = lift get
set s = lift (set s)
instance (StateM m) => StateM (ChoiceT m) where
type State (ChoiceT m) = State m
get = lift get
set s = lift (set s)
instance (StateM m) => StateM (ContT i m) where
type State (ContT i m) = State m
get = lift get
set s = lift (set s)
-- | Classifies monads that support raising exceptions.
class (Monad m) => ExceptionM m where
-- | The type of the exceptions.
type Exception m
-- | Raise an exception.
raise :: Exception m -> m a
instance (Monad m) => ExceptionM (ExceptionT i m) where
type Exception (ExceptionT i m) = i
raise x = X (return (Left x))
instance (ExceptionM m) => ExceptionM (IdT m) where
type Exception (IdT m) = Exception m
raise x = lift (raise x)
instance (ExceptionM m) => ExceptionM (ReaderT i m) where
type Exception (ReaderT i m) = Exception m
raise x = lift (raise x)
instance (ExceptionM m,Monoid i) => ExceptionM (WriterT i m) where
type Exception (WriterT i m) = Exception m
raise x = lift (raise x)
instance (ExceptionM m) => ExceptionM (StateT i m) where
type Exception (StateT i m) = Exception m
raise x = lift (raise x)
instance (ExceptionM m) => ExceptionM (ChoiceT m) where
type Exception (ChoiceT m) = Exception m
raise x = lift (raise x)
instance (ExceptionM m) => ExceptionM (ContT i m) where
type Exception (ContT i m) = Exception m
raise x = lift (raise x)
-- The following instances differ from the others because the
-- liftings are not as uniform (although they certainly follow a pattern).
-- | Classifies monads that provide access to a computation's continuation.
class Monad m => ContM m where
-- | Capture the current continuation.
callCC :: ((a -> m b) -> m a) -> m a
instance (ContM m) => ContM (IdT m) where
callCC f = IT $ callCC $ \k -> runIdT $ f $ \a -> lift $ k a
instance (ContM m) => ContM (ReaderT i m) where
callCC f = R $ \r -> callCC $ \k -> runReaderT r $ f $ \a -> lift $ k a
instance (ContM m) => ContM (StateT i m) where
callCC f = S $ \s -> callCC $ \k -> runStateT s $ f $ \a -> lift $ k (a,s)
instance (ContM m,Monoid i) => ContM (WriterT i m) where
callCC f = W $ callCC $ \k -> runWriterT $ f $ \a -> lift $ k (a,mempty)
instance (ContM m) => ContM (ExceptionT i m) where
callCC f = X $ callCC $ \k -> runExceptionT $ f $ \a -> lift $ k $ Right a
instance (ContM m) => ContM (ChoiceT m) where
callCC f = ChoiceEff $ callCC $ \k -> return $ f $ \a -> lift $ k $ Answer a
-- ??? What does this do ???
instance (Monad m) => ContM (ContT i m) where
callCC f = C $ \k -> runContT k $ f $ \a -> C $ \_ -> k a
-- $Nested_Exec
--
-- The following classes define operations that are overloaded
-- versions of the @run@ operations. Unlike the @run@ operations,
-- these functions do not change the type of the computation (i.e, they
-- do not remove a layer). Instead, they perform the effects in
-- a ``separate effect thread''.
-- | Classifies monads that support changing the context for a
-- sub-computation.
class ReaderM m => RunReaderM m where
-- | Change the context for the duration of a computation.
local :: Reads m -> m a -> m a
-- prop(?): local i (m1 >> m2) = local i m1 >> local i m2
instance (Monad m) => RunReaderM (ReaderT i m) where
local i m = lift (runReaderT i m)
instance (RunReaderM m) => RunReaderM (IdT m) where
local i (IT m) = IT (local i m)
instance (RunReaderM m,Monoid i) => RunReaderM (WriterT i m) where
local i (W m) = W (local i m)
instance (RunReaderM m) => RunReaderM (StateT i m)where
local i (S m) = S (local i . m)
instance (RunReaderM m) => RunReaderM (ExceptionT i m) where
local i (X m) = X (local i m)
-- | Classifies monads that support collecting the output of
-- a sub-computation.
class WriterM m => RunWriterM m where
-- | Collect the output from a computation.
collect :: m a -> m (a,Writes m)
instance (Monad m, Monoid i) => RunWriterM (WriterT i m) where
collect m = lift (runWriterT m)
instance (RunWriterM m) => RunWriterM (IdT m) where
collect (IT m) = IT (collect m)
instance (RunWriterM m) => RunWriterM (ReaderT i m) where
collect (R m) = R (collect . m)
instance (RunWriterM m) => RunWriterM (StateT i m) where
collect (S m) = S (liftM swap . collect . m)
where swap (~(a,s),w) = ((a,w),s)
instance (RunWriterM m) => RunWriterM (ExceptionT i m) where
collect (X m) = X (liftM swap (collect m))
where swap (Right a,w) = Right (a,w)
swap (Left x,_) = Left x
-- NOTE: if an exception is risen while we are collecting,
-- then we ignore the output. If the output is important,
-- then use 'try' to ensure that no exception may occur.
-- Example: do (r,w) <- collect (try m)
-- case r of
-- Left err -> ... do something ...
-- Right a -> ... do something ...
-- | Classifies monads that support handling of exceptions.
class ExceptionM m => RunExceptionM m where
-- | Exceptions are explicit in the result.
try :: m a -> m (Either (Exception m) a)
instance (Monad m) => RunExceptionM (ExceptionT i m) where
try m = lift (runExceptionT m)
instance (RunExceptionM m) => RunExceptionM (IdT m) where
try (IT m) = IT (try m)
instance (RunExceptionM m) => RunExceptionM (ReaderT j m) where
try (R m) = R (try . m)
instance (RunExceptionM m,Monoid j) => RunExceptionM (WriterT j m) where
try (W m) = W (liftM swap (try m))
where swap (Right ~(a,w)) = (Right a,w)
swap (Left e) = (Left e, mempty)
instance (RunExceptionM m) => RunExceptionM (StateT j m) where
try (S m) = S (\s -> liftM (swap s) (try (m s)))
where swap _ (Right ~(a,s)) = (Right a,s)
swap s (Left e) = (Left e, s)
--------------------------------------------------------------------------------
-- Some convenient functions for working with continuations.
-- | An explicit representation for continuations that store a value.
newtype Label m a = Lab ((a, Label m a) -> m ())
-- | Capture the current continuation
-- This function is like 'return', except that it also captures
-- the current continuation. Later we can use 'jump' to go back to
-- the continuation with a possibly different value.
labelCC :: (ContM m) => a -> m (a, Label m a)
labelCC x = callCC (\k -> return (x, Lab k))
-- | Change the value passed to a previously captured continuation.
jump :: (ContM m) => a -> Label m a -> m b
jump x (Lab k) = k (x, Lab k) >> return unreachable
where unreachable = error "(bug) jump: unreachable"
--------------------------------------------------------------------------------
-- | A isomorphism between (usually) monads.
-- Typically the constructor and selector of a newtype delcaration.
data Iso m n = Iso { close :: forall a. m a -> n a,
open :: forall a. n a -> m a }
-- | Derive the implementation of 'fmap' from 'Functor'.
derive_fmap :: (Functor m) => Iso m n -> (a -> b) -> n a -> n b
derive_fmap iso f m = close iso (fmap f (open iso m))
-- | Derive the implementation of 'return' from 'Monad'.
derive_return :: (Monad m) => Iso m n -> (a -> n a)
derive_return iso a = close iso (return a)
-- | Derive the implementation of '>>=' from 'Monad'.
derive_bind :: (Monad m) => Iso m n -> n a -> (a -> n b) -> n b
derive_bind iso m k = close iso ((open iso m) >>= \x -> open iso (k x))
derive_fail :: (Monad m) => Iso m n -> String -> n a
derive_fail iso a = close iso (fail a)
-- | Derive the implementation of 'mfix' from 'MonadFix'.
derive_mfix :: (MonadFix m) => Iso m n -> (a -> n a) -> n a
derive_mfix iso f = close iso (mfix (open iso . f))
-- | Derive the implementation of 'ask' from 'ReaderM'.
derive_ask :: (ReaderM m) => Iso m n -> n (Reads m)
derive_ask iso = close iso ask
-- | Derive the implementation of 'put' from 'WriterM'.
derive_put :: (WriterM m) => Iso m n -> Writes m -> n ()
derive_put iso x = close iso (put x)
-- | Derive the implementation of 'get' from 'StateM'.
derive_get :: (StateM m) => Iso m n -> n (State m)
derive_get iso = close iso get
-- | Derive the implementation of 'set' from 'StateM'.
derive_set :: (StateM m) => Iso m n -> State m -> n ()
derive_set iso x = close iso (set x)
-- | Derive the implementation of 'raise' from 'ExceptionM'.
derive_raise :: (ExceptionM m) => Iso m n -> Exception m -> n a
derive_raise iso x = close iso (raise x)
-- | Derive the implementation of 'callCC' from 'ContM'.
derive_callCC :: (ContM m) => Iso m n -> ((a -> n b) -> n a) -> n a
derive_callCC iso f = close iso (callCC (open iso . f . (close iso .)))
-- | Derive the implementation of 'local' from 'RunReaderM'.
derive_local :: (RunReaderM m) => Iso m n -> Reads m -> n a -> n a
derive_local iso i = close iso . local i . open iso
-- | Derive the implementation of 'collect' from 'RunWriterM'.
derive_collect :: (RunWriterM m) => Iso m n -> n a -> n (a,Writes m)
derive_collect iso = close iso . collect . open iso
-- | Derive the implementation of 'try' from 'RunExceptionM'.
derive_try :: (RunExceptionM m) => Iso m n -> n a -> n (Either (Exception m) a)
derive_try iso = close iso . try . open iso
derive_mzero :: (MonadPlus m) => Iso m n -> n a
derive_mzero iso = close iso mzero
derive_mplus :: (MonadPlus m) => Iso m n -> n a -> n a -> n a
derive_mplus iso n1 n2 = close iso (mplus (open iso n1) (open iso n2))
derive_lift :: (MonadT t, Monad m) => Iso (t m) n -> m a -> n a
derive_lift iso m = close iso (lift m)
derive_inBase :: (HasBase m) => Iso m n -> BaseM m a -> n a
derive_inBase iso m = close iso (inBase m)
| yav/monadlib | experimental/MonadLibTF.hs | mit | 24,318 | 0 | 14 | 6,099 | 9,100 | 4,718 | 4,382 | -1 | -1 |
module Main
( main
) where
{-
Automatic solver for Android game "tents & trees"
-}
{-
Design: for now I think the most difficult part will be,
given an image, to recognize board position and
extract board configuration from it.
good old matchTemplate should work, but here I want to see
if there are better ways that is not sensitive to scaling
so that a method works for 10x10 board will also work for 20x20 board.
Questions:
- how to extract and recognize trees and empty spaces?
For simplicity, let's only work on a clean board (that is, no empty or tent marked).
This is currently done based on the fact that all empty cells use the exact same color,
so the region can be extracted with OpenCV's inRange function, after which we can floodFill
to find boundaries of empty cells can use that to derive row and col coordinates of the board.
Board's position (or we should say each cell's position) is straightforward to figure out
after we derive bounding low/high for each cell's row and col.
a reasonable (but not safe) assumption that we use here is that:
+ there will always be some empty spaces on board for each row and col.
+ every boundary will have at least one empty cell.
- how to extract and recognize digits on board sides?
This is now done by guessing: given first two cells of a row or column,
we extend cell boundary in the other direction - as it turns out that
all digits happen to be placed in that region.
(TODO) Quick notes:
- there are two different colors for digits:
+ one color is consistently used for unsatisfied digits
+ another color is consistently used for satisfied digits,
and satistifed digits are trickier to recognoze as there's an extra check mark character
that we want to exclude.
- for unsatisfied digits, the plan is simple: run through inRange by filtering on just that unsatisfied color,
the we can find boundary of it and extract those as samples
- for satisfied digits, well since that row / col is already satisfied, we can derive what that number is from
the board itself. The board parsing function might need some modification, but I believe we can entirely
ignore the problem of recognizing digits from picture.
-}
main :: IO ()
main = pure ()
| Javran/misc | auto-tents/src/Main.hs | mit | 2,344 | 0 | 6 | 546 | 31 | 18 | 13 | 4 | 1 |
module Part2 where
import Control.Monad
data Item = Item { name :: String, description :: String, weight :: Int, value :: Int } |
Weapon { name :: String, description :: String, weight :: Int, value :: Int, damage :: Int } |
Armor { name :: String, description :: String, weight :: Int, value :: Int, defense :: Int } |
Potion { name :: String, description :: String, weight :: Int, value :: Int, potionType :: PotionType, capacity :: Int }
deriving ( Show )
data PotionType = HP | MP
instance Show PotionType where
show HP = "Health"
show MP = "Mana"
data Shop = Shop { shopName :: String, shopItems :: Items }
type Items = [Item]
main :: IO ()
main = do
printMenu
input <- getLine
play $ read input
Control.Monad.unless (read input == 3) main
printMenu :: IO ()
printMenu = do
putStrLn "- Shop Select -"
putStrLn " 1. Weapon/Armor Shop"
putStrLn " 2. Potion Shop"
putStrLn " 3. Exit\n"
putStr "Select : "
return ()
play :: Int -> IO ()
play n
| n == 1 = showItemList weaponAndArmorShop
| n == 2 = showItemList potionShop
| n == 3 = return ()
| otherwise = putStrLn "\nInvalid number! Try again.\n"
testCase1 = describe items
describe :: Items -> IO ()
describe = mapM_ (putStrLn . toString)
toString :: Item -> String
toString (Item name description weight value) = baseInfo (Item name description weight value)
toString (Weapon name description weight value damage) = baseInfo (Item name description weight value) ++
"Damage = " ++ show damage ++ "\n"
toString (Armor name description weight value defense) = baseInfo (Item name description weight value) ++
"Defense = " ++ show defense ++ "\n"
toString (Potion name description weight value potionType capacity) = baseInfo (Item name description weight value) ++
"Type = " ++ show potionType ++ "\n" ++
"Capacity = " ++ show capacity ++ "\n"
baseInfo :: Item -> String
baseInfo item = "Name = " ++ name item ++ "\n" ++
"Description = " ++ description item ++ "\n" ++
"Weight = " ++ w'' ++ "\n" ++
"value = " ++ v'' ++ "\n"
where
w = weight item
v = value item
w' = show w
v' = show v
w''
| w > 1 = w' ++ " lbs"
| otherwise = w' ++ " lb"
v''
| v > 1 = v' ++ " gold coins"
| otherwise = v' ++ " gold coin"
showItemList :: Shop -> IO ()
showItemList shop = do
putStrLn $ "Welcom to " ++ shopName shop ++ "!\n"
describe $ shopItems shop
putStrLn "\n"
items = [
Weapon { name = "Excalibur", description = "The legendary sword of King Arthur", weight = 12, value = 1024, damage = 24 },
Armor { name = "Steel Armor", description = "Protective covering made by steel", weight = 15, value = 805, defense = 18}
]
weaponAndArmorShop = Shop { shopName = "Weapon/Armor", shopItems = [
Weapon { name = "Sword", description = "Medium DMG", weight = 3, value = 10, damage = 10 },
Armor { name = "Cap", description = "Light Armor", weight = 1, value = 5, defense = 5 },
Armor { name = "Gloves", description = "Light Armor", weight = 1, value = 5, defense = 5 },
Weapon { name = "Axe", description = "High Dmg", weight = 5, value = 15, damage = 15 },
Armor { name = "Boots", description = "Light Armor", weight = 1, value = 5, defense = 5 }
] }
potionShop = Shop { shopName = "Potion", shopItems = [
Potion { name = "Small Health Potion", description = "Recovery 100 HP", weight = 2, value = 5, potionType = HP, capacity = 100 },
Potion { name = "Small Mana Potion", description = "Recovery 50 MP", weight = 1, value = 30, potionType = MP, capacity = 50 },
Potion { name = "Medium Health Potion", description = "Recovery 200 HP", weight = 4, value = 120, potionType = HP, capacity = 200 },
Potion { name = "Medium Mana Potion", description = "Recovery 100 MP", weight = 2, value = 75, potionType = MP, capacity = 100 },
Potion { name = "Large Health Potion", description = "Recovery 300 HP", weight = 6, value = 200, potionType = HP, capacity = 300 }
] } | utilForever/ProgrammingPractice | Solutions/MoNaDDu/Game Shop/3/Part3.hs | mit | 4,510 | 0 | 16 | 1,456 | 1,382 | 776 | 606 | 80 | 1 |
module NeatInterpolation.String where
import NeatInterpolation.Prelude
unindent :: [Char] -> [Char]
unindent s =
case lines s of
head : tail ->
let
unindentedHead = dropWhile (== ' ') head
minimumTailIndent = minimumIndent . unlines $ tail
unindentedTail = case minimumTailIndent of
Just indent -> map (drop indent) tail
Nothing -> tail
in unlines $ unindentedHead : unindentedTail
[] -> []
trim :: [Char] -> [Char]
trim = dropWhileRev isSpace . dropWhile isSpace
dropWhileRev :: (a -> Bool) -> [a] -> [a]
dropWhileRev p = foldr (\x xs -> if p x && null xs then [] else x:xs) []
tabsToSpaces :: [Char] -> [Char]
tabsToSpaces ('\t' : tail) = " " ++ tabsToSpaces tail
tabsToSpaces (head : tail) = head : tabsToSpaces tail
tabsToSpaces [] = []
minimumIndent :: [Char] -> Maybe Int
minimumIndent =
listToMaybe . sort . map lineIndent
. filter (not . null . dropWhile isSpace) . lines
-- | Amount of preceding spaces on first line
lineIndent :: [Char] -> Int
lineIndent = length . takeWhile (== ' ')
| nikita-volkov/neat-interpolation | library/NeatInterpolation/String.hs | mit | 1,083 | 0 | 17 | 261 | 398 | 209 | 189 | 28 | 3 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.NavigatorUserMediaError
(js_getConstraintName, getConstraintName, NavigatorUserMediaError,
castToNavigatorUserMediaError, gTypeNavigatorUserMediaError)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"constraintName\"]"
js_getConstraintName :: NavigatorUserMediaError -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUserMediaError.constraintName Mozilla NavigatorUserMediaError.constraintName documentation>
getConstraintName ::
(MonadIO m, FromJSString result) =>
NavigatorUserMediaError -> m result
getConstraintName self
= liftIO (fromJSString <$> (js_getConstraintName (self))) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/NavigatorUserMediaError.hs | mit | 1,537 | 6 | 10 | 191 | 365 | 233 | 132 | 25 | 1 |
{-# LANGUAGE OverloadedStrings, FlexibleContexts, ScopedTypeVariables #-}
module ProcessStatus ( processStatuses
, RetryAPI(..)
) where
import Data.Conduit
import Data.Conduit.Binary
import qualified Data.Conduit.Attoparsec as CA
import Network.HTTP.Conduit
import qualified Web.Authenticate.OAuth as OA
import Data.Aeson
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString as B
import Data.List
import qualified Data.Vector as V
import Control.Monad.IO.Class
import Control.Monad.State.Strict
import Control.Monad.Trans.Resource
import Control.Concurrent.STM
import Control.Exception
import Control.Concurrent hiding (yield)
import Text.Printf
import Text.Read (readMaybe)
import System.IO
import TwitterJSON
import Trace
-- Pick up Twitter status updates and related messages from a file or an HTTP connection
-- and return the results as data structures from TwitterJSON
-- Put status messages in a TBQueue (TODO: Maybe use stm-conduit package?)
smQueueSink :: (MonadIO m, MonadResource m)
=> TBQueue StreamMessage
-> Sink StreamMessage m ()
smQueueSink smQueue = awaitForever $ liftIO . atomically . writeTBQueue smQueue
-- Count bytes passing through using the state (need to be careful that we don't
-- retain a reference to the ByteString in case we're not looking at the state
-- for a while)
--
-- TODO: We take the byte count after gzip decompression, so not really what goes
-- over the socket
countBytesState :: (MonadIO m, MonadState Int m) => Conduit B.ByteString m B.ByteString
countBytesState = awaitForever $ \mi -> do
modify' (\x -> B.length mi `seq` x + fromIntegral (B.length mi))
yield mi
parseStatus :: (MonadIO m, MonadState Int m, MonadResource m)
=> Conduit B.ByteString m StreamMessage
parseStatus = do
-- Bandwidth message for statistics
yield <$> SMBytesReceived =<< get
put 0
-- Use conduit adapter for attoparsec to read the next JSON
-- object with the Aeson parser from the stream connection
--
-- TODO: The performance we get is quite far away from the figures listed on
-- Aeson's cabal site, do some benchmarking and profiling
--
j <- CA.sinkParser json'
-- The stream connections send individual objects we can decode into SMs,
-- but the home timeline sends an array of such objects
let msg = case j of
Array v -> V.toList v
x -> [x]
forM_ msg $ \m -> do
-- We expect something that can be parsed into a StreamMessage
let sm = fromJSON m :: Result StreamMessage
yield $ case sm of
Success r -> r
Error s -> SMParseError $ B8.pack s
parseStatus
-- Like conduitFile from Conduit.Binary, but with extra options to control the write
-- mode and flushing
conduitFileWithOptions :: MonadResource m
=> FilePath
-> IOMode
-> Bool
-> Conduit B.ByteString m B.ByteString
conduitFileWithOptions fp mode flush =
bracketP
(openBinaryFile fp mode)
hClose
go
where
go h = awaitForever $ \bs -> liftIO (B.hPut h bs >> when flush (hFlush h)) >> yield bs
data RetryAPI = RetryNever
| RetryNTimes Int
| RetryForever -- This even retries in case of success
deriving (Eq)
-- Process status updates as returned from the REST or Stream API, write results into a queue
processStatuses :: String
-> OA.OAuth
-> OA.Credential
-> Manager
-> Maybe FilePath
-> Bool
-> TBQueue StreamMessage
-> RetryAPI
-> IO ()
processStatuses uri oaClient oaCredential manager logFn appendLog smQueue retryAPI = do
let uriIsHTTP = isPrefixOf "http://" uri || isPrefixOf "https://" uri -- File or HTTP?
success <- catches
( -- We use State to keep track of how many bytes we received
runResourceT . flip evalStateT (0 :: Int) $
let sink' = countBytesState =$ parseStatus =$ smQueueSink smQueue
sink = case logFn of Just fn -> conduitFileWithOptions
fn
(if appendLog then AppendMode else WriteMode)
True
=$ sink'
Nothing -> sink'
in if uriIsHTTP
then do -- Authenticate, connect and start receiving stream
req' <- liftIO $ parseUrl uri
let req = req' { requestHeaders =
("Accept-Encoding", "deflate, gzip")
-- Need a User-Agent field as well to get a
-- gzip'ed stream from Twitter
: ("User-Agent", "jacky/http-conduit")
: requestHeaders req'
}
reqSigned <- OA.signOAuth oaClient oaCredential req
liftIO . traceS TLInfo $ "Twitter API request:\n" ++ show reqSigned
res <- http reqSigned manager
liftIO . traceS TLInfo $ "Twitter API response from '" ++ uri ++ "'\n"
++ case logFn of Just fn -> "Saving full log in '"
++ fn ++ "'\n"
Nothing -> ""
++ "Status: " ++ show (responseStatus res)
++ "\n"
++ "Header: " ++ show (responseHeaders res)
-- Are we approaching the rate limit?
case find ((== "x-rate-limit-remaining") . fst) (responseHeaders res) >>=
readMaybe . B8.unpack . snd :: Maybe Int of
Just n -> when (n < 5) . liftIO . traceS TLWarn $ printf
"Rate limit remaining for API '%s' at %i" uri n
Nothing -> return ()
-- Finish parsing conduit
responseBody res $$+- sink
return True
else do liftIO . traceS TLInfo $ "Streaming Twitter API response from file: " ++ uri
sourceFile uri $$ sink
return True
)
[ Handler $ \(ex :: AsyncException) ->
case ex of
ThreadKilled -> do
traceS TLInfo $ "Recv. ThreadKilled while processing statuses from '"
++ uri ++ "', exiting\n" ++ show ex
void $ throwIO ex -- Clean exit, but re-throw so we're not trapped
-- inside RetryForever
return True
_ -> do
traceS TLError $ "Async exception while processing statuses from '"
++ uri ++ "\n" ++ show ex
return False
, Handler $ \(ex :: HttpException) -> do
traceS TLError $ "HTTP / connection error while processing statuses from '"
++ uri ++ "'\n" ++ show ex
return False
, Handler $ \(ex :: CA.ParseError) ->
if "demandInput" `elem` CA.errorContexts ex
then do traceS TLInfo $ "End-of-Data for '" ++ uri ++ "'\n" ++ show ex
return True -- This error is a clean exit
else do traceS TLError $ "JSON parser error while processing statuses from '"
++ uri ++ "'\n" ++ show ex
return False
, Handler $ \(ex :: IOException) -> do
traceS TLError $ "IO error while processing statuses from '"
++ uri ++ "'\n" ++ show ex
return False -- TODO: This exception is likely caused by a failure to read
-- a network dump from disk, we might not want to bother
-- trying again if it can't be opened
]
-- Do we need to retry?
case retryAPI of
RetryForever -> when uriIsHTTP $ do -- Don't retry forever if our source is a static file
traceS TLWarn $
retryMsg ++ " (forever)\nURI: " ++ uri
threadDelay retryDelay
retryThis RetryForever
RetryNTimes n -> when (not success && n > 0) $ do
traceS TLWarn $ retryMsg ++ "\n"
++ "Remaining retries: " ++ show n ++ "\n"
++ "URI: " ++ uri
threadDelay retryDelay
retryThis (RetryNTimes $ n - 1)
RetryNever -> return ()
where retryThis = processStatuses
uri
oaClient
oaCredential
manager
logFn
True -- Don't overwrite log data we've got so far
smQueue
retryDelay = 5 * 1000 * 1000 -- 5 seconds (TODO: Make this configurable)
retryMsg = printf "Retrying API request in %isec"
(retryDelay `div` 1000 `div` 1000)
| blitzcode/jacky | src/ProcessStatus.hs | mit | 10,047 | 0 | 26 | 4,354 | 1,739 | 885 | 854 | 160 | 10 |
{-# htermination concat :: [[a]] -> [a] #-}
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Prelude_concat_1.hs | mit | 44 | 0 | 2 | 8 | 3 | 2 | 1 | 1 | 0 |
{-# LANGUAGE TemplateHaskell #-}
-- Copyright (c) 2005,8 Jean-Philippe Bernardy
module Yi.KillRing (Killring
,krKilled
,krContents
,krEndCmd
,krPut
,krSet, krGet
,krEmpty
)
where
import Control.Monad (ap)
import Data.Binary
import Data.DeriveTH
import Data.Derive.Binary
import Yi.Buffer.Basic
data Killring = Killring { krKilled :: Bool
, krAccumulate :: Bool
, krContents :: [String]
, krLastYank :: Bool
}
deriving (Show)
$(derive makeBinary ''Killring)
maxDepth :: Int
maxDepth = 10
krEmpty :: Killring
krEmpty = Killring { krKilled = False
, krAccumulate = False
, krContents = [[]]
, krLastYank = False
}
-- | Finish an atomic command, for the purpose of killring accumulation.
krEndCmd :: Killring -> Killring
krEndCmd kr@Killring {krKilled = killed} = kr {krKilled = False, krAccumulate = killed }
-- | Put some text in the killring.
-- It's accumulated if the last command was a kill too
krPut :: Direction -> String -> Killring -> Killring
krPut dir s kr@Killring {krContents = r@(x:xs), krAccumulate=acc}
= kr {krKilled = True,
krContents = if acc then (case dir of
Forward -> x++s
Backward -> s++x):xs
else push s r}
krPut _ _ _ = error "killring invariant violated"
-- | Push a string in the killring.
push :: String -> [String] -> [String]
push s [] = [s]
push s r@(h:t) = s : if length h <= 1 then t else take maxDepth r
-- Don't save very small cutted text portions.
-- | Set the top of the killring. Never accumulate the previous content.
krSet :: String -> Killring -> Killring
krSet s kr@Killring {krContents = _:xs} = kr {krContents = s:xs}
krSet _ _ = error "killring invariant violated"
-- | Get the top of the killring.
krGet :: Killring -> String
krGet = head . krContents
| codemac/yi-editor | src/Yi/KillRing.hs | gpl-2.0 | 2,151 | 0 | 13 | 743 | 514 | 297 | 217 | 44 | 3 |
{-
The parser combinators used when reading in input as a DCFG.
This was created as Project 2 for EECS 665 at the University of Kansas.
Author: Ryan Scott
-}
module LR0ItemSet.Parse (parseGrammar) where
import Control.Applicative hiding ((<|>), many)
import Data.Char
import Data.Functor
import LR0ItemSet.Data
import Text.Parsec
import Text.Parsec.String
-- | Parses an uppercase letter as a nonterminal.
parseNonterminal :: Parser Nonterminal
parseNonterminal = Nonterm <$> satisfy isUpper
-- | Parses a non-uppercase, non-@, non-' character as a terminal.
parseTerminal :: Parser Terminal
parseTerminal = Term <$> satisfy isTermChar
-- | Parses either a nonterminal or a terminal.
parseSymbol :: Parser Symbol
parseSymbol = (SymbolTerm <$> try parseTerminal)
<|> (SymbolNonterm <$> parseNonterminal)
-- | Parses a production (i.e., E->E+T or T->).
parseProduction :: Parser Production
parseProduction = Production
<$> parseNonterminal
<* string "->"
-- Read symbols until a newline is encountered
<*> manyTill parseSymbol (void endOfLine <|> eof)
-- | Parses an entire deterministic context-free grammar.
parseGrammar :: Parser Grammar
parseGrammar = Grammar
<$> parseNonterminal
<* spaces
<*> manyTill parseProduction (try $ many endOfLine *> eof) | RyanGlScott/lr0-item-set | src/LR0ItemSet/Parse.hs | gpl-3.0 | 1,302 | 0 | 10 | 226 | 221 | 122 | 99 | 24 | 1 |
module Text.Gedcom.Parser
(gedcom)
where
import Control.Applicative
import Data.Attoparsec.ByteString.Char8
( Parser
, char
, isDigit
, string
)
import qualified Data.Attoparsec.ByteString.Char8 as AT
import Data.Attoparsec.Combinator
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as C8
import Data.CharSet (CharSet)
import qualified Data.CharSet as CS
import Data.Functor.Foldable (Fix(..))
import Text.Gedcom.Types hiding (xref, tag)
eol :: Parser ()
eol = AT.endOfLine
mkPred :: String -> (Char -> Bool)
mkPred xs = flip CS.member cs
where
cs = CS.fromList xs
mkPredInv :: String -> (Char -> Bool)
mkPredInv xs = flip CS.notMember cs
where
cs = CS.fromList xs
space :: Parser Char
space = char ' '
isAlpha = mkPred alphaChars
alpha :: Parser ByteString
alpha = AT.takeWhile isAlpha
alphaChars :: String
alphaChars = ['A' .. 'Z'] ++ ['a'..'z'] ++ "_"
anyChar :: Parser ByteString
anyChar = AT.takeWhile pred
where
pred = mkPredInv "\n"
data XRefState = Di | Ch
xref :: Parser XRef
xref = XRef <$ char '@' <*> AT.scan Ch g <* char '@'
where
g Ch x | isAlpha x = Just Ch
| isDigit x = Just Di
| otherwise = Nothing
g Di x = if isDigit x then Just Di else Nothing
payload :: Parser Payload
payload = option Null (space *> ((X <$> xref) <|> (B <$> anyChar)))
record :: Int -> Parser Records
record n = f <$ np <* space <*> alpha <*> payload <* eol <*> rs
where
np = nat n
rs = many . record $ n + 1
f tag p recs = Fix (TreeF (U (Record tag p)) recs)
zero :: Parser Char
zero = char '0'
nat :: Int -> Parser ()
nat n = () <$ string (C8.pack $ show n)
gedcom :: Parser Gedcom
gedcom = Gedcom <$ zero <* space <*> xref <* space <*> alpha <* eol <*> some (record 1)
| benjumanji/gedcom | src/Text/Gedcom/Parser.hs | gpl-3.0 | 1,784 | 0 | 13 | 399 | 706 | 376 | 330 | 54 | 3 |
-----------------------------------------------------------------------------
-- |
-- Module : Main
-- Copyright : (c) Gushcha Anton 2013-2014
-- License : GNU GPLv3 (see the file LICENSE)
--
-- Maintainer : ncrashed@gmail.com
-- Stability : experimental
-- Portability : portable
--
-- Startup PowerCom module. The main purpose is to create Cloud Haskell
-- transport system and initialize first layer (Application layer). User
-- can pass two arguments: default serial port name and default user name.
-----------------------------------------------------------------------------
module Main (main) where
import Paths_PowerCom
import Application.Layer
import Utility
import Control.Distributed.Process
import Control.Distributed.Process.Node
import Network.Transport.Chan
import System.Environment
-- | Main application function. Initializes application layer and waits
-- terminating command, also retrieves gui resource file and parses
-- input arguments for channel layer.
main :: IO ()
main = do
args <- getArgs
t <- createTransport
node <- newLocalNode t initRemoteTable
gladeFile <- getDataFileName "views/gui.glade"
runProcess node $ do
rootId <- getSelfPid
initApplicationLayer gladeFile (convertArgs args) rootId
while $ receiveWait [match exitMsg]
where
convertArgs args = case length args of
2 -> Just (head args, args !! 1)
_ -> Nothing | NCrashed/PowerCom | src/powercom/Main.hs | gpl-3.0 | 1,472 | 0 | 13 | 296 | 206 | 112 | 94 | 21 | 2 |
{---------------------------------------------------------------------}
{- Copyright 2015, 2016 Nathan Bloomfield -}
{- -}
{- This file is part of Feivel. -}
{- -}
{- Feivel is free software: you can redistribute it and/or modify -}
{- it under the terms of the GNU General Public License version 3, -}
{- as published by the Free Software Foundation. -}
{- -}
{- Feivel 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 Feivel. If not, see <http://www.gnu.org/licenses/>. -}
{---------------------------------------------------------------------}
module Feivel.Parse.Expr (
pDoc, pREPL,
pTypedExpr,
pTypedConst,
pStrConst, pIntConst, pBoolConst, pRatConst, pZZModConst,
pListLiteral, pMatLiteral, pPolyLiteral, pPermLiteral,
pTupleLiteral,
pDOC
) where
import Feivel.Store
import Feivel.Grammar
import Feivel.Parse.Util
import Feivel.Parse.ParseM
import Feivel.Parse.Int
import Feivel.Parse.Str
import Feivel.Parse.Rat
import Feivel.Parse.Bool
import Feivel.Parse.ZZMod
import Feivel.Parse.Perm
import Feivel.Parse.Poly
import Feivel.Parse.Mat
import Feivel.Parse.List
import Feivel.Parse.Doc
import Feivel.Parse.Mac
import Feivel.Parse.Tuple
import Text.ParserCombinators.Parsec hiding (try)
import Text.Parsec.Prim (try)
{---------------}
{- Contents -}
{- :Expr -}
{- :REPL -}
{---------------}
pINT :: ParseM IntExpr
pINT = pIntExpr pTypedExpr parserDict
pSTR :: ParseM StrExpr
pSTR = pStrExpr pTypedExpr parserDict
pBOOL :: ParseM BoolExpr
pBOOL = pBoolExpr pTypedExpr parserDict
pRAT :: ParseM RatExpr
pRAT = pRatExpr pTypedExpr parserDict
pMOD :: Integer -> ParseM ZZModExpr
pMOD n = pZZModExpr pTypedExpr n parserDict
pLIST :: Type -> ParseM ListExpr
pLIST typ = pTypedListExpr typ pTypedExpr parserDict
pTUPLE :: [Type] -> ParseM TupleExpr
pTUPLE typs = pTypedTupleExpr typs pTypedExpr parserDict
pMAT :: Type -> ParseM MatExpr
pMAT typ = pTypedMatExpr typ pTypedExpr parserDict
pPOLY :: Type -> ParseM PolyExpr
pPOLY typ = pTypedPolyExpr typ pTypedConst pTypedExpr parserDict
pPERM :: Type -> ParseM PermExpr
pPERM typ = pTypedPermExpr typ pTypedExpr parserDict
pMAC :: Type -> ParseM MacExpr
pMAC typ = pTypedMacExpr typ pTypedExpr (pBrackDocE pDOC) parserDict
pDOC :: ParseM Doc
pDOC = pDoc pTypedExpr pSTR pDOC
parserDict :: ParserDict
parserDict = ParserDict
{ parseINT = pINT
, parseRAT = pRAT
, parseBOOL = pBOOL
, parseSTR = pSTR
, parseZZMOD = pMOD
, parseLIST = pLIST
, parseMAT = pMAT
, parseMAC = pMAC
, parsePOLY = pPOLY
, parsePERM = pPERM
, parseTUPLE = pTUPLE
}
{---------}
{- :Expr -}
{---------}
pTypedExpr :: Type -> ParseM Expr
pTypedExpr DD = fmap DocE pDOC
pTypedExpr SS = fmap StrE pSTR
pTypedExpr ZZ = fmap IntE pINT
pTypedExpr BB = fmap BoolE pBOOL
pTypedExpr QQ = fmap RatE pRAT
pTypedExpr (ZZMod n) = fmap ZZModE (pMOD n)
pTypedExpr (ListOf t) = fmap ListE (pLIST t)
pTypedExpr (MatOf t) = fmap MatE (pMAT t)
pTypedExpr (MacTo t) = fmap MacE (pMAC t)
pTypedExpr (PermOf t) = fmap PermE (pPERM t)
pTypedExpr (PolyOver t) = fmap PolyE (pPOLY t)
pTypedExpr (TupleOf ts) = fmap TupleE (pTUPLE ts)
pTypedExpr XX = choice
[ pTypedExpr ZZ
, pTypedExpr QQ
, pTypedExpr BB
, pTypedExpr SS
, fmap ListE (pListExpr pTypedExpr parserDict)
, fmap MatE (pMatExpr pTypedExpr parserDict)
, fmap PolyE (pPolyExpr pTypedConst pTypedExpr parserDict)
]
pTypedConst :: Type -> ParseM Expr
pTypedConst SS = fmap StrE pStrConst
pTypedConst ZZ = fmap IntE pIntConst
pTypedConst BB = fmap BoolE pBoolConst
pTypedConst QQ = fmap RatE pRatConst
pTypedConst (ZZMod n) = fmap ZZModE (pZZModConst n)
pTypedConst (ListOf t) = fmap ListE (pListConst t pTypedConst)
pTypedConst (MatOf t) = fmap MatE (pMatConst t pTypedConst)
pTypedConst (PolyOver t) = fmap PolyE (pPolyConst t pTypedConst)
pTypedConst (PermOf t) = fmap PermE (pPermConst t pTypedConst)
pTypedConst (MacTo t) = fmap MacE (pMacConst t pTypedConst (pBrackDocE pDOC))
pTypedConst (TupleOf ts) = fmap TupleE (pTupleConst ts pTypedConst)
pTypedConst _ = error "pTypedConst"
{---------}
{- :REPL -}
{---------}
pREPL :: ParseM Doc
pREPL = do
x <- choice $ map (fmap Doc . pAtLocus)
[ pDefineREPL
, pNakedExprREPL
, pVarExpr NakedKey DD
, pImportREPL
]
eof
return x
where
pDefineREPL = do
try $ keyword "define"
t <- pType
whitespace
k <- pKey
keyword ":="
v <- if t == DD then (pBrackDocE pDOC) else pTypedExpr t
return (Define t k v (Doc (Empty :@ NullLocus)))
pNakedExprREPL = do
x <- try (pTypedNakedExpr pTypedExpr)
return (NakedExpr x)
pImportREPL = do
try $ keyword "import"
path <- pParens pPath
qual <- option Nothing (try (keyword "as") >> pToken >>= return . Just)
return (Import path qual (Doc (Empty :@ NullLocus)))
| nbloomf/feivel | src/Feivel/Parse/Expr.hs | gpl-3.0 | 5,702 | 0 | 17 | 1,563 | 1,465 | 762 | 703 | 122 | 2 |
{-# LANGUAGE BangPatterns #-}
module Codec.Video.MpegTS where
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString as BS
import Data.ByteString.Lazy (empty)
import Data.Binary.Get
import Data.Word
import Data.Bits
import Control.Applicative hiding (empty)
import Control.Monad
import Debug.Trace
type Data = BS.ByteString
type PID = Word16
type PayloadStart = Bool
type ContC = Word8
type SID = Word8
data TS = TS
{ ts_pid :: !PID
, ts_pst :: !PayloadStart
, ts_contc :: !ContC
, ts_ad :: !(Maybe Adaptation)
, ts_data :: !(Maybe Data)
} deriving (Show)
data PAT = PAT
{ pat_nextS :: !Bool
, pat_section :: !Word8
, pat_lastSection :: !Word8
, pat_programs :: ![PAT_Prog]
} deriving (Show)
data PAT_Prog = PAT_Prog
{ prog_num :: !Word16
, prog_pid :: !Word16
} deriving (Show)
data PMT = PMT
{ pmt_prog_num :: !Word16
, pmt_nextS :: !Bool
, pmt_pcrPID :: !Word16
, pmt_programDesc :: !Data
, pmt_progs :: ![PMT_Prog]
} deriving (Show)
data PMT_Prog = PMT_Prog
{ pmtp_streamType :: !StreamType
, pmtp_elemPID :: !Word16
, pmtp_esInfo :: !ESDescriptor
} deriving (Show)
--type Adaptation = BS.ByteString
data AdaptationFlags = AdaptationFlags
{ af_discont :: !Bool
, af_randomAccess :: !Bool
, af_priority :: !Bool
, af_pcr :: !Bool
, af_opcr :: !Bool
, af_splice :: !Bool
, af_transportPrivateData :: !Bool
, af_extension :: !Bool
}
defaultAdaptationFlags =
AdaptationFlags False False False False False
False False False
instance Show AdaptationFlags where
show (AdaptationFlags d r p pcr opcr spl tpd e) =
(t d 'D') : (t p 'P') : (t pcr 'C') : (t opcr 'O') : (t spl 'S') :
(t tpd 'P') : (t e 'E') : []
where
t f c = case f of
True -> c
False -> '-'
data Adaptation = Adaptation
{ ad_len :: !Int
, ad_flags :: !AdaptationFlags
, ad_pcr :: !(Maybe Int)
, ad_opcr :: !(Maybe Int)
, ad_splice :: !Int
} deriving (Show)
data PES = PES
{ pes_sid :: !SID
, pes_data :: !Data
} deriving (Show)
data StreamType = VIDEO_MPEG1 | VIDEO_MPEG2 | AUDIO_MPEG1 | AUDIO_MPEG2
| PRIVATE_SECTION | PRIVATE_DATA | AUDIO_AAC | VIDEO_MPEG4
| AUDIO_LATM_AAC | SYSTEMS_MPEG4_PES | SYSTEMS_MPEG4_SECTIONS
| VIDEO_H264 | AUDIO_AC3 | AUDIO_DTS | SUBTITLE_DVB
| Other Word8
deriving (Show)
fromWord8 0x01 = VIDEO_MPEG1
fromWord8 0x02 = VIDEO_MPEG2
fromWord8 0x03 = AUDIO_MPEG1
fromWord8 0x04 = AUDIO_MPEG2
fromWord8 0x05 = PRIVATE_SECTION
fromWord8 0x06 = PRIVATE_DATA
fromWord8 0x0F = AUDIO_AAC
fromWord8 0x10 = VIDEO_MPEG4
fromWord8 0x11 = AUDIO_LATM_AAC
fromWord8 0x12 = SYSTEMS_MPEG4_PES
fromWord8 0x13 = SYSTEMS_MPEG4_SECTIONS
fromWord8 0x1B = VIDEO_H264
fromWord8 0x81 = AUDIO_AC3
fromWord8 0x8A = AUDIO_DTS
fromWord8 0x100 = SUBTITLE_DVB
fromWord8 x = Other x
data ESDescriptor = Reserved
| Video_stream_descriptor | Audio_stream_descriptor | Hierarchy_descriptor
| Registration_descriptor | Data_stream_alignment_descriptor | Target_background_grid_descriptor
| Video_window_descriptor | CA_descriptor | ISO_639_language_descriptor
| System_clock_descriptor | Multiplex_buffer_utilization_descriptor
| Copyright_descriptor | Maximum_bitrate_descriptor | Private_data_indicator_descriptor
| Smoothing_buffer_descriptor | STD_descriptor | IBP_descriptor
| MPEG | IOD_descriptor | SL_descriptor
| FMC_descriptor | External_ES_ID_descriptor | MuxCode_descriptor
| FmxBufferSize_descriptor | MultiplexBuffer_descriptor | FlexMuxTiming_descriptor
| User_Private
deriving (Show)
esTag 0 = Reserved
esTag 1 = Reserved
esTag 2 = Video_stream_descriptor
esTag 3 = Audio_stream_descriptor
esTag 4 = Hierarchy_descriptor
esTag 5 = Registration_descriptor
esTag 6 = Data_stream_alignment_descriptor
esTag 7 = Target_background_grid_descriptor
esTag 8 = Video_window_descriptor
esTag 9 = CA_descriptor
esTag 10 = ISO_639_language_descriptor
esTag 11 = System_clock_descriptor
esTag 12 = Multiplex_buffer_utilization_descriptor
esTag 13 = Copyright_descriptor
esTag 14 = Maximum_bitrate_descriptor
esTag 15 = Private_data_indicator_descriptor
esTag 16 = Smoothing_buffer_descriptor
esTag 17 = STD_descriptor
esTag 18 = IBP_descriptor
esTag 27 = MPEG
esTag 28 = MPEG
esTag 29 = IOD_descriptor
esTag 30 = SL_descriptor
esTag 31 = FMC_descriptor
esTag 32 = External_ES_ID_descriptor
esTag 33 = MuxCode_descriptor
esTag 34 = FmxBufferSize_descriptor
esTag 35 = MultiplexBuffer_descriptor
esTag 36 = FlexMuxTiming_descriptor
esTag x | (x >= 0x40 && x <= 0xFF) = User_Private
| otherwise = Reserved
decodeESDescriptor :: Int -> Get ESDescriptor
decodeESDescriptor l = do
tag <- getWord8
skip (l-1)
return (esTag tag)
decodeTS :: Get TS
decodeTS = do
checkSyncByte
(ps, pid) <- parsePID
(ad, cc) <- parseAD
let pack = TS pid ps cc
case ad of
0 -> fail (show (pack Nothing Nothing) ++ ": wrong adaptation field code")
2 -> do af <- decodeAdaptation
skip (184-(ad_len af)-1)
return$ pack (Just af) Nothing
3 -> do af <- decodeAdaptation
d <- getByteString (184-(ad_len af)-1)
return$ pack (Just af) (Just d)
_ -> do d <- getByteString 184
return$ pack Nothing (Just d)
where
checkSyncByte =
do sync <- getWord8
when (sync /= 0x47) (fail$ "bad sync byte " ++ show sync) -- checkSyncByte
parsePID =
do chunk <- getWord16be
let ps = testBit chunk 14
pid = 0x1FFF .&. chunk
return (ps, pid)
parseAD =
do byte <- getWord8
let ad = (shiftR (0x30 .&. byte) 4)
cc = (0x07 .&. byte)
return (ad,cc)
decodePES :: Get PES
decodePES = do
checkPSP
sid <- getWord8
len <- fromIntegral <$> getWord8
optional <- getOptionalPES
d <- case len of
0 -> getByteString len
_ -> getByteString len
return$ PES sid d
where
checkPSP = do
pspa <- getWord16be
pspb <- getWord8
when (pspa /= 0x0000 || pspb /= 0x01) (fail $ "bad psp sync bytes" ++ show pspa ++ " " ++ show pspb)
getOptionalPES = do
h <- getWord16be
l <- fromIntegral <$> getWord8
getByteString l
last10 = ((2^10-1).&.)
last13 = ((2^13-1).&.)
decodePAT :: Bool -> Get PAT
decodePAT start = do
when start (skip 1)
tableID <- getWord8
when (tableID /=0x00)
(fail "PAT: wrong tableID")
n16 <- getWord16be
let len = last10 n16
skip 2
a <- getWord8
sn <- getWord8
lastSn <- getWord8
let progN = (len-9) `div` 4
progs <-
forM [1..progN]
(\x -> PAT_Prog <$> getWord16be <*> (last13 <$> getWord16be))
skip 4 -- CRC32
return $ PAT (testBit a 0) sn lastSn progs
decodePMT :: Bool -> Get PMT
decodePMT start = do
when start (skip 1)
tableID <- getWord8
when (tableID /= 0x02)
(fail "PMT: wrong tableID")
n16 <- getWord16be
let len = last10 n16
prog_num <- getWord16be
skip 3
pcr_pid <- last13 <$> getWord16be
pinfo_len <- last10 <$> getWord16be
program_desc <- getByteString (fromIntegral pinfo_len)
progs <-
forM [1..2] (\_ -> do
stype <- fromWord8 <$> getWord8
pid <- last13 <$> getWord16be
esInfoL <- last10 <$> getWord16be
esDesc <- decodeESDescriptor (fromIntegral esInfoL)
return$ PMT_Prog stype pid esDesc)
skip 4 --CRC32
return PMT
{ pmt_prog_num = prog_num
, pmt_nextS = False
, pmt_pcrPID = pcr_pid
, pmt_programDesc = program_desc
, pmt_progs = progs
}
maybeParse False _ = return Nothing
maybeParse True parser = do
a <- parser
return (Just a)
decodeAdaptation :: Get Adaptation
decodeAdaptation = do
len <- fromIntegral <$> getWord8
cursor <- bytesRead
flags <-
if (len == 0)
then return defaultAdaptationFlags
else decodeAdaptationFlags
pcr <- decodePCR (af_pcr flags)
opcr <- decodePCR (af_opcr flags)
splice <- case (af_splice flags) of
False -> return 0
True -> fromIntegral <$> getWord8
cursor2 <- bytesRead
let consumed = fromIntegral (cursor2 - cursor)
skip (len-consumed)
return $ Adaptation len flags pcr opcr splice
where
decodePCR False = return Nothing
decodePCR True = do
up <- getWord32be
--lw <- getWord16be TODO: extension n stuff
skip 2
let ret = 2 * fromIntegral up
return (Just ret)
decodeAdaptationFlags :: Get AdaptationFlags
decodeAdaptationFlags = do
flags <- getWord8
let test = testBit flags
return $ AdaptationFlags (test 7) (test 6) (test 5) (test 4)
(test 3) (test 2) (test 1) (test 0)
parseListOf parser bytestring offset =
let (x, rest, i) = runGetState parser bytestring offset
in
if rest == empty
then x:[]
else x:(parseListOf parser rest i)
parseOffsetMap parser bytestring offset =
let (x, rest, i) = runGetState parser bytestring offset
in
if rest == empty
then (x,i):[]
else (x,i):(parseOffsetMap parser rest i)
collectTS = parseListOf decodeTS
collectTSOff = parseOffsetMap decodeTS
| hepek/MPEG-TS | Codec/Video/MpegTS.hs | gpl-3.0 | 10,124 | 0 | 18 | 3,151 | 2,919 | 1,492 | 1,427 | 352 | 4 |
module L0216 where
data Stream0 a = Cons0 a (Stream0 a) deriving Show
data Stream1 a = Cons1 a (Stream1 a) | End1 deriving Show
instance Functor Stream0 where
fmap f (Cons0 a b) = Cons0 (f a) (fmap f b)
a = Cons0 1 $ Cons0 2 $ Cons0 3 $ a
b = Cons0 4 $ Cons0 5 $ Cons0 6 $ b
interleave :: Stream0 a -> Stream0 a -> Stream0 a
interleave (Cons0 a1 a2) (Cons0 b1 b2) = Cons0 a1 $ Cons0 b1 $ interleave a2 b2
(+++) :: Stream1 a -> Stream1 a -> Stream1 a
End1 +++ s = s
(Cons1 a b) +++ s = Cons1 a (b +++ s)
c = Cons1 1 $ Cons1 2 $ Cons1 3 End1
d = Cons1 4 $ Cons1 5 $ Cons1 6 End1
data List a = Cons a (List a) | Empty deriving Show
e = Cons 1 $ Cons 2 $ Cons 3 $ Cons 4 $ Cons 5 Empty
f = Cons odd $ Cons even Empty
g = Cons (+1) Empty
h = Cons (*2) Empty
x0 = \x -> x
x1 = \x -> \y -> x.y
x2 = \x -> \y -> \z -> x.y.z
instance Functor List where
fmap f Empty = Empty
fmap f (Cons a b) = Cons (f a) (fmap f b)
conn :: List a -> List a -> List a
conn Empty b = b
conn (Cons a as) b = Cons a $ conn as b
listLength Empty = 0
listLength (Cons _ as) = 1 + listLength as
instance Applicative List where
pure x = Cons x Empty
Empty <*> _ = Empty
_ <*> Empty = Empty
(Cons a as) <*> (Cons b bs) = conn (fmap a (Cons b bs)) (as <*> Cons b bs)
| cwlmyjm/haskell | AFP/L0216.hs | mpl-2.0 | 1,265 | 0 | 10 | 341 | 736 | 365 | 371 | 35 | 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.Language.Documents.AnalyzeSentiment
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Analyzes the sentiment of the provided text.
--
-- /See:/ <https://cloud.google.com/natural-language/ Google Cloud Natural Language API Reference> for @language.documents.analyzeSentiment@.
module Network.Google.Resource.Language.Documents.AnalyzeSentiment
(
-- * REST Resource
DocumentsAnalyzeSentimentResource
-- * Creating a Request
, documentsAnalyzeSentiment
, DocumentsAnalyzeSentiment
-- * Request Lenses
, dasXgafv
, dasUploadProtocol
, dasPp
, dasAccessToken
, dasUploadType
, dasPayload
, dasBearerToken
, dasCallback
) where
import Network.Google.Language.Types
import Network.Google.Prelude
-- | A resource alias for @language.documents.analyzeSentiment@ method which the
-- 'DocumentsAnalyzeSentiment' request conforms to.
type DocumentsAnalyzeSentimentResource =
"v1" :>
"documents:analyzeSentiment" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "pp" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "bearer_token" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] AnalyzeSentimentRequest :>
Post '[JSON] AnalyzeSentimentResponse
-- | Analyzes the sentiment of the provided text.
--
-- /See:/ 'documentsAnalyzeSentiment' smart constructor.
data DocumentsAnalyzeSentiment = DocumentsAnalyzeSentiment'
{ _dasXgafv :: !(Maybe Xgafv)
, _dasUploadProtocol :: !(Maybe Text)
, _dasPp :: !Bool
, _dasAccessToken :: !(Maybe Text)
, _dasUploadType :: !(Maybe Text)
, _dasPayload :: !AnalyzeSentimentRequest
, _dasBearerToken :: !(Maybe Text)
, _dasCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'DocumentsAnalyzeSentiment' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dasXgafv'
--
-- * 'dasUploadProtocol'
--
-- * 'dasPp'
--
-- * 'dasAccessToken'
--
-- * 'dasUploadType'
--
-- * 'dasPayload'
--
-- * 'dasBearerToken'
--
-- * 'dasCallback'
documentsAnalyzeSentiment
:: AnalyzeSentimentRequest -- ^ 'dasPayload'
-> DocumentsAnalyzeSentiment
documentsAnalyzeSentiment pDasPayload_ =
DocumentsAnalyzeSentiment'
{ _dasXgafv = Nothing
, _dasUploadProtocol = Nothing
, _dasPp = True
, _dasAccessToken = Nothing
, _dasUploadType = Nothing
, _dasPayload = pDasPayload_
, _dasBearerToken = Nothing
, _dasCallback = Nothing
}
-- | V1 error format.
dasXgafv :: Lens' DocumentsAnalyzeSentiment (Maybe Xgafv)
dasXgafv = lens _dasXgafv (\ s a -> s{_dasXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
dasUploadProtocol :: Lens' DocumentsAnalyzeSentiment (Maybe Text)
dasUploadProtocol
= lens _dasUploadProtocol
(\ s a -> s{_dasUploadProtocol = a})
-- | Pretty-print response.
dasPp :: Lens' DocumentsAnalyzeSentiment Bool
dasPp = lens _dasPp (\ s a -> s{_dasPp = a})
-- | OAuth access token.
dasAccessToken :: Lens' DocumentsAnalyzeSentiment (Maybe Text)
dasAccessToken
= lens _dasAccessToken
(\ s a -> s{_dasAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
dasUploadType :: Lens' DocumentsAnalyzeSentiment (Maybe Text)
dasUploadType
= lens _dasUploadType
(\ s a -> s{_dasUploadType = a})
-- | Multipart request metadata.
dasPayload :: Lens' DocumentsAnalyzeSentiment AnalyzeSentimentRequest
dasPayload
= lens _dasPayload (\ s a -> s{_dasPayload = a})
-- | OAuth bearer token.
dasBearerToken :: Lens' DocumentsAnalyzeSentiment (Maybe Text)
dasBearerToken
= lens _dasBearerToken
(\ s a -> s{_dasBearerToken = a})
-- | JSONP
dasCallback :: Lens' DocumentsAnalyzeSentiment (Maybe Text)
dasCallback
= lens _dasCallback (\ s a -> s{_dasCallback = a})
instance GoogleRequest DocumentsAnalyzeSentiment
where
type Rs DocumentsAnalyzeSentiment =
AnalyzeSentimentResponse
type Scopes DocumentsAnalyzeSentiment =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient DocumentsAnalyzeSentiment'{..}
= go _dasXgafv _dasUploadProtocol (Just _dasPp)
_dasAccessToken
_dasUploadType
_dasBearerToken
_dasCallback
(Just AltJSON)
_dasPayload
languageService
where go
= buildClient
(Proxy :: Proxy DocumentsAnalyzeSentimentResource)
mempty
| rueshyna/gogol | gogol-language/gen/Network/Google/Resource/Language/Documents/AnalyzeSentiment.hs | mpl-2.0 | 5,603 | 0 | 18 | 1,347 | 857 | 497 | 360 | 123 | 1 |
{-# LANGUAGE OverloadedStrings, RecordWildCards #-}
module Model.Category
( module Model.Category.Types
, allCategories
, getCategory
, getCategory'
, categoryJSON
, participantCategory
) where
import qualified Data.IntMap.Strict as IntMap
import Data.Monoid ((<>))
import qualified Data.Text
import qualified JSON
import Model.Id
import Model.Category.Types
-- Formerly used when loaded from db
-- categoryRow :: Selector -- Category
-- categoryRow = selectColumns 'Category "category" ["id", "name", "description"]
-- TODO: db coherence
allCategories :: [Category]
allCategories =
[Category
(Id 1)
(Data.Text.pack "participant")
(Just
(Data.Text.pack
"An individual human subject whose data are used or represented")),
Category
(Id 2)
(Data.Text.pack "pilot")
(Just
(Data.Text.pack
"Indicates that the methods used were not finalized or were non-standard")),
Category
(Id 3)
(Data.Text.pack "exclusion")
(Just (Data.Text.pack "Indicates that data were not usable")),
Category
(Id 4)
(Data.Text.pack "condition")
(Just
(Data.Text.pack
"An experimenter-determined manipulation (within or between sessions)")),
Category
(Id 5)
(Data.Text.pack "group")
(Just
(Data.Text.pack
"A grouping determined by an aspect of the data (participant ability, age, grade level, experience, longitudinal visit, measurements used/available)")),
Category
(Id 6)
(Data.Text.pack "task")
(Just
(Data.Text.pack
"A particular task, activity, or phase of the session or study")),
Category
(Id 7)
(Data.Text.pack "context")
(Just
(Data.Text.pack
"A particular setting or other aspect of where/when/how data were collected"))]
categoriesById :: IntMap.IntMap Category
categoriesById = IntMap.fromAscList $ map (\a -> (fromIntegral $ unId $ categoryId a, a)) allCategories
getCategory :: Id Category -> Maybe Category
getCategory (Id i) = IntMap.lookup (fromIntegral i) categoriesById
getCategory' :: Id Category -> Category
getCategory' (Id i) = categoriesById IntMap.! fromIntegral i
categoryJSON :: JSON.ToObject o => Category -> JSON.Record (Id Category) o
categoryJSON Category{..} = JSON.Record categoryId $
"name" JSON..= categoryName
<> "description" `JSON.kvObjectOrEmpty` categoryDescription
participantCategory :: Category
participantCategory = head allCategories
| databrary/databrary | src/Model/Category.hs | agpl-3.0 | 2,596 | 0 | 11 | 623 | 583 | 316 | 267 | 68 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Ledger
( accountMap
, findParents
, transactionLine
) where
import Data.Maybe
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Builder as TLB
-- Lazy debugging
import Debug.Trace
import Types
--
-- Helper functions
--
inspectId :: Account -> T.Text
inspectId a = if (idType $ aGuid a) /= (T.pack "guid")
then trace ("Account IdType not guid! - " ++ (T.unpack $ aName a)) (idValue $ aGuid a)
else (idValue $ aGuid a)
inspectParentId :: Account -> Maybe T.Text
inspectParentId a =
case (aParent a) of
Nothing -> Nothing
Just p -> Just $
if (idType p) /= (T.pack "guid")
then trace ("Account IdType not guid! - " ++ (T.unpack $ aName a)) (idValue p)
else (idValue p)
inspectAccountId :: Split -> T.Text
inspectAccountId s = if (idType $ spAccountId s) /= (T.pack "guid")
then trace ("Account IdType not guid! - " ++ (show $ sMemo s)) (idValue $ spAccountId s)
else (idValue $ spAccountId s)
--
-- * Map of Account Id -> Account (parent/account lookup)
--
-- Text is idValue out of TypedId
accountMap :: [Account] -> Map T.Text Account
accountMap accounts = foldl foldAccount Map.empty accounts
where
foldAccount :: Map T.Text Account -> Account -> Map T.Text Account
foldAccount m a = Map.insert (inspectId a) a m
-- List is ordered from parent to child, does it include the given Account?
-- * Code to find all parent of an account
-- * For now it does not
findParents :: Account -> Map T.Text Account -> [Account]
findParents account am =
case (inspectParentId account) of
Nothing -> []
Just pid -> case (Map.lookup pid am) of
Nothing -> trace ("Account parent not found in map! - " ++ (T.unpack $ aName account)) []
Just pa -> pa : findParents pa am
--
-- Transaction process
--
transactionLine :: Transaction -> Map T.Text Account -> IO ()
transactionLine t am = do
putStr "Description: "
print $ tDescription t
putStr "\tCurrency: "
print $ tCurrency t
putStr "\tPosted: "
print $ tPosted t
putStr "\tEntered: "
print $ tEntered t
putStrLn "\tAccount Splits:"
mapM_ (\s -> do
putStr "\t\tMemo: "
print $ sMemo s
putStr "\t\tAction: "
print $ sAction s
putStr "\t\tspReconciledState: "
print $ spReconciledState s
putStr "\t\tValue: "
print $ spValue s
putStr "\t\tQuanity: "
print $ spQuantity s
let accountId = inspectAccountId s
let account = Map.lookup accountId am
let account' = fromJust account
let parents = findParents account' am
putStr "\t\tAccounts:"
putStrLn $ show $ reverse $ map (T.unpack . aName) (account' : parents)
) (tSplits t)
--data Transaction = Transaction
-- { tVersion :: Text -- TODO: ADT this
-- , tGuid :: TypedId PTTransaction
-- , tCurrency :: (TypedId PTSpace)
-- , tNum :: Maybe (Maybe Integer) -- No idea what this is
-- , tPosted :: Date
-- , tEntered :: Date
-- , tDescription :: Text
-- , tSlots :: Maybe (TypedSlots STransaction)
-- , tSplits :: [Split]
-- } deriving (Show, Eq)
--
--data Split = Split
-- { spId :: TypedId PTSplit
-- , sAction :: Maybe Text
-- , sMemo :: Maybe Text
-- , spReconciledState :: Text
-- , spReconciledDate :: Maybe Date
-- , spValue :: Text -- TODO: convert to rational
-- , spQuantity :: Text -- TODO: convert to rational
-- , spAccountId :: TypedId PTSplitAccount
-- , spSlots :: Maybe (TypedSlots SSplit)
-- } deriving (Show, Eq)
--
---- Core Type (Cannot access constructors for this)
--data TypedId t = TypedId
-- { idType :: Text
-- , idValue :: Text -- TODO: ADT this value/type
-- } deriving (Show, Eq)
--
--
--data Commodity = Commodity
-- { cVersion :: Text -- TODO: ADT this
-- , cSId :: TypedId PTSpace
-- , cName :: Maybe Text
-- , cXCode :: Maybe Text
-- , cFraction :: Maybe Integer
-- , cQuote :: Maybe ()
-- , cSource :: Maybe Text
-- , cTz :: Maybe ()
-- } deriving (Show, Eq)
--
--data PriceDb = PriceDb
-- { pVersion :: Text -- TODO: ADT this
-- , prices :: [Price]
-- } deriving (Show, Eq)
--
--data Price = Price
-- { pGuid :: TypedId PTPrice
-- , commoditySId :: TypedId PTSpace
-- , currencySId :: TypedId PTSpace
-- , pTime :: Date
-- , pSource :: Text
-- , pType :: Maybe Text
-- , pValue :: Text -- TODO: convert to rational
-- } deriving (Show, Eq)
--
---- TODO: make this handle <gdata> as well
--data Date = Date
-- { date :: Text -- TODO: proper type/parsing
-- , ns :: Maybe Text -- TODO: proper type/parsing (no idea what a ns is)
-- } deriving (Show, Eq)
| pharaun/hGnucash | src/Ledger.hs | apache-2.0 | 4,991 | 0 | 16 | 1,366 | 966 | 514 | 452 | 69 | 3 |
module GTKMain (main) where
import Debug
import BattleContext
import GTKInitialization (initUI, buildUI, setupUI, startUI)
import Data.IORef
import Control.Monad.Trans.Reader (runReaderT)
dataDir = "/usr/home/nbrk/projects/haskell/ld/executable"
main :: IO ()
main = do
putInfo "Starting GTK application"
putInfo $ "Data dir: " ++ dataDir
bc <- newFromScenario testScenario
initUI
gtkctx <- buildUI bc dataDir
runReaderT setupUI gtkctx
runReaderT startUI gtkctx
putInfo "Exiting GTK application"
| nbrk/ld | executable/GTKMain.hs | bsd-2-clause | 522 | 0 | 8 | 86 | 133 | 68 | 65 | 17 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.