Fields and Events in Elm 0.13 - events

This question somehow relates to How to use Fields in Elm 0.13 (and we are working on the same assignment).
In my case, everything that changes in the game should generate a Event:
data Event = NewGame
| PauseGame
| Turn [KeyCode]
| PlayerActive [Bool]
| PlayerChanged [PlayerSettings]
| Tick Time
The PlayerChanged event, for example, is generated as follows:
settingsSignal : Signal Event
settingsSignal =
lift PlayerChanged <|
combine [ pOneSettingsSignal, pTwoSettingsSignal
, pThreeSettingsSignal, pFourSettingsSignal]
pOneSettingsSignal : Signal PlayerSettings
pOneSettingsSignal =
PlayerSettings <~ (Controls <~ lift toCode pOneUp.signal
~ lift toCode pOneDown.signal
~ lift toCode pOneLeft.signal
~ lift toCode pOneRight.signal)
~ (pOneColor.signal)
~ (lift contentToString pOneName.signal)
where pOne<Direction> and pOneColor are inputs for dropDowns and pOneName is an Input for a Input.Field:
pOneName : Input Content
pOneName = input (Content nameOne (Selection 0 0 Forward))
I hereby assume that when I update the text field (or a dropdown), a PlayerChanged [PlayerSettings] event will be generated. All event get combined as follows:
eventSignal : Signal Event
eventSignal = merges [ clockSignal
, newGameSignal
, pauseGameSignal
, turnSignal
, activeSignal
, settingsSignal ]
and finally the event signal is lifted onto an update function:
gameState : Signal Game
gameState =
foldp update initialGame eventSignal
main = lift2 view gameState Window.dimensions
However, when the game is paused, it seems that all input is blocked and no signals propagate anymore. Also, the text fields are uneditable. Each Input.Field for the player names is defined as follows:
playerOneName : String -> Element
playerOneName name =
field defaultStyle pOneName.handle identity nameOne
(Content name (Selection 0 0 Forward))
and then, in the view function
pOneNameField = playerOneName playerOne.settings.name
To me it seems like everything is correct. When editing the displayed field, pOneName.signal is changed, which causes (trough a series of liftings) a PlayerChanged event to be generated, which causes the model to be redrawn, which should show the new update. Somehow the Input.Field is still uneditable, however. Worse: even a simple NewGame event isn't generated anymore and events from the dropdowns are also not propagated: nothing changes.
newGameSignal : Signal Event
newGameSignal =
always NewGame <~ (keepIf identity False <| space)
If I start the game in playing mode (thus no input forms are shown), this works fine and I can reset the game. It seems like the inputs are blocking the event stream, but I can't figure out where its going wrong.

So, I fixed it.
Appearantly the
case (event, game.state) of
(NewGame, _) ->
...
(Tick t, Playing) ->
statement is blocking, so it didn't match Tick Time signals sent in the Paused and Ended states and blocked there. A simple
(_, _) -> game
case fixed everything, so my 960 lines of Elm don't go to waste!

Related

Display images on Tensorboard to have the input, the ground truth and the prediction side by side

I'm working on a deep learning model and I would like to be able to display images on Tensorboard to have the input, the ground truth and the prediction side by side.
Currently, the display look like this :
current display
But this visualization is not convenient, because it's not easy to compare the ground truth with the prediction if images are not side by side, and we have to scroll to pass from the ground truth to the prediction (because images are too big and we display more than 6 images).
The current code :
for epoch in range(EPOCHS):
for step, (x_train, y_train) in enumerate(train_ds):
y_, gloss, dloss = pix2pix.train_step(x_train, y_train, epoch)
if step%PRINT_STEP == 0:
template = 'Epoch {} {}%, G-Loss: {}, D-Loss: {}'
print (template.format(epoch+1,int(100*step/max_steps),gloss, dloss))
with train_writer.as_default():
tf.summary.image('GT', y_train+0.5, step=epoch*max_steps+step, max_outputs=3, description=None)
tf.summary.image('pred', y_+0.5, step=epoch*max_steps+step, max_outputs=3, description=None)
tf.summary.image('input', x_train+0.5, step=epoch*max_steps+step, max_outputs=3, description=None)
tf.summary.scalar('generator loss', gloss, step = epoch*max_steps+step)
tf.summary.scalar('discriminator loss', dloss, step = epoch*max_steps+step)
tf.summary.flush()
So here is an example that what I would like to have :
desired display
I thought about an other solution : save all triples images(input/truth/pred) in local folders (folders 1 : input 1 /truth 1 /pred 1, folders 2 : input 2 /truth 2 /pred 2 ...) and display them with a python library (cv2, matplotlib ...) but same problem, I don't know how to do that if it's possible.
Thanks for your help

Is there a way to have a gpio output 1 when two nodes are outputting 1 into it?

I'm working on a security system with my raspberry pi and node-red. I have an infrared sensor outputting 1 when motion is detected, 0 when no motion is detected. I also have a switch with the pallete node-red-dashboard that outputs 1 when it is "open" and 0 when "closed". I want to make a function that would output 1 when both of the inputs are 1, kind of like an and gate. Any help?
There are a number of ways to achieve what you want. Import the flow below and see if it behaves like you want.
Credits to Cory Guyyn
[{"id":"326ee761.191508","type":"tab","label":"Flow 6","disabled":false,"info":""},{"id":"aa420627.bdb3e8","type":"function","z":"326ee761.191508","name":"Flow On/Off","func":"var state = context.get(\"state\") || \"on\";\n\n// Display initial state status\nif(state ==\"on\"){\n node.status({fill:\"green\",shape:\"dot\",text:state});\n}else{\n node.status({fill:\"red\",shape:\"ring\",text:state});\n}\n\nif(msg.topic == \"state\"){\n context.set(\"state\",msg.payload);\n state = msg.payload;\n // update status\n if(state == \"on\"){\n node.status({fill:\"green\",shape:\"dot\",text:state});\n }else{\n node.status({fill:\"red\",shape:\"ring\",text:state});\n }\n}else{\n if(state == \"on\"){\n return msg;\n }\n}\n","outputs":1,"noerr":0,"x":570,"y":340,"wires":[["6968506.c5da8b"]]},{"id":"d1c0dabc.ff33f8","type":"ui_switch","z":"326ee761.191508","name":"","label":"Dynamic Input","group":"efb0cd04.2f1fe","order":0,"width":0,"height":0,"passthru":true,"decouple":"false","topic":"state","style":"","onvalue":"on","onvalueType":"str","onicon":"","oncolor":"","offvalue":"off","offvalueType":"str","officon":"","offcolor":"","x":500,"y":240,"wires":[["aa420627.bdb3e8"]]},{"id":"fb35a101.734b3","type":"inject","z":"326ee761.191508","name":"","topic":"state","payload":"on","payloadType":"str","repeat":"","crontab":"","once":true,"x":280,"y":220,"wires":[["d1c0dabc.ff33f8"]]},{"id":"7f455eab.e11b4","type":"inject","z":"326ee761.191508","name":"","topic":"state","payload":"off","payloadType":"str","repeat":"","crontab":"","once":false,"x":270,"y":260,"wires":[["d1c0dabc.ff33f8"]]},{"id":"6968506.c5da8b","type":"debug","z":"326ee761.191508","name":"","active":true,"console":"false","complete":"false","x":750,"y":340,"wires":[]},{"id":"38c4ee82.f54e92","type":"comment","z":"326ee761.191508","name":"Sample Flow Toggle with UI and Link input","info":"","x":300,"y":120,"wires":[]},{"id":"5fb3fc9b.523764","type":"inject","z":"326ee761.191508","name":"PIR - 0","topic":"","payload":"0","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":270,"y":340,"wires":[["aa420627.bdb3e8"]]},{"id":"a1e5b421.b65e08","type":"inject","z":"326ee761.191508","name":"PIR - 1","topic":"","payload":"1","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":270,"y":380,"wires":[["aa420627.bdb3e8"]]},{"id":"efb0cd04.2f1fe","type":"ui_group","z":"","name":"Flow Toggle","tab":"6dfbaaa8.8cfbb4","disp":true,"width":"6"},{"id":"6dfbaaa8.8cfbb4","type":"ui_tab","z":"","name":"Sandbox","icon":"dashboard"}]

Set current time in init ELM 0.19

I get input JSON data from JS. This is a simple object, among which there is a date in the format "DD.MM.YYYY" - just a string.
If there is no dateStart in the object, I have to replace it with the current date (in withDefault).
paramsDecoder : Decode.Decoder Params
paramsDecoer =
Decode.succeed Params
|> Decode.andMap (Decode.field "dateStart" (Decode.string) |> (Decode.withDefault) "")
|> Decode.andMap (Decode.field "dateEnd" (Decode.string) |> (Decode.withDefault) "")
|> Decode.andMap (Decode.field "country" (Decode.string) |> (Decode.withDefault) "spain")
How can I do this in ELM?
Timezone is not important and is always equal to the same region.
I found an example of Time.now Time.zone usage,
but there time is getting in Update and its too late.
I solved this in two parts:
Part 1
Send the current time in to Elm when it initializes, using flags:
Elm.Main.init({flags: Date.now()});
And put it in your model:
import Time exposing (Posix, millisToPosix)
type alias Model = { now : Time.Posix, ... }
init : Int -> (Model, Cmd Msg)
init time = (Model (millisToPosix time), Cmd.none)
For your use case, you can then use withDefault model.now.
Part 2
The solution in Part 1 will only set now to the time when the page is loaded.
If you want to keep an up to date time you can use Time.every to update your model:
import Time exposing (Posix, millisToPosix, every)
timeOutCheck : Sub Msg
timeOutCheck = Time.every 250 UpdateTimeNow
type Msg = UpdateTimeNow Posix | ...
update msg model = case msg of
UpdateTimeNow time = { model | now = time }
...
This will ensure now is never more than 250 ms behind the current time. You can change 250 to suit your need.

Pinescript duplicate alerts

I have created a very basic script in pinescript.
study(title='Renko Strat w/ Alerts', shorttitle='S_EURUSD_5_[MakisMooz]', overlay=true)
rc = close
buy_entry = rc[0] > rc[2]
sell_entry = rc[0] < rc[2]
alertcondition(buy_entry, title='BUY')
alertcondition(sell_entry, title='SELL')
plot(buy_entry/10)
The problem is that I get a lot of duplicate alerts. I want to edit this script so that I only get a 'Buy' alert when the previous alert was a 'Sell' alert and visa versa. It seems like such a simple problem, but I have a hard time finding good sources to learn pinescript. So, any help would be appreciated. :)
One way to solve duplicate alters within the candle is by using "Once Per Bar Close" alert. But for alternative alerts (Buy - Sell) you have to code it with different logic.
I Suggest to use Version 3 (version shown above the study line) than version 1 and 2 and you can accomplish the result by using this logic:
buy_entry = 0.0
sell_entry = 0.0
buy_entry := rc[0] > rc[2] and sell_entry[1] == 0? 2.0 : sell_entry[1] > 0 ? 0.0 : buy_entry[1]
sell_entry := rc[0] < rc[2] and buy_entry[1] == 0 ? 2.0 : buy_entry[1] > 0 ? 0.0 : sell_entry[1]
alertcondition(crossover(buy_entry ,1) , title='BUY' )
alertcondition(crossover(sell_entry ,1), title='SELL')
You'll have to do it this way
if("Your buy condition here")
strategy.entry("Buy Alert",true,1)
if("Your sell condition here")
strategy.entry("Sell Alert",false,1)
This is a very basic form of it but it works.
You were getting duplicate alerts because the conditions were fulfulling more often. But with strategy.entry(), this won't happen
When the sell is triggered, as per paper trading, the quantity sold will be double (one to cut the long position and one to create a short position)
PS :You will have to add code to create alerts and enter this not in study() but strategy()
The simplest solution to this problem is to use the built-in crossover and crossunder functions.
They consider the entire series of in-this-case close values, only returning true the moment they cross rather than every single time a close is lower than the close two candles ago.
//#version=5
indicator(title='Renko Strat w/ Alerts', shorttitle='S_EURUSD_5_[MakisMooz]', overlay=true)
c = close
bool buy_entry = false
bool sell_entry = false
if ta.crossover(c[1], c[3])
buy_entry := true
alert('BUY')
if ta.crossunder(c[1], c[3])
sell_entry := true
alert('SELL')
plotchar(buy_entry, title='BUY', char='B', location=location.belowbar, color=color.green, offset=-1)
plotchar(sell_entry, title='SELL', char='S', location=location.abovebar, color=color.red, offset=-1)
It's important to note why I have changed to the indices to 1 and 3 with an offset of -1 in the plotchar function. This will give the exact same signals as 0 and 2 with no offset.
The difference is that you will only see the character print on the chart when the candle actually closes rather than watch it flicker on and off the chart as the close price of the incomplete candle moves.

Elm's Time is not Precise, is it?

I've been toying with Effects.tick and Time in one of my apps, and I can't seem to get my delays to be around the Time.second that it claims to be. It's nearly immediate. I understand that type alias Time = Float, and from my logs it seems that second = 1000, but this just burns so quickly, even with logging. Is there a clear explanation for this?
Effects.tick causes an action to be called nearly instantaneously, but the action that is being called gets passed a value of the current time of the tick. If you want to delay something by a second while using Effects.tick, you'll have to keep track of a starting point and compare it to the time of the current tick, and that's where you can add in Time.second.
Take this arbitrary example (you can paste it into http://elm-lang.org/try):
import Html exposing (..)
import Html.Events exposing (..)
import Html.Attributes exposing (..)
import StartApp
import Effects exposing (Never)
import Task
import Signal
import Time exposing (..)
app =
StartApp.start
{ init = init
, view = view
, update = update
, inputs = [ ]
}
main =
app.html
type alias Model =
{ lastTick : Maybe Time
, tickEverySecond : Maybe Time
}
init =
({ lastTick = Nothing, tickEverySecond = Nothing }, Effects.tick MyTicker)
view address model =
div []
[ div [] [ text <| "Current tick: " ++ (toString model.lastTick) ]
, div [] [ text <| "Updated every second: " ++ (toString model.tickEverySecond) ]
]
type Action
= MyTicker Time
update action model =
let
everySecond = Maybe.withDefault 0 model.tickEverySecond
getTickEverySecond time =
if time > everySecond + Time.second then
Just time
else
Just everySecond
in
case action of
MyTicker time -> (
{ model | lastTick = Just time
, tickEverySecond = getTickEverySecond time
}, Effects.tick MyTicker)
port tasks : Signal (Task.Task Never ())
port tasks =
app.tasks
Every update call requests a new tick, so it will just spin forever. The important part is that tickEverySecond is only updated if the last time it was updated is greater than one second ago.
You ask about the time precision. If you run that example, you'll notice that the increment every second is somewhat approximate; it will drift greater than a second. That isn't due to any kind of underlying imprecision. Remember that Elm's Time functionality is a thin veneer over Javascript's time and timer functionality. That drift is merely an artifact of all the tiny little delays caused by running code that responds to a timer signal.

Resources