on fetch collection is getting zero in backbone - ruby-on-rails

edit method
editCollection: (event) ->
#collection = new BackboneDemo.Collections.Backbonescripts()
#collection.url = "/demos/#{event.target.id}/test"
#collection.fetch()
#collection.on('sync', #selectCheckbox(event), this)
selectCheckbox: (event) ->
console.info #collection.length
#collection.each (test) ->
$('#'+event.target.id+'.test #'+test.get('id')+'.test_checkbox').prop('checked', true);
i even tried to use the reset and on success of the fetch...but length is zero
i know that back bone is lazy loading
How to use wait till fetch is completed......?

Replace those lines on:
editCollection: (event) =>
. . .
selectCheckbox: (event) =>
. . .

This is a function call:
#collection.on('sync', #selectCheckbox(event), this)
# ---------------------^^^^^^^^^^^^^^^^^^^^^^
You're calling #selectCheckbox and passing its return vale to #collection.on as though you said this:
x = #selectCheckbox(event)
#collection.on('sync', x, this)
so you're calling #selectCheckbox before the 'sync' event happens. I think you want to say this:
#collection.on('sync', #selectCheckbox, #)
# ---------------------^^^^^^^^^^^^^^^ Now just a function reference
Also, you should be careful of your indentation inside selectCheckbox or your #collection.each will be iterating with an empty function:
selectCheckbox: (event) ->
console.info #collection.length
#collection.each (test) ->
$("##{event.target.id}.test ##{test.get('id')}.test_checkbox").prop('checked', true)

Related

Avoid loading the same script twice with rFSM library in LUA

PROBLEM DESCRIPTION
The following code is a minimal example that replicates a problem I am having. The rFSM library is used, which can be found here: https://github.com/kmarkus/rFSM
There are three lua scripts. The "main", called runscript.lua, which initializes and runs the state machine (SM) that needs to be run, called mainTask.lua, which in turn, uses an auxiliary state machine subTask.lua.
The code flow is the following. We start inside the state machine mainTask.lua and immediately enter the Sim composite state, and then the state evaluate. There, we are calling the function evaluateData which is inside subTask.lua and set the local variable var to false. After this function call, we go to mainTask.lua again, make a transition and end up inside subTask.lua again. There we print the value of var.
Again, schematically: mainTask.lua -> subTask.lua -> mainTask.lua -> subTask.lua.
We expect the value of var to be false. However, as you can see, inside mainTask.lua, we are loading the subTask.lua twice via rfsm.load("subTask.lua"),. This results in having two instances of the auxiliary SM, but I want to have one instead.
The rfsm.load function is
function load(file)
local fsm = dofile(file)
if not is_state(fsm) then
error("rfsm.load: no valid rfsm in file '" .. tostring(file) .. "' found.")
end
return fsm
end
CODE
runscript.lua
-- Set lua path to location of rFSM library
package.path = "/home/anfr/rFSM-master/?.lua;./?.lua";
require 'rfsm';
print('[runscript.lua] Before rfsm.load("mainTask.lua")')
fsm_ = rfsm.load("mainTask.lua")
print('[runscript.lua] Before rfsm.init(fsm_)')
fsm = rfsm.init(fsm_);
print('[runscript.lua] Before rfsm.run(fsm)')
rfsm.run(fsm);
mainTask.lua
local var = true;
return rfsm.state{
Sim = rfsm.composite_state
{
evaluate = rfsm.state {
entry=function()
var = false;
if (evaluateData(var)) then
rfsm.send_events(fsm, "internal_EvaluateDone")
end
end,
},
sub = rfsm.load("subTask.lua"),
rfsm.trans {
src='initial',
tgt='evaluate',
effect=function()
print('[mainTask.lua] initial -> evaluate')
end,
},
rfsm.trans {
src='evaluate',
tgt='sub',
events={'internal_EvaluateDone'},
effect=function()
print('[mainTask.lua] evaluate -> sub with event "internal_EvaluateDone"')
end,
},
}, -- end of Sim
Seq = rfsm.composite_state
{
entry=function()
print('Entry Seq')
end,
exit=function()
print('Exit Seq')
end,
Running = rfsm.composite_state
{
entry=function()
print('Entry Running')
end,
exit=function()
print('Exit Running')
end,
--sub_2 = sub,
sub_2 = rfsm.load("subTask.lua"),
rfsm.trans {
src='initial',
tgt='sub_2',
effect=function()
print('[Seq composite state] initial -> sub_2')
end,
},
},
rfsm.trans {
src='initial',
tgt='Running',
effect=function()
print('[Seq composite state] initial -> Running')
end,
},
}, -- end of Seq
rfsm.trans {
src='initial',
tgt='Sim',
effect=function()
print('[mainTask.lua] initial -> Sim')
end,
},
};
subTask.lua
print("--- start of subTask.lua ---")
local var = true;
function evaluateData(value)
print("[subTask.lua] var before setting in evaluateData is " .. tostring(var));
var = value;
print("[subTask.lua] var after setting in evaluateData is " .. tostring(var))
return true
end
return rfsm.state {
execute = rfsm.state {
entry=function()
print('[subTask.lua] var inside execute is ' .. tostring(var))
end,
},
rfsm.trans {
src='initial',
tgt='execute',
effect=function()
print('[subTask.lua] initial -> execute')
end,
},
},
print("--- end of subTask.lua ---")
LOGS
The following logs show that the second time we enter the auxiliary SM, we use the second instance where the value of var is true (we don't want this).
[runscript.lua] Before rfsm.load("mainTask.lua")
--- start of subTask.lua ---
--- end of subTask.lua ---
--- start of subTask.lua ---
--- end of subTask.lua ---
[runscript.lua] Before rfsm.init(fsm_)
[runscript.lua] Before rfsm.run(fsm)
[mainTask.lua] initial -> Sim
[mainTask.lua] initial -> evaluate
[subTask.lua] var before setting in evaluateData is true
[subTask.lua] var after setting in evaluateData is false
[mainTask.lua] evaluate -> sub with event "internal_EvaluateDone"
[subTask.lua] initial -> execute
[subTask.lua] var inside execute is true
ATTEMPTS FOR A SOLUTION
Attempt 1
This attempt actually works in my local example (not the real system) and uses the commented line
sub_2 = sub. So the idea was to to load the state machine once, and here simply refer to that. I am wondering if the different versions of LUA have an impact on this. Locally I have Lua 5.2, on system Lua 5.1.
Edit
This attempt stops working if I simply add another dummy state inside the Seq composite state. Also there is no dependence on Lua versions.
Attempt 2
Implement a second version of load and use require instead of dofile. Then use this function in those two places inside mainTask.lua.
function load2(file)
local fileWithoutExtension = file:gsub("%.lua", "")
print(fileWithoutExtension)
local fsm = require(fileWithoutExtension)
if not is_state(fsm) then
error("rfsm.load: no valid rfsm in file '" .. tostring(file) .. "' found.")
end
return fsm
end
If I run this I get:
[runscript.lua] Before rfsm.load("mainTask.lua")
subTask
--- start of subTask.lua ---
--- end of subTask.lua ---
subTask
[runscript.lua] Before rfsm.init(fsm_)
lua: /home/anfr/rFSM-master/rfsm.lua:483: bad argument #1 to 'find' (string expected, got table)
stack traceback:
[C]: in function 'find'
/home/anfr/rFSM-master/rfsm.lua:483: in function '__resolve_path'
/home/anfr/rFSM-master/rfsm.lua:511: in function '__resolve_src'
/home/anfr/rFSM-master/rfsm.lua:551: in function 'func'
/home/anfr/rFSM-master/rfsm.lua:272: in function 'f'
/home/anfr/rFSM-master/utils.lua:246: in function 'map'
/home/anfr/rFSM-master/rfsm.lua:268: in function '__mapfsm'
/home/anfr/rFSM-master/rfsm.lua:275: in function 'f'
/home/anfr/rFSM-master/utils.lua:246: in function 'map'
/home/anfr/rFSM-master/rfsm.lua:268: in function '__mapfsm'
/home/anfr/rFSM-master/rfsm.lua:275: in function 'f'
/home/anfr/rFSM-master/utils.lua:246: in function 'map'
/home/anfr/rFSM-master/rfsm.lua:268: in function '__mapfsm'
/home/anfr/rFSM-master/rfsm.lua:283: in function 'mapfsm'
/home/anfr/rFSM-master/rfsm.lua:554: in function 'resolve_trans'
/home/anfr/rFSM-master/rfsm.lua:704: in function 'init'
runscript.lua:9: in main chunk
[C]: in ?
I don't understand why I get a table instead of a string. Unfortunately one needs to navigate in the rFSM lib code to help, but I would appreciate any hints.
Ps: Making the variable var global inside subTask.lua will give the correct behaviour. However I am trying to avoid the unnecessary overhead of loading the same script two times.
I am wondering if the different versions of LUA have an impact on this
All Lua versions have the same semantics of object references assignment.
as you can see, inside mainTask.lua, we are loading the subTask.lua twice via rfsm.load("subTask.lua")
When you use require the same state object is returned.
I don't understand why I get a table instead of a string
The function resolve_trans(fsm) converts .src fields of transitions from stings to objects (tables).
When you resolve the same transition object for the second time, the error is raised because tr.src field is expected to be a string.

Writing function to check state's machine current state [Lua/Love2d]

I'm learning game development with LÖVE2D and Lua and lately I've been using a state machine class. I haven't coded the class myself, but I've went through the code and I think I pretty much got it, besides this one problem.
The thing is, I'm trying to prompt the class for its current state, just so I can use it inside an if, but no matter what, I cannot get it right.
Here's the relevant code of the class:
StateMachine = Class{}
function StateMachine:init(states)
self.empty = {
render = function() end,
update = function() end,
enter = function() end,
exit = function() end
}
self.states = states or {} -- [name] -> [function that returns states]
self.current = self.empty
end
function StateMachine:change(stateName, enterParams)
assert(self.states[stateName]) -- state must exist!
self.current:exit()
self.current = self.states[stateName]()
self.current:enter(enterParams)
end
What I'm basically trying to do is:
function StateMachine:is(stateName)
if self.current == self.states[stateName] then
-- this never executes
return true
end
return false
end
I've tried changing self.states[stateName] to other things to test it out and also tried printing stuff to the console to see why the comparison is never true. It seems self.current returns a pointer to a table and thus never matches whatever is on the other side of the comparison operator.
Thanks for your help!
self.current is set to the return value of self.states[stateName] in StateMachine:change
function StateMachine:change(stateName, enterParams)
...
self.current = self.states[stateName]() -- note the () indicating the call
This means, unless the return value is self, self.current will not be equal to the function or object self.states[stateName] that it is compared to in StateMachine:is
function StateMachine:is(stateName)
if self.current == self.states[stateName] then -- here we are comparing the function to the return value
I would suggest expanding your state object to have a :getName function that would return the stateName or to store the name in your StateMachine under a key such as currentStateName.
I had the exact same question & I'd like to add--perhaps some of the comments explain this in language I just didn't understand :D--but in the getCurrentState function I created I had to do this:
function StateMachine:getCurrentState()
variable = self.currentStateName
return variable
where ofc variable is just some placeholder. but I had to grab the reference that self.currentStateName was pointing to, otherwise the comparison always failed.

How to save boolean conditions and evaluate later

I need to create a structure. The structure must contain an array of "boolean conditions". Something like this:
function ReturnStructure ()
local structure = {
{A < 10},
{B == "smth"},
{FunctionReturnsTrueOrFalse(params)},
--...
}
return structure
end
structure = ReturnStructure()
print(structure[1][1]) -- prints true or false depending on the value of A
In fact these tables contain true or false, not conditions, because when we call function ReturnStructure and it creates a local table structure, all conditions in the fields will be executed. I want to create a structure whose fields will contain not boolean values, but something that I can execute (when I want to do it) and get a boolean value. I can achieve this by using anonymous functions:
function ReturnStructure ()
local structure = {
{function() return A < 10 end},
{function() return B == "smth" end},
{FunctionReturnsTrueOrFalse, params}, -- I don't call function in this line, a just put its adress and parameters to table.
--...
}
return structure
end
structure = ReturnStructure()
print(structure[1][1]) -- prints function: 0x109bdd0
print(structure[1][1]()) -- prints true or false. I execute condition in this string.
So, there is a code which works as I want it to, but it seems very ugly.
I want to hear some ideas on how to create a simpler and more beautiful table, without printing function () return ... in every field. I think that I should use a simple OOP implementation to create my structure as an object, but I don't know how to do it. I also will be happy to get some references to methods, implementations, articles etc., which can help me to find some ideas.
I want to hear some ideas on how to create a simpler and more beautiful table, without printing function () return ... in every field.
There aren't. If Lua had C#'s lambda syntax, you could write:
local structure = {
() => A < 10,
() => B == "smth",
() => FunctionReturnsTrueOrFalse(params),
But Lua likes to keep things small and simple, to avoid adding size and complexity to the language and its implementation, so we have one syntax for one function type.
You could store them as strings, then compile and run them later, but that's choosing form over function. You don't want to be invoking the compiler unnecessarily.
local structure = {
'A < 10',
'B == "smth"',
'FunctionReturnsTrueOrFalse(params)',
So your original solution is better. I don't particularly like the way that the first two items defer evaluating their arguments, while your third example evaluates the parameters at compile time. It would be more consistent to treat the FunctionReturnsTrueOrFalse the same
local structure = {
function() return A < 10 end,
function() return B == "smth" end,
function() return FunctionReturnsTrueOrFalse(param1) end,
This also means you don't need to put them in tables. Each is just a function you call, which simplifies the calling code as well.
If you really wanted to evaluate FunctionReturnsTrueOrFalse's arguments at compile time, I'd write a utility routine to build a closure from a function and its arguments:
local function bind(f, ...)
local args = {...}
return function() f(unpack(args)) end
end
Then use that to bind the function to its args:
local structure = {
function() return A < 10 end,
function() return B == "smth" end,
bind(FunctionReturnsTrueOrFalse, param1, param2, param3),
Then everything in your table is simply a function so you don't need special handling
function ReturnStructure ()
local structure = {
{'A < 10'},
{'B == "smth"'},
{FunctionReturnsTrueOrFalse, 'parameter'},
}
local function call_me(f, ...)
return (type(f)=='function' and f or
assert((load or loadstring)('return '..f)))(...)
end
return setmetatable({}, {
__index =
function(t,k)
if structure[k] then
return call_me((table.unpack or unpack)(structure[k]))
end
end,
__newindex = function(t,k,v) structure[k] = v end
})
end
A = 2
B = "anything"
function FunctionReturnsTrueOrFalse(par)
return #par > 5
end
structure = ReturnStructure()
print(structure[1]) -- true
print(structure[2]) -- false
print(structure[3]) -- true
structure[4] = {'1==0'}
print(structure[4]) -- false

How to share functions in Coffeescript? Rails

I have one function that should be used in two different events, but I can't make it work. Where am I making a mistake? Or do I have to use Class instead?
coment_error = (that) ->
$this = $(that)
$new_answer = $this.parent('.new_answer')
$new_answer.on('ajax:success',((evt, data, status, xhr)->
$new_answer.hide()
$('.open').show()
))
$new_answer.on('ajax:error',((evt, data, status, xhr)->
$(this).addClass("error")
))
$(document).on("click", ".new_answer > INPUT[type='submit']", coment_error($(this)))
$(document).on("click", ".new_comment > INPUT[type='submit']", coment_error($(this)))
I think the problem is that the last two lines execute the function immediately instead of when the events are called.
$(document).on("click", ".new_answer > INPUT[type='submit']", coment_error)
Also you don't want coment_error to receive "that" because "this" will automatically be bound to the clicked element. So you can get right down to $this = $(this).

how to use mnesia:select/4 and mnesia:select/1 for paging query

a table named "md" with structure {id,name},I want read records from md use paging query,I tried mnesia:select/4 and mnesia:select/1 as below:
%% first use select/2: "ID < 10",returned [1,2,4,3,8,5,9,7,6]
(ejabberd#localhost)5> mnesia:activity(transaction,fun mnesia:select/2,md, [{{md,'$1','_'},[{'<','$1',10}],['$1']}]).
{atomic,[1,2,4,3,8,5,9,7,6]}
%%but when query with select/4,returned [6], why?
(ejabberd#localhost)7> {atomic,{R1,C1}}=mnesia:activity(transaction,fun mnesia:select/4,md,[{{md,'$1','_'},[{'<','$1',10}],['$1']}],5,read).
{atomic,{[6],
{mnesia_select,md,
{tid,10535470,<0.460.0>},
ejabberd#localhost,disc_only_copies,
{dets_cont,select,5,
<<0,0,0,29,18,52,86,120,0,0,0,21,131,104,3,...>>,
{141720,148792,<<>>},
md,<0.130.0>,<<>>},
[],undefined,undefined,
[{{md,'$1','_'},[{'<','$1',10}],['$1']}]}}}
%% and then use mnesia:select/1 with continuation "C1",got wrong_transaction
(ejabberd#localhost)8> mnesia:activity(transaction,fun mnesia:select/1,C1).
{aborted,wrong_transaction}
how to use mnesia:select/4 and mnesia:select/1 for paging query?
You will have to call select/1 inside the same transaction.
Otherwise the table can change between invocations to select/4 and select/1.
You must use a dirty context if you want to use is as written above.
here is my solution:
use async_dirty instead of transaction
{Record,Cont}=mnesia:activity(async_dirty, fun mnesia:select/4,[md,[{Match_head,[Guard],[Result]}],Limit,read])
then read next Limit number of records:
mnesia:activity(async_dirty, fun mnesia:select/1,[Cont])
full code:
-record(md,{id,name}).
batch_delete(Id,Limit) ->
Match_head = #md{id='$1',name='$2'},
Guard = {'<','$1',Id},
Result = '$_',
{Record,Cont} = mnesia:activity(async_dirty, fun mnesia:select/4,[md,[{Match_head,[Guard],[Result]}],Limit,read]),
delete_next({Record,Cont}).
delete_next('$end_of_table') ->
over;
delete_next({Record,Cont}) ->
delete(Record),
delete_next(mnesia:activity(async_dirty, fun mnesia:select/1,[Cont])).
delete(Records) ->
io:format("delete(~p)~n",[Records]),
F = fun() ->
[ mnesia:delete_object(O) || O <- Records]
end,
mnesia:transaction(F).

Resources