How to display a simple Message in Ultimaker Cura - plugins

I have the following code:
from UM.Extension import Extension
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("CostAndTimePlugin")
class CostAndTimePlugin(Extension):
def __init__(self):
super().__init__()
self.name = "Cost And Time"
self.addMenuItem(i18n_catalog.i18n("Sample"), self.message)
def message(self):
pass
and message() should display a simple message
I tried this:
def message(self):
self._message = Message(i18n_catalog.i18nc("#info:status", "Smaple..."),
title=i18n_catalog.i18nc("#title", "Auto-Sample"))
self._message.show()
but it did not work

Related

Get PrepareStament Variable in Scala

I would like to make the prepareStatement serializable
A preparedStatement is not serializable. I have to build a serializable structure that wraps the call and the parameters to control the construction of the said statement during the deserialization
Here are the classes I created to wrap the PrepareStament
import java.sql._
import java.sql.SQLException
import java.util
import java.util.Collections
import avro.shaded.com.google.common.collect.ImmutableMap
import scala.collection.immutable.HashMap
import scala.collection.mutable
class WrappedConnection(var delegate: Connection) extends Serializable {
def prepareStatement(sql: String): WrappedPreparedStatement = {
val ps = delegate.prepareStatement(sql)
new WrappedPreparedStatement(sql, ps)
}
// delegate all Connection methods to the delegate
}
class WrappedPreparedStatement(var sql: String, var delegate: PreparedStatement) extends Serializable {
private var parameters: mutable.Map[Integer, Object] = mutable.Map.empty[Integer, Object]
override def toString: String = sql
def apply( delegateVar: PreparedStatement) {
delegate = delegateVar
parameters = mutable.Map.empty[Integer, Object]
}
def getParameters = parameters
// TODO: many methods to delegate
#throws[SQLException]
def setString(parameterIndex: Int, x: String): Unit = {
delegate.setString(parameterIndex, x)
parameters.put(parameterIndex, x)
}
#throws[SQLException]
def executeQuery = { // perhaps you might want to do some logging here?
delegate.executeQuery
}
// delegate all PreparedStatement methods to the delegate
}
object WrappedConnection {
def apply(delegate: Connection): WrappedConnection = new WrappedConnection(delegate)
}
This is the test code
val connection = MsSqlUtils.createConnectionFactory(config)
val conn = connection()
val wrapperConn = WrappedConnection(conn)
val statement = wrapperConn.prepareStatement("select * from users")
Currently, my problem is to access the variables of my prepareStatement object and create get functions that will return them.
When I talk about variables I talk about the one shown in the picture below not the one in the querie
Anyone know how to access these variables?

Can not access field with sorm

In Scala, I have the following scala case class:
case class Page(url: String)
object Page {
implicit val personFormat = Json.format[Page]
}
Which is encoded in the database like this:
object Db extends Instance(entities = Seq(Entity[Page]()), url="jdbc:h2:mem:test")
Afterwards, I retrieve one instance from the database like this:
val page = Db.query[Page].whereEqual("id", pageId).fetch
val content: String = new URL(page.url).getContent().toString
However, on the last line I am getting.
value url is not a member of Stream[models.Page with sorm.Persisted]
Why is url not a member?
I created a database representation for Page. Shouldn't that include all its fields?
It should be like this
package models
import sorm._
import play.api.libs.json.{JsValue, Writes, Json}
case class Page(url: String)
object Page {
implicit val writes = Json.writes[Page]
implicit val reads = Json.reads[Page]
}
object DB extends Instance(Set(Entity[Page]()), "jdbc:h2:mem:test")
def pages = Action {
val pages = DB.query[Page].fetch()
Ok(Json.toJson(pages))
}
def addPage = Action(parse.json) { request =>
val page = DB.save(request.body.as[Page])
Ok(Json.toJson(page))
}

Import Class: error: not found: object Controller

I'm a beginner in scala, without java background. I don't understand the import system.
I have my application, where i use the import
import Array._
import List._
import Controller.api
object scalaStart{
def main(args: Array[String]){
var apiCtrl = new api()
apiCtrl.getById(1)
println(apiCtrl.title)
}
}
And this is the class:
package Controller
class api {
var id:Int
var title:String
var description:String
def getById(id:Int){
if(id = 1){
this.id = 1
this.title = s"Title Nummer ${this.id}"
this.description = s"Description Nummer ${this.id}"
}else{
this.id = 1
this.title = s"Artikel mit der ID: ${this.id} existiert nicht."
this.description = s"Kein Eintrag mit der ID: ${this.id}"
}
}
}
i checked also only import api and import controller and wildcards controller._ controller.api._.
Philipp, your code actually does not compile.
In the line if(id=1){ it should be if(id==1).
Try to correct this and rebuild your project.
You will notice that compiler will give you another error:
Error:(5, 7) class api needs to be abstract, since: it has 3
unimplemented members. /** As seen from class api, the missing
signatures are as follows. * For convenience, these are usable as
stub implementations. */ def description_=(x$1: String): Unit = ???
def id_=(x$1: Int): Unit = ??? def title_=(x$1: String): Unit = ???
class api {
^
This is because in Scala you can't leave variable declarations abstract as you could do in Java. Instead of var id:Int you need to put something liek var id:Int = 0 and the same for other declared variables.

How to test Actors values with a factory as receiver

Let say I have an actor called TestedActor wich is able to save an Int value and send it back as follow:
class TestedActor extends Actor {
override def receive = receive(0)
def receive(number: Int): Receive = {
case new_number: Int => context.become(receive(new_number))
case ("get", ref: ActorRef) => ref ! number
}
}
In my test, I would like to be able to get this Integer and test it.
So i've been thinking about creating something like:
class ActorsSpecs extends FlatSpec with Matchers {
case class TestingPositive(testedActor: ActorRef) extends Actor {
override def receive = {
case number: Int => checkNumber(number)
case "get" => testedActor ! ("get", self)
}
def checkNumber(number: Int) = {
number should be > 0
}
}
implicit val system = ActorSystem("akka-stream")
implicit val flowMaterializer = ActorMaterializer()
val testedActor = system.actorOf(Props[TestedActor], name = "testedActor")
val testingActor = system.actorOf(Props(new TestingPositive(testedActor)), name = "testingActor")
testingActor ! "get"
}
This way, i'm able to create this TestingPositive actor, to get the number in the TestedActor and test it in checkNumber.
It seems to be working well, my problem is :
When the test fail, it raise an exception in the actor thread, I can see what went wrong in the console, but it is still saying that all my tests succeeded. Because (I think) the main thread is not aware of this failure.
Does someone knows an easier way than all of this TestingActor stuff?
Or any solution to tell the main thread that it failed?
Thank you
Take a look at using TestKit docs here. You can write a much simpler test for your actor. See how you like this test:
import akka.actor.{Props, ActorSystem}
import akka.testkit.{TestProbe, TestKit}
import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, ShouldMatchers}
class ActorSpecs extends TestKit(ActorSystem("TestSystem"))
with FlatSpecLike
with ShouldMatchers
with BeforeAndAfterAll {
override def afterAll = {
TestKit.shutdownActorSystem(system)
}
def fixtures = new {
val caller = TestProbe()
val actorUnderTest = system.actorOf(Props[TestedActor], name = "testedActor")
}
"The TestedActor" should "pass a good test" in {
val f = fixtures; import f._
caller.send(actorUnderTest, 42)
caller.send(actorUnderTest, ("get", caller.ref))
caller.expectMsg(42)
}
"The TestedActor" should "fail a bad test" in {
val f = fixtures; import f._
caller.send(actorUnderTest, 42)
caller.send(actorUnderTest, ("get", caller.ref))
caller.expectMsg("this won't work")
}
}
Also, you should know about sender. While your get certainly works, a cleaner approach might be to reply to the sending actor:
def receive(number: Int): Receive = {
case new_number: Int => context.become(receive(new_number))
case "get" => sender ! number
}
And the test becomes:
"The TestedActor" should "pass a good test" in {
val f = fixtures; import f._
caller.send(actorUnderTest, 42)
caller.send(actorUnderTest, "get")
caller.expectMsg(42)
}
And finally, I'll shamelessly plug my recent blog post about maintaining an akka code base with my team. I feel morally obligated to give a new hAkker an opportunity to read it. :)

Scala pass function args through to case class copy constructor?

I have some (Akka) actor code that is using a case class + the copy constructor to update state:
def foo(state:StateCaseClass) : Receive = {
import state._
{
case Bar(updates) =>
context become foo(copy(/* change a limited number of things */))
// ... other message processing w/ lots of context become foo(copy(...))
}
}
I'd like to add below the import
def update = context become foo(copy(_))
so that the code can be
def foo(state:StateCaseClass) : Receive = {
import state._
def update = context become foo(copy(_))
{
case Bar(updates) =>
update(/* change a limited number of things */)
// ... etc
}
}
but that doesn't compile. I can of course tweak the def update a bit to get rid of most of boilerplate, but the copy still sticks around:
def foo(state:StateCaseClass) : Receive = {
import state._
def update(newState:StateCaseClass) = context become foo(newState)
{
case Bar(updates) =>
update(copy(/* change a limited number of things */))
// ... etc
}
}
Is there comparable syntax that will let me pass through the args to the case class copy constructor and dry out that last bit?
Disclaimer: I guess the best solution is to use context become explicitly. And I don't recommend you to use the code below.
I guess it's impossible without metaprogramming (macros). You have to create a method with default values for named parameters.
You could always create such method manually like this:
def update(filed1: Int = state.field1, field2: String = state.field2) =
context become foo(StateCaseClass(filed1, filed2))
...
update(field1 = 0)
...
update(field2 = "str")
But I guess it's not what you want.
The only way to get such method without metaprogramming is... to use method copy itself. Method copy calls constructor and you could call become in constructor.
The code below works, but I strongly don't recommend you to use it! It's a cryptocode and it will confuse all other developers.
import akka.actor._
trait ReceiveHelper extends PartialFunction[Any, Unit] {
def receive: PartialFunction[Any, Unit]
override def apply(v: Any) = receive(v)
override def isDefinedAt(v: Any) = receive isDefinedAt v
}
sealed trait TestActorMessage
case object Get extends TestActorMessage
case class SetInt(i: Int) extends TestActorMessage
case class SetString(s: String) extends TestActorMessage
class TestActor extends Actor {
case class Behaviour(intField: Int, strField: String) extends ReceiveHelper {
context become this
val receive: Receive = {
case Get => sender ! (intField -> strField)
case SetInt(i) => copy(intField = i)
case SetString(s) => copy(strField = s)
}
}
def receive = Behaviour(0, "init")
}
Usage:
val system = ActorSystem("testSystem")
val testActor = system.actorOf(Props[TestActor], "testActor")
import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
implicit val timeout = Timeout(5 seconds)
testActor ? Get foreach println
// (0,init)
testActor ! SetInt(666)
testActor ? Get foreach println
// (666,init)
testActor ! SetString("next")
testActor ? Get foreach println
// (666,next)