Binding.scala - how to get updating count from Vars - scala

I have a Vars binding statement, like so
val data: Vars[Contact] = Vars.empty[Contact]
I'm trying to show the number of elements like so:
<div>{data.all.bind.size}</div>
But this produces a complication error
type mismatch;
[error] found : com.thoughtworks.binding.Binding[App.this.data.All[App.this.Contact]]
[error] (which expands to) com.thoughtworks.binding.Binding[scala.collection.mutable.Buffer[_ <: App.this.Contact]]
[error] required: com.thoughtworks.binding.Binding[scala.collection.mutable.Buffer[_$6]] where type _$6 <: App.this.Contact
[error] {this.data.all.bind.size}</div>
How to make this work?
Update
trying to use String as type for Vars binding, same outcome
type mismatch;
[error] found : com.thoughtworks.binding.Binding[App.this.data.All[String]]
[error] (which expands to) com.thoughtworks.binding.Binding[scala.collection.mutable.Buffer[_ <: String]]
[error] required: com.thoughtworks.binding.Binding[scala.collection.mutable.Buffer[_$6]] where type _$6 <: String
[error] {this.data.all.bind.size}</div>
Note that i'm using Scala.js 1.2, Scala 2.13.3 and
libraryDependencies += "org.lrng.binding" %%% "html" % "latest.release"
unfortunately, can't provide scalafiddle since it doesn't support Scala 2.13, instead I created a replica project here-
https://www.dropbox.com/s/i9dpsa9pz0lejtj/bindingreplica.tar.gz?dl=0

You can use length for this.
<div>{data.length.bind.toString}</div>

Related

How to init a register with a parametrized value

I'm trying to deploy RegInit in a module with parametrized data types. Normally, for a simple port in Chisel I'd do the following:
val myReg = RegInit (0.U(32.W))
In my code, I have the following:
import dsptools._
import dsptools.numbers._
class Acc[A <: Data:Ring, B <: Data:Ring] (inType:A, outType:B,
mulPipeLen:Int = 1, addPipeLen:Int = 1) extends Module {
...
def zero = dsptools.numbers.Ring[B].zero
val mres = Reg(outType.cloneType) // this works, no initialization
val ares = RegInit(zero(outType.cloneType.getWidth.W)) // this fails trying to zero init in the parametrized Ring
...
}
which return a compile error:
[error] Acc.scala:43:27: B does not take parameters
[error] val mres = RegInit(zero(outType.cloneType.cloneType.getWidth.W))
How do I fix this? Thank you!
When I tried the above, I got 3 errors:
[error] /Users/jack/work/chisel3-raw/src/main/scala/RegInit.scala:10:13: inferred type arguments [Object] do not conform to method apply's type parameter bounds [T <: chisel3.core.Data]
[error] val reg = RegInit(0.U, (32.W))
[error] ^
[error] /Users/jack/work/chisel3-raw/src/main/scala/RegInit.scala:10:23: type mismatch;
[error] found : chisel3.core.UInt
[error] required: T
[error] val reg = RegInit(0.U, (32.W))
[error] ^
[error] /Users/jack/work/chisel3-raw/src/main/scala/RegInit.scala:10:30: type mismatch;
[error] found : chisel3.internal.firrtl.Width
[error] required: T
[error] val reg = RegInit(0.U, (32.W))
[error] ^
RegInit has two flavors, documented here: https://chisel.eecs.berkeley.edu/api/latest/chisel3/core/RegInit$.html
In short, if just 1 argument, it is the initialization value. If the initialization value has a defined width (0.U(32.W) vs. 0.U) then it will adopt the width (and type) of the initializing value.
val reg = RegInit(0.U(32.W))
Otherwise, you can give 2 arguments, the first defining the type, the second defining the initialization value
val reg2 = RegInit(UInt(32.W), 0.U)
Response to Edited post
I don't know much about the dsptools, but I don't think Ring has much to do with the concept of zero. You can set the type of ares to be the same as outType and then try casting 0 to the same type as the init value, eg.
val ares = RegInit(outType.cloneType, 0.U.asTypeOf(outType.cloneType))
Or perhaps you can cast 0 and also set the width:
val ares = RegInit(0.U(outType.getWidth.W).asTypeOf(outType.cloneType))
I'm not sure if these will work, but they might

Scala.Rx with ScalaTags example compilation error

I tried the scala.js example https://github.com/lihaoyi/hands-on-scala-js and its scala.rx with scalatags part in advanced section.
Example compiles are runs fine but when I try to use the latest scala.rx v 0.3.1 I get following compile errors:
[info] Compiling 19 Scala sources to /home/code/workspace/hands-on-scala-js-master/examples/demos/target/scala-2.11/classes...
[error] /home/code/workspace/hands-on-scala-js-master/examples/demos/src/main/scala/advanced/BasicRx.scala:14:
[error] This Rx might leak! Either explicitly mark it unsafe (Rx.unsafe) or make an implicit RxCtx available
[error] in the enclosing scope, for example, by adding (implicit ctx: Ctx.Owner) to line 12: method main
[error] val numChars = Rx{txt().length}
[error] ^
[error] /home/code/workspace/hands-on-scala-js-master/examples/demos/src/main/scala/advanced/BasicRx.scala:15:
[error] This Rx might leak! Either explicitly mark it unsafe (Rx.unsafe) or make an implicit RxCtx available
[error] in the enclosing scope, for example, by adding (implicit ctx: Ctx.Owner) to line 12: method main
[error] val numWords = Rx{
[error] ^
[error] /home/code/workspace/hands-on-scala-js-master/examples/demos/src/main/scala/advanced/BasicRx.scala:55:
[error] This Rx might leak! Either explicitly mark it unsafe (Rx.unsafe) or make an implicit RxCtx available
[error] in the enclosing scope, for example, by adding (implicit ctx: Ctx.Owner) to line 42: method main2
[error] for(fruit <- fruits) yield Rx {
[error] ^
[error] /home/code/workspace/hands-on-scala-js-master/examples/demos/src/main/scala/advanced/BasicRx.scala:65: diverging implicit expansion for type Nothing => scalatags.JsDom.Frag
[error] starting with method rxFrag in object BasicRx
[error] ul(fragments)
[error] ^
[error] /home/code/workspace/hands-on-scala-js-master/examples/demos/src/main/scala/advanced/BasicRx.scala:72: not found: value Obs
[error] Obs(r, skipInitial = true){
[error] ^
[error] /home/code/workspace/hands-on-scala-js-master/examples/demos/src/main/scala/advanced/BasicRx.scala:72: not found: value skipInitial
[error] Obs(r, skipInitial = true){
[error] ^
[warn] /home/code/workspace/hands-on-scala-js-master/examples/demos/src/main/scala/webpage/WeatherSearch.scala:53: non-variable type argument scala.scalajs.js.Dynamic in type pattern scala.scalajs.js.Array[scala.scalajs.js.Dynamic] is unchecked since it is eliminated by erasure
[warn] case jsonlist: js.Array[js.Dynamic] =>
[warn] ^
[warn] one warning found
[error] 6 errors found
[error] (demos/compile:compile) Compilation failed
It seems that ownership concept has somehow changed and also there is no Obs companion object.
I tried to fix these erros in BasicRx.scala:
Old code:
#JSExport
def main(container: html.Div) = {
New code (Leakage fix):
#JSExport
def main(container: html.Div) = {
implicit val ctx: Ctx.Owner = Ctx.Owner.safe()
Old code:
implicit def rxFrag[T <% Frag](r: Rx[T]): Frag = {
def rSafe: dom.Node = span(r()).render
var last = rSafe
Obs(r, skipInitial = true){
val newLast = rSafe
js.Dynamic.global.last = last
last.parentNode.replaceChild(newLast, last)
last = newLast
}
last
}
New code (conversion fix):
implicit def rxFrag[T <% Frag](r: Rx[T]): Frag = {
def rSafe: dom.Node = span(r()).render
var last = rSafe
val thunk = () => {
val newLast = rSafe
js.Dynamic.global.last = last
last.parentNode.replaceChild(newLast, last)
last = newLast
}
new Obs(thunk, r)
last
}
But still get following error:
[info] Compiling 19 Scala sources to /home/code/workspace/hands-on-scala-js-master/examples/demos/target/scala-2.11/classes...
[warn] /home/code/workspace/hands-on-scala-js-master/examples/demos/src/main/scala/webpage/WeatherSearch.scala:53: non-variable type argument scala.scalajs.js.Dynamic in type pattern scala.scalajs.js.Array[scala.scalajs.js.Dynamic] is unchecked since it is eliminated by erasure
[warn] case jsonlist: js.Array[js.Dynamic] =>
[warn] ^
[error] /home/code/workspace/hands-on-scala-js-master/examples/demos/src/main/scala/advanced/BasicRx.scala:74: No implicit Ctx.Data is available here!
[error] def rSafe: dom.Node = span(r()).render
[error] ^
How to fix this one?
And is the leakage fix correctly done?
Updating scalatags to 0.5.4. did not have any affect.
I helped contribute to the 0.3.x branch of scala.rx - and yep, the api is largely changed from 0.2.x. However, I also maintain a more recent version of the "framework" code you are looking at here:
https://github.com/Voltir/framework.rx/blob/master/src/main/scala/framework/Framework.scala
Also, it turns out that in the case of using js.App and its def main(), the correct way to get a Ctx.Owner is to use import rx.Ctx.Owner.Unsafe._. So long as that main function is evaluated a finite number of times (ie once) per page load, it is safe to allow a "leak". Your usage of Ctx.Owner.safe() wont work because the compiler can't prove that main is only called a finite number of times.
One complete example of all of this can be found in the demo project of this library:
https://github.com/Voltir/route.rx

Implementing custom foreach in order to better understand types and function composition

In order to try and understand Scala's type system I'm attempting
to implment a custom implementation for List.foreach method :
package com
object customForEach extends App {
class customForEach[B, A] extends Iterable[A] with collection.Seq[A] {
def foreach[B](f: A ⇒ B) {
var these = this
while (!these.isEmpty) {
f(these.head)
these = these.tail
}
}
def tail = this match {
case h :: t ⇒ t
}
}
}
When I complile this code I receive errors :
[error] \Desktop\Scala\src\main\scala\typeparam.scala:16: constructor cannot be instantiated to expected type;
[error] found : scala.collection.immutable.::[B(in class ::)]
[error] required: com.customForEach.customForEach[B(in class customForEach),A]
[error] case h :: t ? t
[error] ^
[error] \Desktop\Scala\src\main\scala\typeparam.scala:16: not found: value t
[error] case h :: t ? t
[error] ^
[error] \Desktop\Scala\src\main\scala\typeparam.scala:11: type mismatch;
[error] found : Seq[A]
[error] required: com.customForEach.customForEach[B,A]
[error] these = these.tail
[error] ^
[error] three errors found
[error] (compile:compile) Compilation failed
[error] Total time: 0 s, completed 31-Jan-2015 11:53:40
In particular I find it iteresting how println can be composed with List in this fashion : List(1,2,3).foreach(println)
Do I need to add extend another trait in order to access the .tail function ?
For this error :
not found: value t
[error] case h :: t ? t
Shouldn't t be found since it is created using pattern match operator :: ?
There are many reasons why this code won't work. In order to understand the first compiler error not found: value t, you must look at the error immediately before it. :: exists solely for List, but here you do not have a List, only Iterable with Seq. That pattern match can't work, which causes t to become "not found".
There are even larger problems than that, though. Even if you remove your definition of tail (which is unnecessary), you'll then find that you're missing abstract method definitions for apply, iterator, and length from the Seq trait. I imagine you're doing this because you can't extend List, which is sealed. You can copy the implementations of apply, and length from LinearSeqOptimized, then easily implement an iterator method, but there's still another problem: your class does not have a constructor.
Okay, well we'll look at what List does again. List is abstract and has two sub-types, :: and Nil. Nil is just a case object, and :: has a constructor that accepts the head and tail of the List. This isn't going to help you very much, unless you also want to duplicate the code for :: and Nil as well.
Scala collections are very large complicated beasts, and extending them to override one method is not a simple process.

Ambiguous implicit conversions causing compile failure in Scalatest and Argonaut.io

I'm currently doing that most noble of programming endeavors, writing tests for Json encoding / decoding. I'm using Argonaut.io for Json and Scalatest for my testing framework. Under scalatest, the use of === during assertion verification provides additional information if a failure occurs, while the use of ==simply gives this org.scalatest.exceptions.TestFailedException was thrown.. However, the scala compiler is not happy. Here's the code:
val default = new Broadcast("default", "default", "default")
test("Should parse out network when present") {
val hcursor = testHCursor(jsonPath + "complete-broadcast.json")
val actualNetwork = Parser.BroadcastDecodeJson(hcursor)
.getOr(default)
.network
assert(actualNetwork === "ESPNU")
}
That spews out this:
[info] Compiling 1 Scala source to /home/vagrant/waltercamp/waltercamp-dataservice/target/scala-2.10/test-classes...
[error] /home/vagrant/waltercamp/waltercamp-dataservice/src/test/scala/io/ptx/waltercamp/schedules/BroadcastParserSuite.scala:16: type mismatch;
[error] found : actualNetwork.type (with underlying type String)
[error] required: ?{def ===(x$1: ? >: String("ESPNU")): ?}
[error] Note that implicit conversions are not applicable because they are ambiguous:
[error] both method ToEqualOps in trait ToEqualOps of type [F](v: F)(implicit F0: scalaz.Equal[F])scalaz.syntax.EqualOps[F]
[error] and method convertToEqualizer in trait Assertions of type (left: Any)BroadcastParserSuite.this.Equalizer
[error] are possible conversion functions from actualNetwork.type to ?{def ===(x$1: ? >: String("ESPNU")): ?}
[error] assert(actualNetwork === "ESPNU")
[error] ^
[error] one error found
[error] (test:compile) Compilation failed
The use == however provides a clean compilation and pass. Is there a way provide the compiler a hint as to which conversion, or the conversion order, to use?
I'd go with ScalaTest's version here. One approach would be to apply the conversion explicitly:
assert(convertToEqualizer(actualNetwork) === "ESPNU")
That's kind of unpleasant, though, and involves a lot of repetitious boilerplate if you're using === many times in a file. Another way would be to exclude the Scalaz conversion from the general import:
import scalaz._, Scalaz.{ ToEqualOps => _, _ }
You could also switch to à la carte imports for Scalaz and just be sure you don't pull in ToEqualOps via scala.syntax.equal._. I'll admit I find à la carte imports a pain to maintain sometimes, but if you're not doing much with Scalaz in the test this wouldn't be too bad.

Scala Class[_$1] where type _$1

Right now trying to instantiate a new JSONConverter to register Jackson's Scala module.
private def getConverter(implicit m: ClassTag[T]) = {
new JSONConverter[T](classTag[T].runtimeClass, bucketName)
JSONConverter.registerJacksonModule(DefaultScalaModule)
converter
}
The above code sits in a standard Scala trait that looks like trait Writeable[T] { }.
The problem with the above code is that Scala seems to be having a difficult time with Types. Compiler error is:
[error] found : Class[_$1] where type _$1
[error] required: Class[T]
[error] val converter = new JSONConverter[T](classTag[T].runtimeClass, bucketName(clientId))
[error] ^
[error] one error found
Anyone know the source or easy fix of this issue? Thanks!
Update
Although #wingedsubmariner had an answer that allowed this to originally compile, as soon as I went to write more code the issue cascaded further. I'll show an example:
val o = bucketLookup(clientId).fetch(id, classTag[T].runtimeClass).withConverter(converter).withRetrier(DB.retrier).r(DB.N_READ).execute()
At withConverter the compiler throws the same error:
[error] found : com.basho.riak.client.convert.JSONConverter[T]
[error] required: com.basho.riak.client.convert.Converter[_$1] where type _$1
[error] val o = bucketLookup(clientId).fetch(id, classTag[T].runtimeClass).withConverter(converter).withRetrier(DB.retrier).r(DB.N_READ).execute()
I even tried doing the same type casting using converter.asInstanceOf[JSONConverter[T]] but inheritance (JSONConverter<T> extends Converter<T>) seems to cascade the issue. Any ideas here?
runtimeClass is retuning a Class with the wrong type parameter. Try:
new JSONConverter(classTag[T].runtimeClass.asInstanceOf[Class[T]], bucketName(clientId))