Effects.tick replacement for elm 0.17 - thread-sleep

As it's stated in the upgrade guide, Effects is being replaced by this new Applicative Functor-like thing Cmd. I don't see any trace of a clue as to where Effects.tick might be hiding, or how it could be reimplemented.
From the looks of things, Process.sleep might be the right answer, something like
Task.perform errorHandler (\x -> x) <| Process.sleep
<| 500 * Time.millisecond
would allow the process to wait 500 milliseconds before issuing the next message / action. I'm just not sure if this is what will replace Effects.tick in the long run though.

Effect.tick functionality is replaced by AnimationFrame.
You basically subscribe to a set of msg of either times or diffs. And react accordingly.
import Html exposing (..)
import Html.App as App
import AnimationFrame
import Time exposing (Time, second)
main =
App.program
{ init = Model 0 0 ! []
, update = \msg model -> update msg model ! []
, view = view
, subscriptions = \_ -> AnimationFrame.diffs identity}
type alias Model =
{ timeSinceLastIncrement : Time
, counter : Int }
incrementTime = 1*second
update diff {timeSinceLastIncrement, counter} =
if timeSinceLastIncrement > incrementTime then
Model 0 (counter+1)
else
Model (timeSinceLastIncrement+diff) counter
view {counter} =
div [] [text (toString counter)]
I've chosen to send the Time diffs directly as messages and to unpack the structure of the model in both update and view for easier access to components. In a more complex app you will probably have something like a Tick Time message.

Related

Using Insert with a large multi-layered table using Lua

So I am working on a script for GTA5 and I need to transfer data over to a js script. However so I don't need to send multiple arrays to js I require a table, the template for the table should appear as below.
The issue I'm having at the moment is in the second section where I receive all vehicles and loop through each to add it to said 'vehicleTable'. I haven't been able to find the "table.insert" method used in a multilayered table
So far I've tried the following
table.insert(vehicleTable,vehicleTable[class][i][vehicleName])
This seems to store an 'object'(table)? so it does not show up when called in the latter for loop
Next,
vehicleTable = vehicleTable + vehicleTable[class][i][vehicleName]
This seemed like it was going nowhere as I either got a error or nothing happened.
Next,
table.insert(vehicleTable,class)
table.insert(vehicleTable[class],i)
table.insert(vehicleTable[class][i],vehicleName)
This one failed on the second line, I'm unsure why however it didn't even reach the next problem I saw later which would be the fact that line 3 had no way to specify the "Name" field.
Lastly the current one,
local test = {[class] = {[i]={["Name"]=vehicleName}}}
table.insert(vehicleTable,test)
It works without errors but ultimately it doesn't file it in the table instead it seems to create its own branch so object within the object.
And after about 3 hours of zero progress on this topic I turn to the stack overflow for assistance.
local vehicleTable = {
["Sports"] = {
[1] = {["Name"] = "ASS", ["Hash"] = "Asshole2"},
[2] = {["Name"] = "ASS2", ["Hash"] = "Asshole1"}
},
["Muscle"] = {
[1] = {["Name"] = "Sedi", ["Hash"] = "Sedina5"}
},
["Compacts"] = {
[1] = {["Name"] = "MuscleCar", ["Hash"] = "MCar2"}
},
["Sedan"] = {
[1] = {["Name"] = "Blowthing", ["Hash"] = "Blowthing887"}
}
}
local vehicles = GetAllVehicleModels();
for i=1, #vehicles do
local class = vehicleClasses[GetVehicleClassFromName(vehicles[i])]
local vehicleName = GetLabelText(GetDisplayNameFromVehicleModel(vehicles[i]))
print(vehicles[i].. " " .. class .. " " .. vehicleName)
local test = {[class] = {[i]={["Name"]=vehicleName}}}
table.insert(vehicleTable,test)
end
for k in pairs(vehicleTable) do
print(k)
-- for v in pairs(vehicleTable[k]) do
-- print(v .. " " .. #vehicleTable[k])
-- end
end
If there is not way to add to a library / table how would I go about sorting all this without needing to send a million (hash, name, etc...) requests to js?
Any recommendations or support would be much appreciated.
Aside the fact that you do not provide the definition of multiple functions and tables used in your code that would be necessary to provide a complete answere without making assumptions there are many misconceptions regarding very basic topics in Lua.
The most prominent is that you don't know how to use table.insert and what it can do. It will insert (append by default) a numeric field to a table. Given that you have non-numeric keys in your vehicleTable this doesn't make too much sense.
You also don't know how to use the + operator and that it does not make any sense to add a table and a string.
Most of your code seems to be the result of guess work and trial and error.
Instead of referring to the Lua manual so you know how to use table.insert and how to index tables properly you spend 3 hours trying all kinds of variations of your incorrect code.
Assuming a vehicle model is a table like {["Name"] = "MyCar", ["Hash"] = "MyCarHash"} you can add it to a vehicle class like so:
table.insert(vehicleTable["Sedan"], {["Name"] = "MyCar", ["Hash"] = "MyCarHash"})
This makes sense because vehicleTable.Sedan has numeric indices. And after that line it would contain 2 cars.
Read the manual. Then revisit your code and fix your errors.

Is there something like "awful.client.focus.global_byidx()"?

I have two monitors and I would like to change client focused by shortcut. Right now I have awful.client.focus.byidx(1) but it only changes clients on one monitor. I know there is awful.client.focus.global_bydirection("right") that works on multiple screens but it only goes to one direction and it stops working when get to last client. I like awful.client.focus.byidx(1) behavior which loops through all clients, so from the last client it goes to the first one.
I would like to use a hybrid between: going through clients as in awful.client.focus.byidx(1) but on all monitors/screens like awful.client.focus.global_bydirection("right") does. Is there a function that would have that behavior so I could use it? If not, do you know how could I achieve that goal?
First, let's look at how awful.client.focus.byidx is implemented.
The function itself calls awful.client.next and then focused the returned client, if any is found:
https://github.com/awesomeWM/awesome/blob/9781f14b105ee700c5bca339bf49bb52d2cca4b5/lib/awful/client/focus.lua#L65-L71
awful.client.next is implemented here: https://github.com/awesomeWM/awesome/blob/9781f14b105ee700c5bca339bf49bb52d2cca4b5/lib/awful/client.lua#L262-L284
It does the following:
line 263: Get the currently focused client
line 267: Get all visible clients on the screen of the visible client
line 270-274: Filter out unfocusable clients from the list
line 277 - 278: Find the focused client in the resulting list
line 280: Get the client at the wanted offset and return it
So, your request sounds like you only need to change one step here: Get the list of all visible clients instead of only those at the currently focused screen.
To get that list, you need to call awful.client.visible with nil instead of a specific screen.
Untested code:
function next_global(i, sel, stacked)
sel = sel or client.focus
if not sel then return end
local cls = awful.client.visible(nil, stacked)
local fcls = {}
for _, c in ipairs(cls) do
if awful.client.focus.filter(c) or c == sel then
table.insert(fcls, c)
end
end
cls = fcls
for idx, c in ipairs(cls) do
if c == sel then
return cls[gears.math.cycle(#cls, idx + i)]
end
end
end
function focus_byidx_global(i, c)
local target = next_global(i, c)
if target then
target:emit_signal("request::activate", "client.focus.byidx", {raise=true})
end
end
I don't know which version of AwesomeWM you are using. If in doubt, look at the installed files in /usr/share/awesome/lib/ and copy the code from there, then change it.
(A little more ugly solution would be something like the following, even though it requires less code; I leave it as an exercise to the reader to figure out what this does, but note that this "breaks stuff" in case a Lua error occurs and the monkey-patching becomes permanent)
function focus_byidx_global(i, c)
local old = awful.client.visible
awful.client.visible = function(_, s) return old(nil, s) end
awful.client.focus.byidx(i, c)
awful.client.visible = old
end

How broadcast variables are used in dask parallelization

I have some code applying a map function on a dask bag. I need a lookup dictionary to apply that function and it doesn't work with client.scatter.
I don't know if I am doing the right things, because the workers starts, but they don't do anything. I have tried different configuration looking to different examples, but I can't get it to work. Any support will be appreciated.
I know from Spark, you define a broadcast variable and you access the content by variable.value inside the function you want to apply. I don't see the same with dask.
# Function to map
def transform_contacts_add_to_historic_sin(data,historic_dict):
raw_buffer = ''
line = json.loads(data)
if line['timestamp] > historic_dict['timestamp]:
raw_buffer = raw_buffer + line['vid']
return raw_buffer
# main program
# historic_dict is a dictionary previously filled, which is the lookup variable for map function
# file_records will be a list of json.dump getting from a S3 file
from distributed import Client
client = Client()
historic_dict_scattered = client.scatter(historic_dict, broadcast=True)
file_records = []
raw_data = s3_procedure.read_raw_file(... S3 file.......)
data = TextIOWrapper(raw_data)
for line in data:
file_records.append(line)
bag_chunk = db.from_sequence(file_records, npartitions=16)
bag_transform = bag_chunk.map(lambda x: transform_contacts_add_to_historic(x), args=[historic_dict_scattered])
bag_transform.compute()
If your dictionary is small you can just include it directly
def func(partition, d):
return ...
my_dict = {...}
b = b.map(func, d=my_dict)
If it's large then you might want to wrap it up in Dask delayed first
my_dict = dask.delayed(my_dict)
b = b.map(func, d=my_dict)
If it's very large then yes, you might want to scatter it first (though I would avoid this if things work out with either of the approaches above).
[my_dict] = client.scatter([my_dict])
b = b.map(func, d=my_dict)

How can I reset ESP8266 MicroPython after main.py crashes?

I have a NodeMCU ESP8266 board running MicroPython. I'm running a web server on my ESP8266. This is my first IoT project based on one of these boards.
The below is a snippet of the code.
This is being executed within main.py. Every now and then, something causes the code to crash (perhaps timing and request based). When main.py exits, for whatever reason, I'm dropped back at the python CLI.
I'd like for the board to reset when this happens (if there isn't a better way).
What is the best method of restarting/reseting the ESP8266?
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
s.listen(5)
print('listening on', addr)
while True:
cl, addr = s.accept()
print('client connected from', addr)
cl_file = cl.makefile('rwb', 0)
print("Request:")
while True:
line = cl_file.readline()
print("Line:" , line)
if not line or line == b'\r\n':
print("breaking")
break
if line == b'GET /active HTTP/1.1\r\n':
MicroPython has machine.reset() function to reset a board.
Python (not just MicroPython) uses exception handling to handle errors.
Combining the two, you can easily achieve what you want. For example:
a = 4
b = 2
try:
a / b
except:
machine.reset()
If in the code above you replace value of b with 0, your board will reset. If you think about it for a bit, you probably will find out that it doesn't make much sense - you don't want your board suddenly reset if you just divide by 0 by mistake or otherwise. There're got to be better ways to handle errors! Likewise, you may want to think about your own case and see if resetting the board is really the best choice. If you think that yes, that's fine, just always keep in mind that you programmed your board to suddenly reset. Otherwise, your next question here may be "My board suddenly resets! Why???" ;-)
It may be late for the original question, but the answer I am going to share might help other people. Consider it is not a final solution, but in many scenarios, it may save a day. You can explore your case.
The solution is using the internal scheduling function of MicroPython. since its execution is guaranteed, then its behavior can be used as a tool to mimic a functional watchdog.
Following code will run with given timers and threshold which can be customized in your case, and if the timer reaches its threshold, and the value of wd_buffer is not updated for that time, then the function might be called, and we repeat the process again.
So in order to prevent the ESP getting restarted in this case after 12 sec, you have to in someplace in your code, periodically (shorter than 12 sec or adjust the timer and threshold according to your need) update the value of the Global wd_buffer variable. Hope it helps.
# Simple WD - Global Variable
wd_feeder = 0
wd_buffer = 0
wd_counter = 0
wd_threshold = 4
def wd_checker(calledvalue):
print('watchdog is checking... feeder= {} buffer= {}'.format(wd_feeder, wd_buffer))
global wd_counter
global wd_buffer
global wd_feeder
if wd_feeder == wd_buffer:
print('state is suspicious ... counter is {} incrementing the counter'.format(wd_counter))
wd_counter += 1
else:
wd_counter = 0
wd_feeder = wd_buffer
if wd_counter == wd_threshold:
print('Counter is reached its threshold, following function will be called')
wd_feeder = wd_buffer = wd_counter = 0
machine.reset()
if __name__ == '__main__':
scheduler_wd = machine.Timer(-1)
scheduler_wd.init(period=3000, mode=machine.Timer.PERIODIC, callback=wd_checker)
you could add a while loop checking for the Flash Button (GPIO pin 0) like this:
import machine
pin = machine.Pin(0, machine.Pin.IN, machine.Pin.PULL_UP)
while pin.value():
print('Put your code here...')
print('..this will looping until the Flash button is pressed...')
print('...and then it continues here.')
You could execute your code (which should be outside of the main.py -> other file) from the boot or the main.py. if it drops out it should execute the following code, which could trigger a reset.
You may have to catch the error first.
I hope I helped

How to close a programm in Erlang with WxWidgets?

I have a problem to close a program in Erlang. I use wxWidgets.
-module(g).
-compile(export_all).
-define(height, 500).
-define(width, 500).
-include_lib("wx/include/wx.hrl").
-define(EXIT,?wxID_EXIT).
init() ->
start().
start() ->
Wx = wx:new(),
Frame = wxFrame:new(Wx, -1, "Line", [{size, {?height, ?width}}]),
setup(Frame),
wxFrame:show(Frame),
loop(Frame).
setup(Frame) ->
menuBar(Frame),
wxFrame:connect(Frame, close_window).
menuBar(Frame) ->
MenuBar = wxMenuBar:new(),
File = wxMenu:new(),
wxMenuBar:append(MenuBar,File,"&Fichier"),
wxFrame:setMenuBar(Frame,MenuBar),
Quit = wxMenuItem:new ([{id,400},{text, "&Quit"}]),
wxMenu:append (File, Quit).
loop(Frame) ->
receive
#wx{event=#wxCommand{type=close_window}} ->
io:format("quit icon"),
wxWindow:close(Frame,[]);
#wx{id=?EXIT, event=#wxCommand{type=command_menu_selected}} ->
io:format("quit file menu"),
wxWindow:close(Frame,[])
end.
But the program doesn't close; neither the quit icon or Quit from the menu do anything.
You're almost there, but there's a few mistakes.
First, there's never any event being generated for your quit selection on your mention, you need to use connect again, like this:
Quit = wxMenuItem:new ([{id,400},{text, "&Quit"}]),
wxFrame:connect(Frame, command_menu_selected),
Now you have an event for each of the quit methods, but neither of them is working still.
The event for your quit icon isn't matching because you have the wrong event type in your pattern match, and the event for the menu quit selection isn't matching because you're looking for an ID of ?EXIT, which is defined as ?wxID_EDIT, which is defined as.. well clearly not 400, the ID you used when you created your quit menu item. So your receive clause needs to be changed to something like this:
receive
#wx{event=#wxClose{type=close_window}} ->
io:format("quit icon"),
wxFrame:destroy(Frame);
#wx{id=400, event=#wxCommand{type=command_menu_selected}} ->
io:format("quit file menu"),
wxFrame:destroy(Frame)
end.
In addition to Michael's answer regarding using connect/3 to listen for menu commands, nearly any frame will require a few standard event connections to behave the way you expect them to on closing in addition to whatever specific things you have going on. Note that this is connecting to the close_window event and using the option {skip, true}. This is so the signal doesn't stop propagating before it hits the part of Wx that will handle it the way you expect (one click to close) instead of requiring two clicks to close the frame on some platforms.
The basic skeleton often looks like this:
init(Args) ->
Wx = wx:new(),
Frame = wxFrame:new(Wx, ?wxID_ANY, ""),
% Generate whatever state the process represents
State = some_state_initializer(Args),
% Go through the steps to create your widget layout, etc.
WidgetReferences = make_ui(Frame),
% The standardish connects nearly any frame will need.
ok = wxFrame:connect(Frame, close_window, [{skip, true}]),
ok = wxFrame:connect(Frame, command_button_clicked),
ok = wxFrame:connect(Frame, command_menu_selected),
% Add more connects here depending on what you need.
% Adjust the frame size and location, if necessary
Pos = initial_position(Args),
Size = initial_size(Args),
ok = wxFrame:move(Frame, Pos),
ok = wxFrame:setSize(Frame, Size),
wxFrame:show(Frame),
% Optional step to add this frame to a UI state manager if you're
% writing a multi-window application.
ok = gui_manager:add_live(self()),
% Required return for wx_object behavior
{Frame, State}.
Digressing a bit from the original, but strongly related...
Many wxWidgets application have something very similar to this, customized as necessary not by writing all that out again, but by defining your own callback module and passing it in as an argument:
init({Mod, Args}) ->
% ...
PartialState = blank_state([{mod, Mod}, {frame, Frame}, {wx, Wx}]),
State = Mod:finalize(PartialState, Args),
Where blank_state/1 accepts a proplist and returns whatever the actual data structure will be later (usually a record at this level, that looks something like #s{mod, frame, wx, widgets, data}), and Mod:finalize/2 takes the incomplete state and the initial args and returns a completed GUI frame plus whatever program state it is supposed to manage -- in particular the widgets data structure that carries references to any GUI elements you will need to listen for, match on, or manipulate later.
Later on you have some very basic generic handlers all frames might need to deal with, and pass any other messages through to the specific Mod:
handle_call(Message, From, State = #s{mod = Mod}) ->
Mod:handle_call(Message, From, State).
handle_cast(blit, State) ->
{ok, NewState} = do_blit(State),
{noreply, NewState};
handle_cast(show, State) ->
ok = do_show(State),
{noreply, State};
handle_cast(Message, State = #s{mod = Mod}) ->
Mod:handle_cast(Message, State).
In this case do_blit/1 winds up calling Mod:blit/1 in the callback module which rebuilds and refreshes the GUI, rebuilding it from zero by calling a function that does that within wx:batch/1 to make it appear instant to the user:
blit(State) ->
wx:batch(fun() -> freshen_ui(State) end).
If you have a lot of elements to change in the GUI at once, blitting is far smoother and faster from the user's perspective than incrementally shuffling things around or hiding/showing elements as you go -- and is much more certain to feel the same across platforms and various computer speeds and userland loads (some Wx backends give a lot of flicker or intermediate display weirdness otherwise).
The do_show/1 function usually looks something like
do_show(#s{frame = Frame}) ->
ok = wxFrame:raise(Frame),
wxFrame:requestUserAttention(Frame).
(I have been meaning to write a basic "here is one way to structure a multi-window wxErlang application" tutorial/example but just haven't gotten around to it, so a lot of details are missing here but you'll stumble on them on your own after writing a couple of programs.)

Resources