How to override the write method in res.users class - overriding

I want to inherit the res.users class and override her write method, so I wrote this code:
class User(models.Model):
_inherit = 'res.users'
is_commercial = fields.Boolean(string= 'is Commercial')
#api.multi
def write(self, values):
super(User, self).write()
for partner in self.partner_id:
partner.is_commercial = self.is_commercial
and I created this res.partner class too:
class Partner(models.Model):
_inherit = 'res.partner'
is_commercial = fields.Boolean(string= 'is Commercial')
Now when I try to change the is_commercial content it appears this error:
TypeError: write() got an unexpected keyword argument 'context'
It appears to me that there's a syntaxe error in overriding the write method in res.users class. Can someone help me? Thanks.

You can try this: replace super(User, self).write() with super(User, self).write(values). That should work.

How to override the write method in res.users class: You just need to write this code to override the write method:
class User(models.Model):
_inherit = 'res.users'
#api.multi
def write(self, vals):
res = super(User, self).write(vals)
your code here...
return res

When you call write(), you should pass any argument or context. So you can pass values in write() method. Like below
super(User, self).write(values)
because write() take dictionary type data.

When you call write(), try passing any argument or context.
For example:
#api.multi
def action_cancel(self):
res = super(SaleOrder, self).action_cancel()
.
.
your logic
.
.
return res

Related

parameterized task to swap two values in SystemVerilog

I want to write a generic-width swap, but I'm not sure what the syntax should be.
My first guess:
task automatic swap #( int W=1 ) ( ref logic [W-1:0] a, ref logic [W-1:0] b );
begin
automatic logic[W-1:0] temp=a; a=b; b=temp;
end endtask
But I get the following error (from Cadence irun):
ncvlog: *E,SVNOCS: Class specialization syntax not allowed in method name for out-of-block method declaration.
Also, what is the syntax to invoke such a task?
Tasks and functions cannot have their own parameters. You can achieve the same effect by declaring a static method in a parameterized class. The methods can be made more generic by making the parameter a data type instead of a bit width. Example:
class generic #(type T=logic);
// Note: you may want to replace 'ref' with 'inout'
static function void swap( ref T a, b );
{b,a} = {a,b};
endfunction
endclass
Then somewhere in your code, you can do this like:
generic#(logic[4:0])::swap( my_a, my_b);
generic#(int)::swap( my_int_a, my_int_b);
generic#(my_struct_st)::swap( my_struct_a, my_struct_b);
generic#(my_class)::swap( my_class_a, my_class_b);
generic#(virtural my_interface)::swap( my_if_a, my_if_b);

How to call inputTask from within another inputTask?

In a inputTask I'm programmatically calling another inputTask, e.g. testOnly, with parameter string as follows:
val readParams = inputKey[Unit]("reads version")
readParams := {
... // here some Parser code
val a = "*OnlyThisClassPls*"
testOnly.toTask(a)
}
Unfortunately instead of result I get an exception Illegal dynamic reference. Why?
I think I solved my problem.
I created a method which converts testOnly inputTask to dynamic task (taskDyn) with parameter
def testOnlyWithDynamicParams(params: String) = Def.taskDyn {
(testOnly in Test).toTask(params)
}
I defined an dynamic input task (inputTaskDyn) which uses method to convert and evaluates value at the end
readParams := Def.inputTaskDyn {
... // here some Parser code
val paramsForTestOnly = " *OnlyThisClassPls*"
testOnlyWithDynamicParams(paramsForTestOnly)
}.evaluated
I'm not sure if it is a best way but it works for me. If you know the better solution please correct me.

Ruby, what is the difference between a setter and initialize method

class Account
def initialize(starting_balance = 0)
#balance = starting_balance
end
def balance #instance getter method
#balance #instance variable visible only to this object
end
def balance=(new_amount)
#balance = new_amount
end
def deposit(amount)
#balance+=amount
end
##bank_name= "MyBank.com" # class (static) variable
# A class method
def self.bank_name
##bank_name
end
# or: def SavingsAccount.bank_name : ##bank_name : end
end
I want to understand the code snippets in bold. What do they do? what is the difference between a setter and initialize method.
If I had an object test=Account.new() and why is test(30) giving an error. Isn't that suppose to call the setter method with parameter 30 and set the balance?
initialize is the method that is called on the newly created object when you do Account.new or Account.new(my_starting_balance). In the first case initialize would be called with the default value 0 for starting_balance and in the second with my_starting_balance.
The setter method balance= is called when you do my_account.balance = some_value where my_account is an instance of the class Account. So if you have the following code, initialize will be called on line 1 (with 0 as its argument) and balance= on line 2 (with 23) as its argument:
my_account = Account.new
my_account.balance = 23
Of course in this case I could just as well write the following and not use the setter method at all:
my_account = Account.new(23)
However that doesn't always work because some times you might want to change the value of balance after the object has already been created.
If I had an object test=Account.new() and why is test(30) giving an error.
Because test(30) means "call the method test with the argument 30" and there is no method called test in your code.
Regarding the second bolded part of your code: As the comments indicate, it sets a class variable named ##bank_name and defines a class method that returns that variable's value.

Is there an easy (idiomatic) way to convert a java.lang.reflect.Method to a Scala function?

Can I retrieve a Method via reflection, somehow combine it with a target object, and return it as something that looks like a function in Scala (i.e. you can call it using parenthesis)? The argument list is variable. It doesn't have to be a "first-class" function (I've updated the question), just a syntactic-looking function call, e.g. f(args).
My attempt so far looks something like this (which technically is pseudo-code, just to avoid cluttering up the post with additional definitions):
class method_ref(o: AnyRef, m: java.lang.reflect.Method) {
def apply(args: Any*): some_return_type = {
var oa: Array[Object] = args.toArray.map { _.asInstanceOf[Object] }
println("calling: " + m.toString + " with: " + oa.length)
m.invoke(o, oa: _*) match {
case x: some_return_type => x;
case u => throw new Exception("unknown result" + u);
}
}
}
With the above I was able to get past the compiler errors, but now I have a run-time exception:
Caused by: java.lang.IllegalArgumentException: argument type mismatch
The example usage is something like:
var f = ... some expression returning method_ref ...;
...
var y = f(x) // looks like a function, doesn't it?
UPDATE
Changing the args:Any* to args:AnyRef* actually fixed my run-time problem, so the above approach (with the fix) works fine for what I was trying to accomplish. I think I ran into a more general issue with varargs here.
Sure. Here's some code I wrote that add an interface to a function. It's not exactly what you want, but I think it can be adapted with few changes. The most difficult change is on invoke, where you'll need to change the invoked method by the one obtained through reflection. Also, you'll have to take care that the received method you are processing is apply. Also, instead of f, you'd use the target object. It should probably look something like this:
def invoke(proxy: AnyRef, method: Method, args: Array[AnyRef]) = method match {
case m if /* m is apply */ => target.getClass().getMethod("name", /* parameter type */).invoke(target, args: _*)
case _ => /* ??? */
}
Anyway, here's the code:
import java.lang.reflect.{Proxy, InvocationHandler, Method}
class Handler[T, R](f: Function1[T, R])(implicit fm: Manifest[Function1[T, R]]) extends InvocationHandler {
def invoke(proxy: AnyRef, method: Method, args: Array[AnyRef]) = method.invoke(f, args: _*)
def withInterface[I](implicit m: Manifest[I]) = {
require(m <:< manifest[Function1[T, R]] && m.erasure.isInterface)
Proxy.newProxyInstance(m.erasure.getClassLoader(), Array(m.erasure), this).asInstanceOf[I]
}
}
object Handler {
def apply[T, R](f: Function1[T, R])(implicit fm: Manifest[Function1[T, R]]) = new Handler(f)
}
And use it like this:
trait CostFunction extends Function1[String, Int]
Handler { x: String => x.length } withInterface manifest[CostFunction]
The use of "manifest" there helps with syntax. You could write it like this:
Handler({ x: String => x.length }).withInterface[CostFunction] // or
Handler((_: String).length).withInterface[CostFunction]
One could also drop the manifest and use classOf instead with a few changes.
If you're not looking for a generic invoke that takes the method name--but rather, you want to capture a particular method on a particular object--and you don't want to get too deeply into manifests and such, I think the following is a decent solution:
class MethodFunc[T <: AnyRef](o: Object, m: reflect.Method, tc: Class[T]) {
def apply(oa: Any*): T = {
val result = m.invoke(o, oa.map(_.asInstanceOf[AnyRef]): _*)
if (result.getClass == tc) result.asInstanceOf[T]
else throw new IllegalArgumentException("Unexpected result " + result)
}
}
Let's see it in action:
val s = "Hi there, friend"
val m = s.getClass.getMethods.find(m => {
m.getName == "substring" && m.getParameterTypes.length == 2
}).get
val mf = new MethodFunc(s,m,classOf[String])
scala> mf(3,8)
res10: String = there
The tricky part is getting the correct type for the return value. Here it's left up to you to supply it. For example,if you supply classOf[CharSequence] it will fail because it's not the right class. (Manifests are better for this, but you did ask for simple...though I think "simple to use" is generally better than "simple to code the functionality".)

instantiate object with reflection using constructor arguments

I'm trying to figure out how to instantiate a case class object with reflection. Is there any support for this? The closest I've come is looking at scala.reflect.Invocation, but this seems more for executing methods that are a part of an object.
case class MyClass(id:Long, name:String)
def instantiate[T](className:String)(args:Any*) : T = { //your code here }
Is close to the API I'm looking for.
Any help would be appreciated.
scala> case class Foo(id:Long, name:String)
defined class Foo
scala> val constructor = classOf[Foo].getConstructors()(0)
constructor: java.lang.reflect.Constructor[_] = public Foo(long,java.lang.String)
scala> val args = Array[AnyRef](new java.lang.Integer(1), "Foobar")
args: Array[AnyRef] = Array(1, Foobar)
scala> val instance = constructor.newInstance(args:_*).asInstanceOf[Foo]
instance: Foo = Foo(1,Foobar)
scala> instance.id
res12: Long = 1
scala> instance.name
res13: String = Foobar
scala> instance.getClass
res14: java.lang.Class[_] = class Foo
Currently there is not much reflection support in Scala. But you can fall back to th Java Reflection API. But there are some obstacles:
You have to create a Array[AnyRef] and box your "primitive types" in the wrapper classes (java.lang.Integer, java.lang.Character, java.lang.Double, ...)
newInstance(Object ... args) gets an varargs array of Object, so you should give the type inferer a hint with :_*
newInstance(...) returns an Object so you have to cast it back with asInstanceOf[T]
The closest I could get to your instantiate function is this:
def instantiate(clazz: java.lang.Class[_])(args:AnyRef*): AnyRef = {
val constructor = clazz.getConstructors()(0)
return constructor.newInstance(args:_*).asInstanceOf[AnyRef]
}
val instance = instantiate(classOf[MyClass])(new java.lang.Integer(42), "foo")
println(instance) // prints: MyClass(42,foo)
println(instance.getClass) // prints: class MyClass
You cannot get the get class from a generic type. Java erases it (type erasure).
Edit: 20 September 2012
Three years on, the instantiate method can be improved to return a properly typed object.
def instantiate[T](clazz: java.lang.Class[T])(args:AnyRef*): T = {
val constructor = clazz.getConstructors()(0)
return constructor.newInstance(args:_*).asInstanceOf[T]
}
See http://www.nabble.com/How-do-I-get-the-class-of-a-Generic--td20873455.html
See answers to Scala: How do I dynamically instantiate an object and invoke a method using reflection? as well, especially regarding type erasure.
This is what I've ended up with so far, I'd like to not have to deal directly with AnyRef if possible. So if anyone knows a way to get around that I'd appreciate the help.
case class MyClass(id:Long,name:String)
def instantiate[T](classArgs: List[AnyRef])(implicit m : Manifest[T]) : T ={
val constructor = m.erasure.getConstructors()(0)
constructor.newInstance(classArgs:_*).asInstanceOf[T]
}
val list = List[AnyRef](new java.lang.Long(1),"a name")
val result = instantiate[MyClass](list)
println(result.id)

Resources