When presented with the below four classes, my editor, VS2013, accepts the first three but gets confused by the fourth one.
type ClassOne =
val mutable myint: int
new (j) = { myint= j }
new () = ClassOne 1
type ClassTwo =
val mutable myint: int
new j = { myint= j }
new () = ClassTwo 2
type ClassThree =
val mutable myint: int
new j = { myint= j }
new () = ClassThree 3
type ClassFour =
val mutable myint: int
new j = { myint= j }
new () = ClassFour 4 // confusion here
My question is, in ClassFour when I use neither parentheses nor 'crooked' indentation for the constructor, what does the compiler think I am trying to do?
Related
i am trying to write code to mask nested json fields..
def maskRecursively(map :mutable.Map[String,Object]):mutable.Map[String,Object] ={
val maskColumns = PII_Data.getPIIData()
for((k,v) <- map){
if(v.isInstanceOf[Map[String,Object]]){
maskRecursively(map.get(k).asInstanceOf[mutable.Map[String,Object]])
}else if(v.isInstanceOf[List[Object]]) {
} else {
if(maskColumns.contains(k)){map+=(k->"*****")}
}
}
map }
calling this method from ..
val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)
val result = mapper.readValue(jsonStr, classOf[ java.util.Map[String,Object] ])
import scala.collection.JavaConverters._
val myScalaMap = result.asScala
maskRecursively(result.asScala)
i am getting error while trying to iterate a nested json object ..
Cannot cast value of type 'scala.Some' to type 'scala.collection.mutable.Map'
how do i recurse a complex nested json object this way ?
Your mistake was
if(v.isInstanceOf[Map[String,Object]]){
maskRecursively(map.get(k).asInstanceOf[mutable.Map[String,Object]])
There are a few issues:
You check if v is an instance of Map, but then attempt to cast it to mutable.Map. They are technically different types (mutable vs immutable).
You check the type of v, but then apply the cast to map.get(k), which is going to be a different value and type from v. A map's get method returns an Option, hence the error message.
Thanks to type erasure on the JVM, the runtime won't be able to tell the difference between e.g. a Map[String, Object] and a Map[SomethingElse, Whatever] - both will just look like Map at runtime. The compiler should have given you a warning about the isInstanceOf call for this reason.
If you do an isInstanceOf / asInstanceOf combo, make sure the operand is the same each time. You already have v, so you don't need to look it up a second time from the map. And make sure you use the same type on both instanceOf calls.
Fix this by changing it to
if(v.isInstanceOf[mutable.Map[_, _]]){
maskRecursively(v.asInstanceOf[mutable.Map[String,Object]])
After some digging , i was able to solve this..
def maskJson(jsonStr: String): String = {
implicit val formats = org.json4s.DefaultFormats
val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)
val result = mapper.readValue(jsonStr, classOf[Map[String, Object]])
val maskedJson = maskRecursively(result)
mapper.writeValueAsString(maskedJson)
}
def maskRecursively(map: Map[String, Object]): collection.mutable.Map[String, Object] = {
val mutable = collection.mutable.Map[String, Object]()
val maskColumns = PII_Data.getJsonPIIFields()
for ((k, v) <- map) {
if (v.isInstanceOf[Map[String, Object]]) {
mutable += k -> maskRecursively(v.asInstanceOf[Map[String, Object]])
} else if (v.isInstanceOf[List[Object]]) {
val list = v.asInstanceOf[List[Map[String, Object]]].map(i => maskRecursively(i)).toList
mutable += k -> list
} else {
if (maskColumns.contains(k)) {
mutable += (k -> "*****")
}
else {
mutable += k -> v
}
}
}
mutable
}
I have a room database from which I can get a List<LearningEvent>, which I then have to convert into a Collection<JSONObject> and return it. How can I efficiently do that?
Here's the LearningEvent class:
#Entity(tableName = "learningEvents")
data class LearningEvent(
#ColumnInfo(name = "learningeventid")
#PrimaryKey(autoGenerate = true)
var id: Int? = null,
var sessionId: Long,
var time: Float,
var eventType: String,
var description: String,
var feedback: String
)
Here's the DAO:
#Query("SELECT * FROM learningEvents WHERE sessionId = :sessionId")
suspend fun getAllLearningEvents(sessionId: Long?): List<LearningEvent>
And here's my non-working/non-building code for the getEvents() function:
override suspend fun getEvents(): Collection<JSONObject> =
withContext(Dispatchers.IO) {
Log.d("\ngetEvents(eventType)", currentSessionId.toString())
if (currentSessionId === null) {
throw Exception("Current session Id is null; Session cannot be retrieved.")
}
var gson = Gson();
// Return JSON object collection of table rows.
var learningEvents = db.learningEventDao().getAllLearningEvents(currentSessionId);
var returnCollection = emptyList<JSONObject>();
learningEvents.forEach{element ->
var singleObject = gson.toJsonTree(element);
returnCollection += singleObject;
}
return#withContext returnCollection;
}
In my humble opinion, you can convert LearningEvent to JSONObject using .toJson. Here the sample code:
var learningEvents = db.learningEventDao().getAllLearningEvents(currentSessionId);
var returnCollection = emptyList<JSONObject>();
learningEvents.forEach{ element ->
val singleObject = gson.toJson(element);
returnCollection += JSONObject(singleObject);
}
I'd like to implement a generic addr decoder. This is a follow up question to this post.
class AddrDecoder[T <: Data with Num[T]] (dType:T, n:Int) extends Module {
val io = IO (new Bundle {
val mmap = Map(BigInt, BigInt) // base, size ranges
val addr = Input (dType)
val en = Input (Bool())
//val sel = Output(Vec(n,Bool())) // $onehot0 selector
val sel = Output(Bool():_*) // $onehot0 selector
})
// Curried function which accepts a tuple and an input addr
// Use map to apply it to inputs
def inside (range:(T,T))(addr:T):Bool = {
addr >= range._1 && addr < range._1 + range._2
}
// MUX output
for (i <- 0 until n) {
io.sel(i) := false.B
}
// Check addr range and assert high if matches
var idx = 0 // yes, variable
for ((k,v) <- io.mmap) {
when (io.en) {
io.sel(idx) := (k + v) (inside(_)(io.addr))
idx := idx + 1.U
}
}
// $onehot0 output encoding check
assert (PopCount(io.sel) >= 1.U, "Invalid addr decoding")
}
I get a compile errors:
[error] found : math.BigInt.type
[error] required: (?, ?)
[error] val mmap = Map(BigInt, BigInt) // base, size ranges
...
[error] found : chisel3.core.Bool
[error] required: Seq[?]
[error] val sel = Output(Bool():_*) // $onehot0 selector
Can I use Map and a variable Bool array as IO ports? If not, how to rewrite this correctly?
Thank you!
Okay, here's my solution. Not that generic, since I could not specialize it to BigInt, but works for me now:
class AddrDecoder (addrWidth:Int, mmap:Map[UInt, UInt]) extends Module {
val size = mmap.size
val io = IO (new Bundle {
val addr = Input (UInt(addrWidth.W))
val en = Input (Bool())
val sel = Output(Vec(size,Bool())) // $onehot0 selector
})
// Curried function which accepts a tuple and an input addr
def inside (range:(UInt,UInt))(addr:UInt):Bool = {
addr >= range._1 && addr < range._1 + range._2
}
// MUX output
for (i <- 0 until size) {
io.sel(i) := false.B
}
// Loop thru the Memory Map, pair with index and evaluate logic value for io.sel
mmap.zipWithIndex foreach { case (entry,idx) =>
when (io.en && inside(entry)(io.addr)) {
io.sel(idx) := true.B
} .otherwise {
io.sel(idx) := false.B
}
}
// $onehot0 output encoding check
assert (PopCount(io.sel) <= 1.U, "Invalid addr decoding")
}
I am trying to rewrite OpenSoCFaric-1.1.2 from chisel2 to chisel3. But I encounter error messages "data to be connected 'chisel3.core.UInt#103' must be hardware, not a bare Chisel type" for below code:
File: packettoFlit.scala class: PacketToFlit
val flitWidth = Flit.fromBits(0.U, parms).getWidth
File:channel.scala object: Flit
object Flit {
def head(h: HeadFlit) : Flit = {
val f = new Flit(h.parms)
f.x := f.union.pack("Head", h)
f
}
def body(b: BodyFlit) : Flit = {
val f = new Flit(b.parms)
f.x := f.union.pack("Body", b)
f
}
def fromBits(n: UInt, parms: Parameters) : Flit = {
val f = new Flit(parms)
f.x := n
f
}
/*
def zeroHead(parms: Parameters) : HeadFlit = {
val x = new HeadFlit(parms)
x.
}
*/
}
And now I don't have good ideas about how to rewrite such code segments to fix the error. Could you give some help or suggestions ? Thanks a lot!
We would need to see more of the error message (line number) and more of the code to provide a definitive answer, but our guess is that somewhere a UInt(x.W) is being used where a literal (y.U) is expected, or a Wire()/WireInit() wrapper is missing.
NOTE: LBL is actively migrating this code to Chisel3. You might be better off waiting for their work to be published.
Below is source code for class Flit.
class Flit(parms: Parameters) extends Bundle {
val union = new BitUnion(Map("Head" -> new HeadFlit(parms), "Body" -> new BodyFlit(parms)))
val x = UInt(union.width.W)
val numVCs = parms.get[Int]("numVCs")
def asHead(dummy: Int = 0) : HeadFlit = union.unpack[HeadFlit]("Head", x)
def asBody(dummy: Int = 0) : BodyFlit = union.unpack[BodyFlit]("Body", x)
def whenHead(block: HeadFlit => Unit) { union.whenTag[HeadFlit]("Head", x)(block) }
def whenBody(block: BodyFlit => Unit) { union.whenTag[BodyFlit]("Body", x)(block) }
def isHead(dummy: Int = 0) : Bool = union.tagEquals("Head", x)
def isBody(dummy: Int = 0) : Bool = union.tagEquals("Body", x)
def isTail(dummy: Int = 0) : Bool = {
val tailBit = Bool()
when (isHead()) {
tailBit := union.unpack[HeadFlit]("Head", x).isTail
} .otherwise {
tailBit := union.unpack[BodyFlit]("Body", x).isTail
}
tailBit
}
def getVCPort(dummy: Int = 0) : UInt = {
val vcBits = UInt(log2Ceil(numVCs).W)
when (isHead()) {
vcBits := union.unpack[HeadFlit]("Head", x).vcPort
} .otherwise {
vcBits := union.unpack[BodyFlit]("Body", x).vcPort
}
vcBits
}
//override def clone = { new Flit(parms).asInstanceOf[this.type] }
override def cloneType: this.type = new Flit(parms).asInstanceOf[this.type]
// override def width : Int = {x.width}
}
Thanks a lot!
Bibo
I'm trying to define Vector of Vector for my IO, but I'm getting an error from the chisel saying:
vec element 'Vec(chisel3.util.DecoupledIO#2b57)' must be hardware, not a bare Chisel type
The code which I've written is like the following:
//Module's argument
,val ArgsOut: Array[Int]
...
...
val Args = for (i <- 0 until ArgsOut.length) yield {
val arg = Vec(ArgsOut(i), Decoupled(UInt()))
arg
}
val outputArg = Vec(Args)
Some things to consider
IO ports, i.e. members of the IO Bundle, must be chisel hardware constructs, Args is a scala Vector type, it needs to be chisel Vec
All elements of a Vec must be the same size, mostly a consequence of the need to be able to index elements of the Vec. You have each element of Args as a Vec whos's length is determined by some the elements of ArgsOut. Vec(n, type) will not
Do really mean to have a 2D Vec(Vec( of decoupled IO's?
Your UInt in the Decoupled has an unknown width. This is not strictly speaking an error, because Firrtl can infer the width in most situations. But again this can be a problem for the requirement that a Vec's element are all the same length. Inferred widths in IOs should be used cautiously.
I was able to construct at IOBundle like this
val io = IO(new Bundle {
val args = Vec(ArgsOut.length, Vec(ArgsOut(0), Decoupled(UInt(18.W))))
val outputArg = Flipped(args)
})
Which compiles but may not quite be what you had in mind. I was able to connect the io's using
io.outputArg <> io.args
If this doesn't seem to fit your use case, I need to know a bit more how you intend to use the fields and we should be able to figure out how to wire them up.
Here is an illustration of how to use a subclass of Record to manage a virtual array of Vectors of varying length. This example runs for me. It is not exactly the same as your examples. But I think it makes things clearer. This is for the use case where you do not need to access your Vecs via a UInt, but is for when you need to match a heterogenous mix of Vectors.
import chisel3._
import chisel3.iotesters.PeekPokeTester
import org.scalatest.{FreeSpec, Matchers}
import scala.collection.immutable.ListMap
final class VariableBundle(elts: (String, Vec[UInt])*) extends Record {
val elements = ListMap(elts map { case (field, elt) => field -> elt.chiselCloneType }: _*)
def apply(elt: String): Vec[UInt] = elements(elt)
override def cloneType = (new VecVecBundle(elements.toList: _*)).asInstanceOf[this.type]
}
class SeqIO(val sizes: Array[Int]) extends Module {
val io = IO(new VariableBundle(Seq.tabulate(sizes.length) { i =>
s"vec_in_$i" -> Input(Vec(sizes(i), UInt(8.W)))
} ++
Seq.tabulate(sizes.length) { i =>
s"vec_out_$i" -> Output(Vec(sizes(i), UInt(8.W)))
}:_*
)
)
for(i <- sizes.indices) {
io(s"vec_out_$i") := io(s"vec_in_$i")
}
}
class SeqIOTester(c: SeqIO) extends PeekPokeTester(c) {
for(i <- c.sizes.indices) {
for(j <- 0 until c.sizes(i)) {
poke(c.io(s"vec_in_$i")(j), j)
}
}
step(1)
for(i <- c.sizes.indices) {
for(j <- 0 until c.sizes(i)) {
expect(c.io(s"vec_out_$i")(j), j)
}
}
}
class SeqIOSpec extends FreeSpec with Matchers {
"illustrate how to build bundles that have vecs wrapping different sized vecs" in {
iotesters.Driver.execute(Array.empty[String], () => new SeqIO(Array(1, 2, 3, 4))) { c =>
new SeqIOTester(c)
} should be (true)
}
}
Let me write the actual code:
class LoopLatch(val NumInputs: Int,
val ArgsOut: Array[Int],
val ID: Int)
(implicit val p: Parameters) extends Module with CoreParams with UniformPrintfs {
val io = IO(new Bundle {
val inputArg = Vec(NumInputs, Flipped(Decoupled(new DataBundle())))
val Args = Vec(for (i <- 0 until ArgsOut.length) yield {
val arg = Vec(ArgsOut(i), Decoupled(new DataBundle()))
arg
})
DataBundle() is a custom data type which I have defined it in a separate file. What I really want to do is that. I want to pass an array to the module like ArgsOut and then build a vector of vector of Databundle and each subsequent vector has its own number of Databundle which comes from the input array.
The loopLatch module is a wrapper for other module, LiveInNode which I have designed. Actually the LoopLatch module only has a vector of this elements and then provide an IO for it.
Here is the actual code:
class LoopStart(val NumInputs: Int,
val ArgsOut: Array[Int],
val ID: Int)
(implicit val p: Parameters) extends Module with CoreParams with UniformPrintfs {
val io = IO(new Bundle {
val inputArg = Vec(NumInputs, Flipped(Decoupled(new DataBundle())))
val Args = Vec(ArgsOut.length, Vec(ArgsOut(0), Decoupled(new DataBundle())))
val Out = new VecVecBundle(
Seq("inputArg" -> Vec(NumInputs, Flipped(Decoupled(new DataBundle())))) ++
(ArgsOut.indices).map { i =>
val arg = Vec(ArgsOut(i), Decoupled(new DataBundle()))
s"Args_$i" -> arg
}:_*
)
val pSignal = Vec(NumInputs, Flipped(Decoupled(Bool())))
val Finish = Vec(NumInputs, Flipped(Decoupled(new ControlBundle())))
}
)
val Args = for (i <- 0 until NumInputs) yield {
val arg = Module(new LiveInNode(NumOuts = 1, ID = i))
arg
}
//Iterating over each loopelement and connect them to the IO
for (i <- 0 until NumInputs) {
Args(i).io.InData <> io.inputArg(i)
Args(i).io.Finish <> io.Finish(i)
Args(i).io.pred <> io.pSignal(i)
}
for (i <- 0 until ArgsOut.length) {
io.Out("Args_0") <> Args(i).io.Out
}
}