Unable to call custom method - django-models

I am newbie at Django. I have model with a custom method. In view I am
retrieving a single object.
Here is my code -- My model
class Problem(models.Model):
problem = models.CharField(max_length=100)
solution=models.CharField(max_length=500)
def __unicode__(self):
return self.problem
def retrieve_rankdata(self):
return self.problem.split()[0].split('/')
in view I am doing this
def show(request):
problem = Problem.objects.all()[0]
t1=problem.retrieve_rankdata()
But, I am getting this error
'Problem' object has no attribute 'retrieve_rankdata'
What am I doing wrong?

It's a bit hard to tell, but the problem could be with your indentation. The indentation in the code you've pasted is inconsistent, so it wouldn't work properly anyway - I suspect in your actual code, def retrieve_rankdata is a couple more spaces to the left.
Don't forget that Python uses indentation to tell whether or not an attribute or a method is part of a class. So if your def retrieve_rankdata line is not actually indented at the same level as the def __unicode__ one, it won't be considered part of the Problem class.

Related

Wrapping HTML tags using Yield with Ruby

Ruby beginner here.
I am trying to understand yield and how to wrap HTML tags around it and I have been having issues with this code.
def tag (tag_name, attributes = nil)
"<#{tag_name}#{attributes}>#{yield}</#{tag_name}>"
end
style_tag = tag("div", ["class=", "red"]) do
tag("h1") do
"Google it"
end
end
my output is :
"<div[\"class=\", \"red\"]><h1>Google it</h1></div>"
Thank you
The issue is not with yield wich seems to be working fine, but with the attributes parameter. Or rather inserting the parameter into the string.
At the moment you are doing an implicit Array.to_s which is where the brackets come from. If you are sure the attributes string is correct, you can do a simple ...#{attributes.join} ... to join all elements to a proper string (provided the HTML syntax is correct and so on).

How do I make a custom tensorflow probability layer?

I am trying to make a tensorflow probability probabilistic model that learns the linear relation as well as the error in Linear Regression. Obviously its a toy problem and as been kind of solved in an official tutorial. There the model is
model = tf.keras.Sequential([
tf.keras.layers.Dense(1 + 1),
tfp.layers.DistributionLambda(
lambda t: tfd.Normal(loc=t[..., :1],
scale=1e-3 + tf.math.softplus(t[...,1:]))),
])
The problem is that this learns the relation where the error is a function of the independent variable.
If I do not want that I can make the following model
std_val=tf.Variable(1.)
model = Sequential([
Dense(1,input_shape=(1,)),
tfpl.DistributionLambda(lambda t: tfd.Independent(tfd.Normal(loc=t,
scale=std_val)))
])
and indeed it gives the correct result but also the following warning
WARNING:tensorflow:
The following Variables were used a Lambda layer's call (distribution_lambda_22), but
are not present in its tracked objects:
<tf.Variable 'Variable:0' shape=() dtype=float32>
It is possible that this is intended behavior, but it is more likely
an omission. This is a strong indication that this layer should be
formulated as a subclassed Layer rather than a Lambda layer.
My question is how do I go about making the subclassed Layer the message is talking about?
I found one way to do it but it would still be useful to know a more general way to make custom Distribution layers. The way I have is to subclass the DistributionLambda layer
class MyClass(tfp.layers.DistributionLambda):
def __init__(self):
self.std_val = tf.Variable(1.)
super().__init__(lambda t: tfd.Independent(tfd.Normal(loc=t,scale=self.std_val)))
model = Sequential([
Dense(1,input_shape=(1,)),
MyClass()
])

Why was I able to get away with not using a splat operator sometimes

I have some ruby code from my Ruby on Rails project.
I am formatting some data so I am calling attributes.extract! to get the fields I need from my model.
I noticed recently that every now and then the data wouldn't get extracted as expected. I realized that I needed a splat operator. But it is strange because I do notice that sometimes when the method is called in my Rails project it will sometimes extract the data without the use of the splat operator. But when I run the code from my Rails console it never extracts the data unless I add the splat operator.
Here is the code in question
# in a service file, let's call it service.rb
def self.format_user_home_address_data(user)
# This doesn't work in the console but sometimes works when run in my Rails project
home_address_data = user.attributes.extract!(User::HOME_ADDRESS_FIELDS)
home_address_data[:address_type] = "home"
home_address_data
end
# at the end this method will sometimes return { address_type: "home" } or
# sometimes it'll actually return the extracted attributes as expected
HOME_ADDRESS_FIELDS is just an array with the values ["address_line_1", "city", "state", "zip"]
Anyway I know that to get it to run correctly I need to do this
home_address_data = user.attributes.extract!(*User::HOME_ADDRESS_FIELDS)
But does anyone know why I was able to get away without adding the splat operator for so long? Is there some Ruby on Rails magic that is only sometimes happening? What's the deal?
Well, let's check it out. There is no any magic behind attributes.extract! in the end. Here is an actual implementation of this method from Rails source code:
def extract!(*keys)
keys.each_with_object(self.class.new) { |key, result|
result[key] = delete(key) if has_key?(key)
}
end
Link: click. As you can see, it creates new hash, goes over the keys one by one and moves value from self to this new array. So, if you give an Array argument to this method then key in the block will be an Array as well. So, it won't be found. So, no way it may work for array argument. The only one possibility is that something else is passed instead of User::HOME_ADDRESS_FIELDS.

peewee get_or_create and then save: error binding

Is there an easy way to update a field on a get of a get_or_create?
I have a class ItemCategory and I want to either create a new entry or get the already created entry and update a field (update_date).
What I do is:
item,created= ItemCategory.get_or_create(cat=cat_id,item=item_id)
if created == True:
print "created"
else:
item.update_date = datetime.now
item.somethingelse = 'aaa'
item.save()
This works for a while in my loop. But after 50-100 get/create it crashes:
peewee.InterfaceError: Error binding parameter 4 - probably unsupported type.
Maybe I should use upsert(), I tried but wasn't able to get anything working. Also it's not probably the best solution, since it makes a replace of the whole row instead of just a field.
I like peewee, it's very easy and fast to use, but I can't find many full examples and that's a pity
Newbie mistake
item.update_date = datetime.now()
I am not 100% sure this is the only answer though. I modified my code so many times that it might be also something else.
Regarding my question about create_or_update , I've done this:
try:
Item.create(...)
except IntegrityError:
Item.update(...)
peewee is really great, I wonder why no one ever asked for a create_or_update.

InvalidOperationException in Fsharp.Core.dll

So I am doing a simple personal project in winforms with F#. My code used to work, but now throws this exception for seemingly no reason.
An unhandled exception of type 'System.InvalidOperationException' occurred in FSharp.Core.dll
Additional information: The initialization of an object or value resulted in an object or value being accessed recursively before it was fully initialized.
The code is a member method that is being invoked from the constructor of the form itself
do
//lots of other constructor code before this point
// render the form
form.ResumeLayout(false)
form.PerformLayout()
form.ReloadGoals
//several other members before here
member form.ReloadGoals =
let x = 10 //crashes on this line
The website where I grabbed the template for the project I am using is this one.
Unfortunately I have made some substantial additions to this.
I would be glad to post more code, but I need to know what code would be relevant exactly, as I am not exactly sure and don't want to bog down the post in extraneous code.
Also I can't really find a lot of documentation on System.InvalidOperationException.
Every time I find it, it is being used as an example of an exception you can throw on your own, not what causes it.
See The F# 3.0 Language Specification (final version, PDF), ยง8.6.1 Primary Constructors in Classes:
During construction, no member on the type may be called before the last value or function definition in the type
has completed; such a call results in an InvalidOperationException.
Almost certainly, your code in the question doesn't tell the full story. If you hit the above
mentioned restriction, then there's somewhere an attempt to access a field or member not fully initialized.
Some example:
type X() as this =
let x = this.X
member __.X = 42
X()
One workaround might be to encapsulate the offending code in a member of its own and call that in the constructor instead. Another would be the wrapping in a function definition.
This will be an incomplete answer, since I cannot reproduce the problem (using F# interactive, the given example, the ReloadGoals modification, and Form.Show, the code runs fine). However, there are strange things happening:
Taken from the template, there should be a handler method for the Form.Load event, which fires when the type is fully constructed. Why is additional loading code in the constructor instead of this event handler? Load exists precisely to counter this kind of problem with unorderly initialization.
The template you are using isn't exactly sane F#. For example, initControls is a value of type unit that is evaluated where it is defined; its binding to a name is absolutely useless and should be replaced with a simple do. Writing initControls in the do block later has no effect at all. form.ResumeLayout(false); form.PerformLayout() should be equivalent to form.ResumeLayout(true), but I don't understand what these are doing in the constructor in the first place. The event handlers have two possibly unnecessary indirections: one to a delegate constructor, another to a method that has no real reason to exist -- the handlers should be lambdas or simple, private functions. Why are they public members?!
The error appearing in the question is probably caused by the usage of form in its own constructor. Move your new usage to the Load event handler, and it should work.
Personally, I would go further and ditch implementation inheritance by instantiating a plain Form and subscribing to its events. For example, in FSI, something similar to the template could be done like this:
open System.Drawing
open System.Windows.Forms
let form = new Form()
form.ClientSize <- new Size(600, 600)
form.Text <- "F# Form"
let formLabel = new Label()
formLabel.Text <- "Doubleclick test!"
formLabel.DoubleClick.Add <| fun _ -> form.Close()
form.Controls.Add(formLabel)
form.Show()
which uses no inheritance at all. (In an application, you'd use Application.Run etc instead of form.Show().) This does not run into initialization problems as easily and, additionally, is very useful if you want to encapsulate the form inside a simpler type or even just a function.

Resources