get at instance variable from inside constructor - ruby-on-rails

Hi Im having this problem that when Im creating a class in coffeescript I want to define a function on an object in the contructor, but I cant figure out the scope, see the code example belove
collection_of_objects = [{id:234},{id:546},{id:234}]
class SampleObject
constructor: (collection_of_objects)->
#posts = []
#divide_number = 1337
for post in collection_of_objects
post.magicnr = ()->
return #id / #divide_number
the id get set but I cant get at divide_number from inside the magicnr function
i realize its due to the scope, but I cant seem to figure out how to do it
i tried to make a getDivideNumber function that returns it but I cant seem to access that inside the magicnr function either
any help would be appreciated
UPDATE
Had to settle for the following hack
collection_of_objects = [{id:234},{id:546},{id:234}]
class SampleObject
#divide_number = 1337
divide_number = #divide_number
constructor: (collection_of_objects)->
#posts = []
for post in collection_of_objects
post.magicnr = ()->
return #id / divide_number
# for updating the #divide_number
setDivnr: (nr)->
#divide_number = nr
divide_number = #divide_number

This is because when you are defining magicnr you change scope. this (#) becomes post.
You can get round this either by caching a reference to #divide_number:
for post in collection_of_objects
divide_number = #divide_number
post.magicnr = ()->
return #id / divide_number
or by using a fat arrow to define post.magicnr like this:
for post in collection_of_objects
post.magicnr = ()=>
return post.id / #divide_number

Related

How to get the result using neo4j-driver functions as same as the result from evaluate() function in py2neo?

def get_nlg(graph_query):
driver = Graph("neo4j://localhost:7687", auth=("neo4j","password"))
graph_response = graph.evaluate(graph_query)
For the above code, I replaced with the driver code as below, but its not working, what is the function in neo4j driver equivalent to evaluate() function in py2neo?
def get_nlg(graph_query):
driver = GraphDatabase.driver("neo4j://localhost:7687", auth=("neo4j","password"))
with driver.session() as session:
graph_response = session.run(graph_query)
return graph_response
When the result from graph_response of 2nd code is passed to the below code, I am getting an error
TypeError: <neo4j.work.result.Result object at 0x7f94cf7f31d0> is not JSON serializable
class GetBiggestComponent(Action):
def name(self):
return "action_get_biggest_component"
def run(self, dispatcher, tracker, domain):
query = None
intent = tracker.latest_message['intent']
child_comp = tracker.get_slot('component_type_child')
parent_comp = tracker.get_slot('component_type_parent')
error = None
graph_response = GenerateQuery.get_biggest_component(child_comp, parent_comp)
graph_response['intent_name'] = intent['name']
dispatcher.utter_message(json.dumps(graph_response))
return []
the error is coming when it is passed in the line
dispatcher.utter_message(json.dumps(graph_response))
The output of session.run is an object that lets you navigate the result, not the result itself. I strongly recommend reading the manual and API docs for the driver, as this is all described in there.
https://neo4j.com/docs/driver-manual/current/session-api/simple/#driver-simple-result-consume
https://neo4j.com/docs/api/python-driver/current/api.html#result
As per my answer to your other question, to simulate evaluate, you will simply need to navigate to the first record of the result and then return the first value of that record.

how to pass additional parametes to spider parse function in scrapy during web scraping

I am trying to pass additional information to the parse function but it is giving a type error.
TypeError: parse() got an unexpected keyword argument 'body'
i am unable to resolve this issue.
"""
return [scrapy.Request(url=website.search_url.format(prod), callback=self.parse,
cb_kwargs = {"body":website.body_xpath,"product_list":website.products_list_xpath,
"names":website.products_name_xpath,"selling_price":website.selling_price_xpath,
"market_price":website.market_price_xpath}) for website in websites for prod in modified_products]
def parse(self, response):
body = response.cb_kwargs.get("body")
product_list = response.cb_kwargs.get("product_list")
name = response.cb_kwargs.get("names")
selling_price = response.cb_kwargs.get("selling_price")
market_price = response.cb_kwargs.get("market_price")
"""
I forgot to write those names in parse function definition, after adding them i am getting the correct result. Thanks for having a look at it.
"""
return [scrapy.Request(url=website.search_url.format(prod), callback=self.parse,
cb_kwargs = dict(body = website.body_xpath, product_list = website.products_list_xpath,
name = website.products_name_xpath, selling_price = website.selling_price_xpath,
market_price = website.market_price_xpath)) for website in websites for prod in modified_products]
def parse(self, response, body, product_list, name, selling_price, market_price):
body = response.cb_kwargs["body"]
product_list = response.cb_kwargs["product_list"]
name_ = response.cb_kwargs["name"]
selling_price_ = response.cb_kwargs["selling_price"]
market_price_ = response.cb_kwargs["market_price"]
"""

Scoping classes created in Lua using Luabind

I am aware that Lua classes can be created using the OO system that Luabind exposes to Lua:
http://www.rasterbar.com/products/luabind/docs.html#defining-classes-in-lua
class 'lua_testclass'
function lua_testclass:__init(name)
self.name = name
end
function lua_testclass:print()
print(self.name)
end
a = lua_testclass('example')
a:print()
However I am unable to figure out how to scope the class within another namespace so I can do the following:
a = MyScope.lua_testclass('example')
a:print()
Anyone has a idea. I do not want my classes to pollute the global namespace in Lua.
Luabind's class function will always pollute the global table. However, you can clean up after it:
function newclass(name)
oldglobal = _G[name]
class(name)
cls = _G[name]
_G[name] = oldglobal
return cls
end
Then you would use it like this:
MyScope.lua_testclass = newclass 'lua_testclass'
Analogous to local mod = require 'mod' you have to spell the name of the class twice, but you could easily build another function on top of this that could be used like setclass(MyScope, 'lua_testclass'), automatically putting the class into MyScope:
function setclass(scope, name) scope[name] = newclass(name) end
Disclaimer: All this code is entirely untested.
I did mine a little differently, but it's generally the same concept. Mine doesn't create the class, but rather just moves it. I also implemented it on the C++ side.
To implement what I did in Lua, you would write:
function moveClass(name)
oldGlobal = _G[name]
_G[name] = nil
return oldGlobal
end
To implement it in C++, you would write:
luabind::module(lua) [
luabind::def("moveClass", +[](lua_State * lua, std::string name) {
// In the case the class does not exist, this will just
// remove nil and return nil. That essentially does nothing.
luabind::object oldGlobal = luabind::globals(lua)[name];
luabind::globals(lua)[name] = luabind::nil;
return oldGlobal;
})
];
So now if you were to use that to move a class you created, you would do this:
class 'MyClass'
myTable = {}
myTable.MyClass = moveClass 'MyClass'
As an extra note, if you want the moveClass function to give an error in the case that the class you are trying to move does not exist, use luabind::type(oldGlobal) == LUA_TNIL to determine if the class existed or not.
Example:
luabind::module(lua) [
luabind::def("moveClass", +[](lua_State * lua, std::string name) {
luabind::object oldGlobal = luabind::globals(lua)[name];
if (luabind::type(oldGlobal) == LUA_TNIL) {
throw std::runtime_error("Class does not exist.");
}
luabind::globals(lua)[name] = luabind::nil;
return oldGlobal;
})
];

Why JAX-WS generates wrapper for all method arguments?

I am trying to generate web service interface using jax-ws, but i am getting a methods with wrapper class for all arguments instead of arguments list. For example:
#SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
#WebResult(name = "ResendControlsToDmiResponse", targetNamespace = "http://tempuri.org/", partName = "parameters")
#WebMethod(operationName = "ResendControlsToDmi", action = "http://tempuri.org/ResendControlsToDmi")
#Generated(value = "org.apache.cxf.tools.wsdlto.WSDLToJava", date = "2014-01-30T16:01:26.266+02:00")
public ResendControlsToDmiResponse resendControlsToDmi(
#WebParam(partName = "parameters", name = "ResendControlsToDmiData", targetNamespace = "http://tempuri.org/")
ResendControlsToDmiData parameters
);
Can't understand why it's happening and how to generate method with corredct signature.
There rules about the naming of the part elements as they related to the operation name. In your case, it looks like the operation is named resendControlsToDmi, but the incoming data part/element is named ResendControlsToDmiData. Remove the Data off the end of that and it may change. The response element is properly ResendControlsToDmiResponse.

Django-Admin Exception Value: 'DeclarativeFieldsMetaclass' object is not iterable

I have one form in forms.py
class EmailForm(forms.Form):
recipient = forms.CharField(max_length=14, min_length=12,
widget=forms.TextInput(attrs=require))
message = forms.CharField(max_length=140, min_length=1,
widget=forms.Textarea(attrs={'cols': 30, 'rows': 5}))
and my site url is
admin.autodiscover()
urlpatterns = patterns('', (r'^admin/(.*)',
include(admin.site.urls)),)
now I want it to be shown on admin interface
I tried so far
First attempt
from myapps.forms import EmailForm
class EmailAdmin(admin.ModelAdmin):
form = EmailForm
did not work Exception Value:
'DeclarativeFieldsMetaclass' object is not iterable
Second attempt
and now I followed http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contri...
but could not get help
class EmailAdmin(admin.ModelAdmin):
def my_view(self,request):
return admin_my_view(request,self)
def get_urls(self):
urls = super(SmsAdmin, self).get_urls()
my_urls = patterns('',(r'^my_view/
$',self.admin_site.admin_view(self.my_view)))
return my_urls + urls
def admin_my_view(request, model_admin):
opts = model_admin.model._meta
admin_site = model_admin.admin_site
has_perm = request.user.has_perm(opts.app_label \
+ '.' + opts.get_change_permission())
context = {'admin_site': admin_site.name,
'title': "My Custom View",
'opts': opts,
'root_path': '/%s' % admin_site.root_path,
'app_label': opts.app_label,
'has_change_permission': has_perm}
template = 'admin/demo_app/admin_my_view.html'
return render_to_response(template,
context,context_instance=RequestContext(request))
admin.site.register(EmailForm,EmailAdmin)
and when I run server and type on browser localhost:8000/admin
and hit enter button
Exception Value:
'DeclarativeFieldsMetaclass' object is not iterable
and second time just after first time when I again enter then it show
me the admin page but I can't see my EmailAdmin in admin interface..
Just help me or suggest me any link.
Thanks
(This is my attempt at reformatting your model code):
class EmailForm(forms.Form):
recipient = forms.CharField(max_length=14, min_length=12,
widget=forms.TextInput(attrs=require))
message = forms.CharField(max_length=140, min_length=1,
widget=forms.Textarea(attrs={'cols': 30, 'rows': 5}))
I would put my money on the bit that says "attrs=require" -- if that's not a typo.
What you want instead is something like this:
recipient = forms.CharField(max_length=14, min_length=12,
widget=forms.TextInput(), required=True)

Resources