How can we return instance of class from ladon functions in python? - ladon

I want to return a instance of user defined class and list of instances of user defined class from a ladon function? Is it possible?

this might help you its something like this
from ladon.ladonizer import ladonize
from ladon.types.ladontype import LadonType
class Response(LadonType):
values = [int]
class MyService(object):
#ladonize(int, int, rtype=Response)
def foo(self, a, b):
result = Response()
result.values = [a+b, a*b]
return result

Related

How to create an object attribute without writing to database -- peewee -- python

Maybe i have an understanding problem. I try to make 2 tabeles in one database. But additionaly i need to have some temporary values in one class that i doen´t want to write to the database.
I try to switch to peewee and read the dokumentation but i find no solution at my own.
without peewee i would make an init method where i write my attributes. But where did i have to write them now?
from peewee import *
import datetime
db = SqliteDatabase('test.db', pragmas={'foreign_keys': 1})
class BaseModel(Model):
class Meta:
database = db
class Sensor(BaseModel):
id = IntegerField(primary_key=True)
sort = IntegerField()
name = TextField()
#def __init__(self):
#self.sometemporaryvariable = "blabla"
def meineparameter(self, hui):
self.hui = hui
print(self.hui)
class Sensor_measure(BaseModel):
id = ForeignKeyField(Sensor, backref="sensorvalues")
timestamp = DateTimeField(default=datetime.datetime.now)
value = FloatField()
class Meta:
primary_key = CompositeKey("id", "timestamp")
db.connect()
db.create_tables([Sensor_measure, Sensor])
sensor1 = Sensor.create(id=2, sort=20, name="Sensor2")
#sensor1.sometemporaryvariable = "not so important to write to the database"
sensor1.save()
Remember to call super() whenever overriding a method in a subclass:
class Sensor(BaseModel):
id = IntegerField(primary_key=True)
sort = IntegerField()
name = TextField()
def __init__(self, **kwargs):
self.sometemporaryvariable = "blabla"
super().__init__(**kwargs)

Maya Python static class function scope

I have some trouble getting my static class to work. There is something I am missing about the scope of functions within a class. If called the script gives me following error:
NameError: global name 'disableCostumFrames' is not defined #
import maya.cmds as cmds
from functools import partial
class Blast:
def createWindow():
# Todo:
# hanldes the gui for the user
windowID = 'window'
if cmds.window(windowID, exists = True):
cmds.deleteUI('window')
window = cmds.window(windowID, title="Blast", iconName='Blast', widthHeight=(400, 200) )
cmds.frameLayout( label='')
cmds.rowColumnLayout( numberOfColumns=4, columnWidth=[(1, 100),(3, 100)] )
cmds.text( label='Start: ' )
global Blast_startFrame
Blast_startFrame = cmds.textField( enable = False)
cmds.text( label=' End: ' )
global Blast_endFrame
Blast_endFrame = cmds.textField( enable = False)
cmds.setParent('..')
cmds.rowColumnLayout( numberOfColumns=2, columnWidth=[(1, 100), (2, 100)] )
cmds.radioCollection()
#cmds.radioButton( label='Full', select = True, onCommand= partial(disableCostumFrames, Blast_startFrame, Blast_endFrame ) )
#cmds.radioButton( label='Costum', onCommand= partial(enableCostumFrames, Blast_startFrame, Blast_endFrame ) )
cmds.setParent('..')
cmds.rowColumnLayout( numberOfColumns=1, columnWidth=[(1, 400), (2, 100)] )
cmds.button( label='Playblast' ,command= 'createPlayblast')
cmds.setParent('..')
cmds.showWindow( window )
return Blast_startFrame, Blast_endFrame
def main():
createWindow()
def enableCostumFrames(Blast_startFrame, Blast_endFrame, *args):
cmds.textField(Blast_startFrame, edit=True, enable=True)
cmds.textField(Blast_endFrame, edit=True, enable=True)
def disableCostumFrames(Blast_startFrame, Blast_endFrame, *args):
cmds.textField(Blast_startFrame, edit=True, text="", enable=False)
cmds.textField(Blast_endFrame, edit=True, text="", enable=False)
How do I need to define these functions within the class? I am calling the module like that:
import sys
Dir = 'c:/Blast'
if Dir not in sys.path:
sys.path.append(Dir)
try: reload(Blast_v011)
except: import Blast_v011
Blast_v011.Blast()
maybe iam doing something wrong on this side? Appreciated any help.
In this case you need to add a self reference to all of the methods in your class. The usual python class looks like this:
class MyClass(object):
def __init__(self):
self.variable = 123
def some_method(self):
print "my variable = ", self.variable
def some_other_method(self):
if self.variable > 1:
self.some_method()
The self reference in the member functions is how you get at class member variables and other functions -- it's python's way of referring to what other languages call this.
Instance methods can only be called on an instance (it's the instance that gets passed in as self). You can make a method that is called on the class itself -- rather than any particular instance of the class -- using the #classmethod decorator. Classmethods also take an argument, but instead of self it's a reference to the class. You use it the same way to get variables defined at the class level, which are shared by all copies of the class:
class HasShared(object):
shared = 99
#classmethod
def a_class_method(cls):
print cls.shared
(You can mix and match class and instance methods in the same class).
You can also make static methods using the #staticmethod decorator. These don't get a default argument at all:
class NotPythonic(object):
#staticmethod
def needs_no_args():
print "call me as NotPythonic.needs_no_args()"
In Python we tend to avoid this formula, since you can get a static method by just creating a function in a module without making a class to hold them. For the example code you posted, I'd probably just make a conventional class using instance methods, since your functions need the names of the gui widgets to be able to actually ask them questions.

get classOf[Array[A]] from classOf[A]

I have a list of scala classes in the form like:
List(classOf[A], classOf[B], ...)
I need to register these classes as well as the array of the classes into kryo. The result is like:
kryo.register(classOf[A])
kryo.register(classOf[Array[A]])
kryo.register(classOf[B])
kryo.register(classOf[Array[B]])
...
So, with the list at hand, I may just use a foreach to register both the class and the array of the class.
However, I fail to get classOf[Array[A]] from classOf[A]. I have tried the ClassTag as following method:
def getArrayClass[T: ClassTag](c: Class[T]): Class[_] = {
classOf[Array[T]]
}
The result is not the right (though the type of the both results is the same), and kryo still complains that Class is not registered: A[].
scala> getArrayClass(classOf[A])
res0: Class[Array[A]] = class java.lang.Object
scala> classOf[Array[A]]
res1: Class[Array[A]] = class [LA;
Any clues? Thanks.
You can do it using the wrap method ClassTag:
def getArrayClass(c: Class[_]): Class[_] =
scala.reflect.ClassTag(c).wrap.runtimeClass
Note that this does not work if c is classOf[Null] or classOf[Nothing] (I believe this is bug in ClassTags). For any other Class, it will work.
You can also go to the Java way of doing it, without ClassTags, which is basically equivalent:
def getArrayClass(c: Class[_]): Class[_] =
java.lang.reflect.Array.newInstance(c, 0).getClass

How to iterate over a list of type Class to edit the properties of its objects in Groovy

I know there are more elaborate ways to achieve this in Java, but Groovy should have a concise way to do the same as per http://groovy.codehaus.org/Looping
Class Currency.groovy
class Currency {
String name
double rate
}
CurrencyController
def select(){
List<Currency> selectedCurrencies = Currency.getAll(params.currencies)
selectedCurrencies.eachWithIndex { obj, i -> obj.rate = update(obj.name)};
[selectedCurrencies:selectedCurrencies]
}
def update(String sym){
return sym
}
The above code throws:
No signature of method: currencychecker.CurrencyController$_$tt__select_closure12.doCall() is applicable for argument types: (currencychecker.Currency)
Thanks to #dmahapatro, the issue was that I was using an iterator variable obj[i], even though obj itself is the iterated object. The rest is correct!
I experimented with selectCurrencies.each as well instead of selectCurrencies.eachWithIndex however the right one in this case is eachWithIndex

How to use Slick's mapped tables with foreign keys?

I'm struggling with Slick's lifted embedding and mapped tables. The API feels strange to me, maybe just because it is structured in a way that's unfamiliar to me.
I want to build a Task/Todo-List. There are two entities:
Task: Each task has a an optional reference to the next task. That way a linked list is build. The intention is that the user can order the tasks by his priority. This order is represented by the references from task to task.
TaskList: Represents a TaskList with a label and a reference to the first Task of the list.
case class Task(id: Option[Long], title: String, nextTask: Option[Task])
case class TaskList(label: String, firstTask: Option[Task])
Now I tried to write a data access object (DAO) for these two entities.
import scala.slick.driver.H2Driver.simple._
import slick.lifted.MappedTypeMapper
implicit val session: Session = Database.threadLocalSession
val queryById = Tasks.createFinderBy( t => t.id )
def task(id: Long): Option[Task] = queryById(id).firstOption
private object Tasks extends Table[Task]("TASKS") {
def id = column[Long]("ID", O.PrimaryKey, O.AutoInc)
def title = column[String]("TITLE")
def nextTaskId = column[Option[Long]]("NEXT_TASK_ID")
def nextTask = foreignKey("NEXT_TASK_FK", nextTaskId, Tasks)(_.id)
def * = id ~ title ~ nextTask <> (Task, Task.unapply _)
}
private object TaskLists extends Table[TaskList]("TASKLISTS") {
def label = column[String]("LABEL", O.PrimaryKey)
def firstTaskId = column[Option[Long]]("FIRST_TASK_ID")
def firstTask = foreignKey("FIRST_TASK_FK", firstTaskId, Tasks)(_.id)
def * = label ~ firstTask <> (Task, Task.unapply _)
}
Unfortunately it does not compile. The problems are in the * projection of both tables at nextTask respective firstTask.
could not find implicit value for evidence parameter of type
scala.slick.lifted.TypeMapper[scala.slick.lifted.ForeignKeyQuery[SlickTaskRepository.this.Tasks.type,justf0rfun.bookmark.model.Task]]
could not find implicit value for evidence parameter of type scala.slick.lifted.TypeMapper[scala.slick.lifted.ForeignKeyQuery[SlickTaskRepository.this.Tasks.type,justf0rfun.bookmark.model.Task]]
I tried to solve that with the following TypeMapper but that does not compile, too.
implicit val taskMapper = MappedTypeMapper.base[Option[Long], Option[Task]](
option => option match {
case Some(id) => task(id)
case _ => None
},
option => option match {
case Some(task) => task.id
case _ => None
})
could not find implicit value for parameter tm: scala.slick.lifted.TypeMapper[Option[justf0rfun.bookmark.model.Task]]
not enough arguments for method base: (implicit tm: scala.slick.lifted.TypeMapper[Option[justf0rfun.bookmark.model.Task]])scala.slick.lifted.BaseTypeMapper[Option[Long]]. Unspecified value parameter tm.
Main question: How to use Slick's lifted embedding and mapped tables the right way? How to I get this to work?
Thanks in advance.
The short answer is: Use ids instead of object references and use Slick queries to dereference ids. You can put the queries into methods for re-use.
That would make your case classes look like this:
case class Task(id: Option[Long], title: String, nextTaskId: Option[Long])
case class TaskList(label: String, firstTaskId: Option[Long])
I'll publish an article about this topic at some point and link it here.

Resources