Cannot use self in python-socketio - python-socketio

I can't use self in a class.It seems that the data of the function after the decorator is the first parameter.
Example:
import socketio
import random
sio = socketio.Client()
class Test:
def __init__(self):
self.uid = random.randint(0, 10)
#sio.on('test')
def test(self, message):
test_message = str(self.uid) + message
print(test_message)
#staticmethod
def run():
sio.connect('ws://127.0.0.1:5000')
sio.wait()
if __name__ == '__main__':
test = Test()
test.run()
Error:
TypeError: test() missing 1 required positional argument: 'message'

By:miguelgrinberg
Right, so how is Socket.IO going to know that the value for self should be this test object you created near the bottom of the file? When you set up your handlers in this way there is really no link to the actual instance of the Test class.
Try setting the handlers once the class has been instantiated, maybe something like this:
def run(self):
sio.on('test', self.test)
sio.connect('ws://127.0.0.1:5000')
sio.wait()

Related

Passing variables between classes in Ruby on Rails

So I have two files, one called a.rb and one called b.rb. Here's the contents in both:
# a.rb
class A
def initialize
#variable = ""
#module_b = B.new(self)
end
def pass_to_b(self)
#module_b.do_something(#variable)
end
def set_variable(var)
# var = empty
#variable = var
end
end
and
# b.rb
class B
def initialize(module_a)
#module_a = module_a
end
def set_variable_in_a(data)
#module_a.set_variable(data)
end
def do_something(variable)
# variable = empty
set_variable_in_a("hello world")
end
end
This is just an example of what I'm dealing with. If I'm trying to start a function in Class A, which is supposed to do something in ClassB and then change an instance variable in Class A, I'm not sure how to do this properly. This is what I've tried, however:
a = A.new
a.pass_to_b
Class B cannot see the instance variable #variable, and if it tries to set_variable_in_a, that doesn't work either. It's like the do_something function in Class A successfully calls the do_something function in Class B, but the instance variable information is not available. I thought by passing self to Class B, we'd be able to at least call the function
My MRI throws exeption about
def pass_to_b(self)
because you can't pass self to method as argument.
You need delete 'self' how argument
Run code below and you will see that #variable of instance of Class A has '123hello world' string
class A
def initialize
#variable = "123"
#module_b = B.new(self)
end
def pass_to_b
#module_b.do_something(#variable)
end
def set_variable(var)
# var = empty
#variable = var
end
end
# b.rb
class B
def initialize(module_a)
#module_a = module_a
end
def set_variable_in_a(data)
#module_a.set_variable(data)
end
def do_something(variable)
set_variable_in_a(variable + "hello world")
end
end
a = A.new
a.pass_to_b
display variable 'a' and you will see something like this
#<A:0x00007fdaba0f3c90 #variable="123hello world", #module_b=#<B:0x00007fdaba0f3c40 #module_a=#<A:0x00007fdaba0f3c90 ...>>>

Rails: difference between self.function and self.class.function

I am not sure I understand why I get a NoMethodError exception if I replace "var3 = self.class.function2" with "var3 = self.function2"
When should I use self and when should I use self.class ?
class TestClass
var1 = nil
def self.function1
var1 = "hello"
end
def self.function2
p self.function1
var2 = "world"
end
def function3
var3 = self.class.function2
p var3
end
end
myvar = TestClass.new
myvar.function3
def self.function2 is your class method that can not be called with instance of class. It call like TestClass.function2. While def function3 is instance method. You are calling it right.
myvar = TestClass.new
myvar.function3
So if we follow flow. Under function3 self will become instance that is calling that function.
var3 = self.class.function2 # Here self is myvar
# self.class == TestClass
# self.class.function2 == TestClass.function2 # No error
# self.function2 == myvar.function2 # error, Calling class method with instance of class.
Now if you try to call class method with instance it will surely through error.
Because the def self.function2 means, the function2 is "wired" to the class (TestClass) not to the instance of class (TestClass.new return instance of class TestClass). The call self.class returns the class (TestClass) where is the function2 based.
The function2 can be also called this way: TestClass.function2

overriding updateGradInput method in torch is not working for my self defined module

I implemented a module called sharedModule for my own use. And I have overriden the updateGradInput method below:
function SharedModule:updateGradInput(input, gradOutput)
test_grad = {}
print("call updateGradInput")
test_input = input
test_gradOutput = gradOutput
assert(type(gradOutput) == 'table' and #input == #gradOutput)
local T = #input
for t = 1, T do
self.gradInput[t] = self.clones[t]: updateGradInput(input[t], gradOutput[t])
test_grad[t] = self.gradInput[t]
end
print(#self.gradInput) -- print normal value
--self.gradInput = test_grad --
return self.gradInput -- empty, ???
end
However, when i call backward method on my module, the self.gradInput field is not updated, what's the problem, any one can help me out?
backward method will call two methods named updateGradInput and accGradParams, turns out that the error occurs in accGradParams because of typos

how to get url of an object in cherrypy?

I am new to CherryPy. I am using the default dispatcher, with a URL structure similar to this:
root = Root()
root.page1 = Page1()
root.page1.apple = Apple()
root.page2 = Page2()
root.page2.orange = Orange()
Orange renders a template, in which I need a link to Apple. I could just hardcode /page1/apple/. But how can I get the URL of Apple in a DRY manner?
Can this be done with the default dispatcher in CherryPy, or is it only possible with the Routes dispatcher?
(I am coming from the Django world, where one would use reverse() for this purpose.)
You can access to the mounted apps through
cherrypy.tree.apps[mount_point].root
root is always the mounted instance to the mount point. So a reverse function would look like:
def reverse(cls):
# get link to a class type
for app_url in cherrypy.tree.apps.keys():
if isinstance(cherrypy.tree.apps[app_url].root, cls):
# NOTE: it will return with the first mount point of this class
return app_url
Please find a sample code below that uses your classes. http://localhost:8080/page4/orange/ prints out { Orange and the link to apple: : "/page3/apple" }
import cherrypy
link_to_apple_global = ''
class Orange(object):
def __init__(self):
pass
#cherrypy.expose
#cherrypy.tools.json_out()
def index(self):
return {"Orange and the link to apple: ": link_to_apple_global}
class Page2(object):
def __init__(self):
pass
#cherrypy.expose
def index(self):
return "Page2"
class Apple(object):
def __init__(self):
pass
#cherrypy.expose
def index(self):
return "Apple"
class Page1(object):
def __init__(self):
pass
#cherrypy.expose
def index(self):
return "Page1"
class Root(object):
def __init__(self):
pass
#cherrypy.expose
def index(self):
return "Root"
def reverse(cls):
#return cherrypy.tree.apps.keys()
#return dir(cherrypy.tree.apps[''].root)
#return dir(cherrypy.tree.apps['/page3/apple'].root)
# get link to apple
for app_url in cherrypy.tree.apps.keys():
if isinstance(cherrypy.tree.apps[app_url].root, cls):
# NOTE: it will return with the first instance
return app_url
root = Root()
root.page1 = Page1()
root.page1.apple = Apple()
root.page2 = Page2()
root.page2.orange = Orange()
cherrypy.tree.mount(root, '/')
# if you do not specify the mount points you can find the objects
# in cherrypy.tree.apps[''].root...
cherrypy.tree.mount(root.page1, '/page4')
cherrypy.tree.mount(root.page2, '/page3')
cherrypy.tree.mount(root.page2.orange, '/page4/orange')
cherrypy.tree.mount(root.page1.apple, '/page3/apple')
link_to_apple_global = reverse(Apple)
cherrypy.engine.start()
cherrypy.engine.block()

mocking out a lua module using package.preload

I'm trying to write a unit test against a single module function. This module collaborates with a few other modules, so I'd like to mock those modules out to isolate my system under test. Here's some simplified pseudo code:
local moduleFoo={}
local moduleBaz= require("moduleBaz")
moduleFoo.doSomething = function (arg)
if moduleBaz.bar.neatMethod(arg) then
--does something interesting
end
end
return moduleFoo
And here's the code for moduleBaz
local moduleBaz={}
moduleBaz.bar= {}
moduleBaz.bar.neatMethod=function(arg)
--does something neat
end
return moduleBaz
I'm trying to use the package.preload function to inject a mock instance of moduleBaz before my tests run, but it doesn't appear to work (i.e. the real instance of the moduleBaz is used in the test, not my mock)
Here's some psueudo test code:
package.loaded.moduleBaz= nil
local moduleBaz = {}
moduleBaz.bar = {}
moduleBaz.bar.neatMethod= function(guid) return true end
package.preload['moduleBaz'] = function ()
return moduleBaz
end
local foo= require("moduleFoo")
foo.doSomething('asdasdasda')--real moduleBaz is called, not my mock!
Any ideas what I'm doing wrong? I'm very new to Lua, and not at all comfortable with how scope is handled in the language!
You seem to be missing a return statement in your moduleBaz code
return moduleBaz
Why not use package.loaded as it gives you a simpler interface? package.loaded.moduleBaz would simply need to include whatever you'd want to return from your moduleBaz code. Something like this should work or give you an idea:
package.loaded.moduleBaz = {
bar = {
neatmethod = function(arg)
-- your mock code here
end,
}
}
Then require('moduleBaz') would simply return that object you just created.
I cannot reproduce the issue with your setup either. The files I used are below; notice that I added return moduleBaz as I described above, but this is the only change I made:
file moduleBaz.lua:
local moduleBaz={}
moduleBaz.bar= {}
moduleBaz.bar.neatMethod=function(arg)
print "baz"
return true
end
return moduleBaz
file moduleFoo.lua:
local moduleFoo={}
local moduleBaz= require("moduleBaz")
moduleFoo.doSomething = function (arg)
if moduleBaz.bar.neatMethod(arg) then
print "foo"
end
end
return moduleFoo
file testFoo.lua
package.loaded.moduleBaz= nil
local moduleBaz = {}
moduleBaz.bar = {}
moduleBaz.bar.neatMethod= function(guid) print "mock" return true end
package.preload['moduleBaz'] = function ()
return moduleBaz
end
local foo= require("moduleFoo")
foo.doSomething('asdasdasda')--real moduleBaz is called, not my mock!
When I run this, I get mock\nfoo\n printed as expected.

Resources