w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Change fields of case class based on map entries with simple type check in scala macros
After all I ended up with following solution: import language.experimental.macros import scala.reflect.macros.Context object ProductUtils { def withOverrides[T](entity: T, overrides: Map[String, Any]): T = macro withOverridesImpl[T] def withOverridesImpl[T: c.WeakTypeTag](c: Context)(entity: c.Expr[T], overrides: c.Expr[Map[String, Any]]): c.Expr[T] = { import c.universe._ val originalEntityTree = reify(entity.splice).tree val originalEntityCopy = entity.actualType.member(newTermName("copy")) val originalEntity = weakTypeOf[T].declarations.collect { case m: MethodSymbol if m.isCaseAccessor => (m.name, c.Expr[T](Select(c.resetAllAttrs(originalEntityTree), m.name)), m.returnType)

Categories : Scala

Scala Macros: Making a Map out of fields of a class in Scala
Note that this can be done much more elegantly without the toString / c.parse business: import scala.language.experimental.macros abstract class Model { def toMap[T]: Map[String, Any] = macro Macros.toMap_impl[T] } object Macros { import scala.reflect.macros.Context def toMap_impl[T: c.WeakTypeTag](c: Context) = { import c.universe._ val mapApply = Select(reify(Map).tree, newTermName("apply")) val pairs = weakTypeOf[T].declarations.collect { case m: MethodSymbol if m.isCaseAccessor => val name = c.literal(m.name.decoded) val value = c.Expr(Select(c.resetAllAttrs(c.prefix.tree), m.name)) reify(name.splice -> value.splice).tree } c.Expr[Map[String, Any]](Apply(mapApply, pairs.toList)) } } Note also that you need the c.r

Categories : Scala

Scala. Can case class with one field be a value class?
You can have a case class that is a value class. As you can see from the example below, there is no object creation. Except of course the inevitable boxing if you would upcast to Any. Here is a little piece of scala code class ValueClass(val value:Int) extends AnyVal case class ValueCaseClass(value:Int) extends AnyVal class ValueClassTest { var x: ValueClass = new ValueClass(1) var y: ValueCaseClass = ValueCaseClass(2) def m1(x:ValueClass) = x.value def m2(x:ValueCaseClass) = x.value } And the bytecode, which does not contain the slightest trace of the two value classes. Compiled from "ValueClassTest.scala" public class ValueClassTest { public int x(); Code: 0: aload_0 1: getfield #14 // Field x:I 4: ireturn

Categories : Scala

An object extends its companion case class in Scala
There is no benefit except for some confusion and that you can use the JsPath object as empty JsPath. If you need an empty object, it is probably more readable if you give it a separate name (equivalent to List's Nil): object EmptyJsPath extends JsPath(Nil) or you define a empty method on the companion (like most other collection classes do): object JsPath { def empty = ... }

Categories : Scala

Scala Play form validation: different forms for one case class - is it possible?
You could try to add methods applyOld and unapplyOld to companion object like this: case class User(username: String, loginDetails: LoginDetails) object User { def applyOld(username: String, password: String, field3: Option[Int], field4: String) = new User(username, LoginDetails(password, field3, field4)) def unapplyOld(u: User): Option[(String, String, Option[Int], String)] = Some((u.username, u.loginDetails.password, u.loginDetails.field3, u.loginDetails.field4)) } You just need methods (String, String, Option[Int], String) => User and User => Option[(String, String, Option[Int], String)], you could place them anywhere you like. For instance you could create object UserOld with methods apply and unapply. Usage: val oldForm = Form( mapping( "username" -> email,

Categories : Forms

Is it possible to take advantage of case class inheritance in pattern matching in Scala 2.10.0?
As far as I could understand the problem, I have no reason to use "case classes" for the children. Hopefully the correct code is as follows: object AST { sealed abstract class Expr case class MathOp(e1: Expr, e2: Expr) extends Expr case class Number extends Expr class Add(e1: Expr, e2: Expr) extends MathOp(e1, e2) class Sub(e1: Expr, e2: Expr) extends MathOp(e1, e2) } expr match { case MathOp(e1: Expr, e2: Expr) => //do something that would be done to Add, Sub, Mul, Div case Number => //do another thing }

Categories : Scala

Scala case class copy with dynamic named parameter
It is not possible using case classes. Copy method generated at compile time and named parameters handled on compile time to. There is no possibility to do it ar runtime. Dynamic may help to solve your issue: http://hacking-scala.tumblr.com/post/49051516694/introduction-to-type-dynamic

Categories : Scala

Creating a case class for an embedded MongoDB Array with Salat and Scala
Arrays are not supported. Make it a list, a seq, nearly any other type of collection, and your document will serialize and deserialize correctly. https://github.com/novus/salat/wiki/Collections Make a player case class with all the possible fields and use default arguments to cover all the cases. If there are too many different cases to cover, that's when things get really ugly. You are essentially trying to deserialize data that has no expected structure as ... what, exactly? I haven't added Map[String, Any] support to mainstream Salat although there is an outstanding pull request.

Categories : Json

How to update a mongo record using Rogue with MongoCaseClassField when case class contains a scala Enumeration
Answer coming from : http://grokbase.com/t/gg/rogue-users/1367nscf80/how-to-update-a-record-with-mongocaseclassfield-when-case-class-contains-a-scala-enumeration#20130612woc3x7utvaoacu7tv7lzn4sr2q But more convenient directly here on StackOverFlow: Sorry, I should have chimed in here sooner. One of the long-standing problems with Rogue was that it was too easy to accidentally make a field that was not serializable as BSON, and have it fail at runtime (when you try to add that value to a DBObject) rather than at compile time. I introduced the BSONType type class to try to address this. The upside is it catches BSON errors at compile time. The downside is you need to make a choice when it comes to case classes. If you want to do this the "correct" way, define your case class plus a B

Categories : Mongodb

Equals for case class with floating point fields
You are correct. If you are worried about precision, then you will need to override equals: case class SomeClass(a:Double, b:Double) SomeClass(2.2 * 3, 1.0) == SomeClass(6.6, 1.0) // res0: Boolean = false case class BetterClass(a: Double, b: Double) { override def equals(obj: Any) = obj match { case x: BetterClass => (this.a - x.a).abs < 0.0001 && (this.b - x.b).abs < 0.0001 case _ => false } } BetterClass(2.2 * 3, 1.0) == BetterClass(6.6, 1.0) // res1: Boolean = true

Categories : Scala

java.lang.NoClassDefFoundError: scala/reflect/ClassManifest
You should add dependecy for scala-reflect to your maven build: <dependency> <groupId>org.scala-lang</groupId> <artifactId>scala-reflect</artifactId> <version>2.10.2</version> </dependency>

Categories : Scala

scala case class with casbah. Accept objectid parameter as string or as a objectid
You should go for a companion object and a case class eg: object User { def apply(name: String): User = User(new ObjectId(), name) def apply(id: String, name: String): User = User(new ObjectId(id), name) } case class User(id: ObjectId, name: String) Then you can handle either these cases: val user = User("Ross") val user1 = User("5204b74d9932e8319b8e9ec0", "Ross") val user2 = User(new ObjectId(), "Whitehead")

Categories : Scala

Scala - No TypeTag Available Exception when using case class to try to get TypeTag?
You need a TypeTag at compile time, because that is the way to work around erasure: import scala.reflect.runtime.{currentMirror => m, universe => ru} def getChildSettings[T: TypeTag](path: String, settingsParameterObject: T) = { val tpe = ru.typeOf[T] // val classC = tpe.typeSymbol.asClass val ctor = tpe.declaration(ru.nme.CONSTRUCTOR).asMethod ... } The Scala Documentation Overview for Reflection gives an example of getting and invoking a constructor.

Categories : Scala

class java.lang.RuntimeException/Scala class file does not contain Scala annotation
Looks like the library is configured to compile against Scala 2.9.1. Major versions of Scala are not binary compatible. I put the necessary SBT changes here: https://github.com/mpartel/prestashop-scala-client/commit/e9a1df40bfe35518aaebac899e438b9b6fa6d728

Categories : Scala

Is it possible in Play 2.1 to convert a JsValue to a case class instance if you only know the name of the case class at the runtime?
You need to implement a PathBinder...this should help out http://www.richard-foy.fr/blog/2012/04/09/how-to-implement-a-custom-pathbindable-with-play-2/

Categories : Scala

Reflect annotations from android activity class
Discovering all classes annotated with particular annotation in runtime requires, in general, classpath scanning. There is no streamlined, official API for doing it, though. This is because it is, always and inevitably, a hack, due to design of classloading system. In short, classes can, in principle, be created on demand, in completely uncontrollable and arbitrary manner. Nevertheless, usually the classpath jungle is by no means that vicious and frought with pitfalls, and we can list all the classes with particular property reasonably reliably. There is one android-specific obstacle to overcome, but it's not too bad. Basically, the trick is to list contents of classes.dex file in the app's .apk archive, load classes it contains one by one and reflectively check for the desired property.

Categories : Java

Reflect the class file changes without bouncing websphere server
I believe you are looking for Hot deployment and dynamic reloading of applications on websphere. Here is the documentation that should guide to achieve that: Websphere Hot deployment and dynamic reloading

Categories : Java

"error: can't find main class scala.tools.nsc.MainGenericRunner" when running scala in windows
Those weird variables are called parameter extensions. they allow you to interpret a variable as a path to a file/directory and directly resolve things from that path. For example, if %1 is a path to a file dir123456file.txt, %~f1 is the fully qualified path to file.txt, %~p1 is the path to the containing directory dir123456, %~s1 is the path in short name format dir123~1file.txt, and many others... Also, %0 is always set to the path of the currently running script. So: %~fs0 is the fully qualified path, in short name format, to the current script, %%~dpsi is the manual expansion of the FOR variable %%i to a drive letter (d option) followed by the path the containing folder (p option), in short format (s option). Now, this weird looking block of code is a workaround for KB83343

Categories : Windows

scala Duration: "This class is not meant as a general purpose representation of time, it is optimized for the needs of scala.concurrent."
Time can be represented in various ways depending on your needs. I personally have used: Long — a lot of tools take it directly Updated: java.time.* thanks to @Vladimir Matveev The package is designed by the author of Joda Time (Stephen Colebourne). He says it is designed better. Joda Time java.util.Date Separate hierarchy of classes: trait Time case class ExactTime(timeMs:Long) extends Time case object Now extends Time case object ASAP extends Time case class RelativeTime(origin:Time, deltaMs:Long) extends Time Ordered time representation: case class History[T](events:List[T]) Model time. Once I had a global object Timer with var currentTime:Long: object Timer { private var currentTimeValue:Long def currentTimeMs = currentTimeValue def currentTimeMs_=(newTime:Long) { ...

Categories : Scala

Scala import statement at top and inside scala class
The difference is: In Option 1 the import is viable for the complete scope. i.e any class/trait/function in com.somePackage can be used anywhere inside/outside the MyClass But in case of Option 2 it can only be used inside the MyClass and not outside it because scope of import is limited to inside MyClass only.

Categories : Scala

MultiSelectListPreference Error inflating class java.lang.reflect.Constructor
It looks like the following attribute for your MultiSelectListPreference is causing the NullPointerException (while trying to resolve the String?) android:defaultValue="@string/pref_consumptionUnit_default"

Categories : Android

Scala Set match case
Set defines an isEmpty method so the simplest solution is def test(originalSet: Set[Int]): Boolean = originalSet.isEmpty When you match against a List using list match { case Nil => true case x :: y => false } you are matching against the List Nil object and against the :: class i.e. it is equivalent to list match { case Nil => true case ::(x, y) => false } So you can't use this form with Set. When you pattern match against a List using: list match { case List(a, b) => true case _ => false } you are using the List extractor. The List extractor is defined using unapplySeq which matches if the list is of the given format. Set does not define an unapply or unapplySeq method, so you can't match against it in this way either.

Categories : Scala

Scala: Convert if to case
Hard to tell without a description of what you're trying to accomplish, but perhaps you want something like: Seq(title, subtitle) .flatMap(_ split "\s") .filter(a contains _) .map((query, _, item_id) To answer your question, directly, though: You could replace { term => if (a contains term) Some(query, term, item_id) else None } with { case term if a contains term => Some(query, term, item_id) case _ => None }

Categories : Scala

How make java.lang.reflect.Method.getReturnType return void.class with EasyMock?
The answer is: EasyMock.expect(method.getReturnType()).andReturn((Class) void.class); But there is EasyMock run time errors because java.lang.reflection.Method is final.

Categories : Java

Use case classes as messages in Scala
You have 2 different classes with the same name CreateTS. You are sending CreateTS defined in sender and trying to receive message of other type with the same name in receiver. You should move declarations of case classes from method body so it will be in scope of both methods. Note that scala actors are deprecated, you should use akka actors.

Categories : Scala

Scala case matching Any with String
Regarding your updating question : the code works as it should. classOf[User].getDeclaredField does not return a String or whatever, it returns a java.lang.reflect.Field. Which is rightly dealt with by case _. You could get value of type java.lang.class, or java lang.reflect.Type by calling getType or getGenericType on that. However, even then, your routine does not expect values of type Class, it expects plain values, of type String or Int or Double... "cls" does not sound like a good argument name there. A routine expecting classes would look like def typecast(cls: Class[_]) { // will work with cls: Any too if(cls == classOf[Int]) println("Int") else if(cls == classOf[String]) println("String") else if(cls == classOf[Option[_]]) println("Option") else println("Nothing") }

Categories : Scala

Scala: returning results from a case match
def find(teamId: Int = 0) { = is missing, explaining why your method doesn't return anything (Unit). Should be: def find(teamId: Int = 0) = {

Categories : Scala

Scala: Refactoring a case-statement to use for-comprehension
I don't think for-comprehension is useful here. You could make your code more readable with custom extractors like this: class Extractor(s: String) { def unapply(v: JsValue): Option[JsArray] = json s match { case a: JsArray => Some(a) case _ => None } } val AllOf = new Extractor("allOf") val AnyOf = new Extractor("anyOf") val OneOf = new Extractor("oneOf") val (name, es) = json match { case AllOf(a) => "allOf" -> Some(a) case AnyOf(a) => "anyOf" -> Some(a) case OneOf(a) => "oneOf" -> Some(a) case _ => "oneOf" -> None } val result = es. map{ a => ComplexType("object", name, a.as[Seq[JsObject]].flatMap(_.values.map(_.as[String]))) }. getOrElse("Unspecified" :: Nil)

Categories : Json

Jackson Scala JSON Deserialization to case classes
I think there's a few separate problems to address here, so I've listed three separate approaches. TL;DR Either use Jackson polymorphism correctly or, in your case, go to a simpler approach and remove the need for the polymorphism. See my code on github. 1. Custom Deserializer Your formatted JSON is: { inventory: [ { productType: 'someProduct1', details: { productId: 'Some_id', description: 'some description' } }, { productType: 'someProduct2', details: { productId: 'Some_id', description: { someKey: 'somevalue' } } } ] } The field productType is misplaced, in my opinion, but if this format is a strict requirement then you could write your own deserializer that looks at the productType field and instantiates

Categories : Json

Scala using regex with or syntax in match case statement
An "anchored" regex for pattern matching matches whole inputs: val aorb = ".*(a|b).*".r "with a " match { case aorb(_) => "have a or b" case _ => "None" } // res0: String = have a or b If you have capturing groups in your regex you should also use or explicitly ignore results: note _ in aorb(_).

Categories : Scala

Fastest serialization/deserialization of Scala case classes
Your use case is exactly the targeted use case for scala/pickling (https://github.com/scala/pickling). Disclaimer: I'm an author. Scala/pickling was designed to be a faster, more typesafe, and more open alternative to automatic frameworks like Java or Kryo. It was built in particular for distributed applications, so serialization/deserialization time and serialized data size take a front seat. It takes a different approach to serialization all together- it generates pickling (serialization) code inline at the use-site at compile-time, so it's really very fast. The latest benchmarks are in our OOPSLA paper- for the binary pickle format (you can also choose others, like JSON) scala/pickling is consistently faster than Java and Kryo, and produces binary representations that are on par or sm

Categories : Scala

Why is the Empty input case needed in Scala Iteratees?
Let's say you connect an enumerator that feeds some elements to the peek iteratee that looks at the first element and returns it but does not consume it, leaving it to be used by possibly another iteratee that will be composed with peek. Then you would want to provide a mechanism for peek to put back the element. From what I can tell from both Play and Scalaz iteratee, the done iteratee takes an argument just for this purpose. So you can do something like in pseudo code: done(Some(result), El(result)). See this implementation of peek. Now if you implement something like head which will actually consume the element, then it feels like one way to do it is to return done(Some(result), emptyInput) to indicate that the input was consumed. See also this comment in the playframework source cod

Categories : Scala

How to get fields of classtype in scala?
cls is already a Class, no need to call classOf on it. Btw, your code can be written much shorter: cls.getDeclaredFields.filter(_.getName != "id").map(f => f.getName -> f.getType).toMap[String, Any] And no, it is not possible to get a more general type than Any because your fields may have completely different types.

Categories : Scala

Play framework scala template with case statement on enumeration
You don't have to use try here, just the wild card in you match (see: http://www.playframework.com/documentation/2.1.x/ScalaTemplateUseCases). @(tagStatus: String) @tagStatus match { case TagStatus.deployed.toString => {<span class="label label-success">@tagStatus</span>} case TagStatus.deployedPartially.toString => {<span class="label label-important">@tagStatus</span>} case TagStatus.deployedWithProblems.toString => {<span class="label label-important">@tagStatus</span>} case _ => {<span class="label label-important">??</span>} }

Categories : Scala

Custom json serialization of structured scala case classes
Argonaut does a great job. Mark Hibbard helped me out with getting the example below working. All that is needed is to create a codec for the types and it will implicitly add an asJson to your objects to turn them into strings. It will also add a decodeOption[YourClass] to strings to extract an object. The following: package argonaut.example import argonaut._, Argonaut._ abstract class Message case class CardDrawn(player: Long, card: Int, mType: String = "CardDrawn") extends Message case class CardSet(cards: List[CardDrawn], mType: String = "CardSet") extends Message object CardSetExample { implicit lazy val CodecCardSet: CodecJson[CardSet] = casecodec2(CardSet.apply, CardSet.unapply)("cards","mType") implicit lazy val CodecCardDrawn: CodecJson[CardDrawn] = casecodec3(CardDrawn.

Categories : Scala

How to match against the pattern of a partial function's case definition in a Scala macro?
First of all, there is a special flavor of quasiquotes specifically for CaseDefs called cq: override def transformCaseDefs(trees: List[CaseDef]) = trees map { case caseDef @ cq"$pattern if $guard => $body" => ... } Secondly, you should use pq to deconstruct patterns: pattern match { case pq"$name @ $nested" => ... case pq"$extractor($arg1, $arg2: _*)" => ... ... } If you are interested in internals of trees that are used for pattern matching they are created by patvarTransformer defined in TreeBuilder.scala On the other hand if you're are working with UnApply trees (that are being produced after typechecking) I have bad news for you: quasiquotes currently don't support them. Follow SI-7789 to get notified when this is fixed.

Categories : Scala

Is explicit variable declaration in case of subsequent function calls necessary in Scala?
No, it does not cache the computation automatically. How should it? Since Scala doesn't have an effect system, the compiler doesn't know if the function being executed has side effects or not. Thus, not repeating a computation due to potential performance improvements could lead to different behavior: scala> for (i <- Option(5) if {println(i); i*i} < 50) yield {println(i); i*i} 5 5 res0: Option[Int] = Some(25) scala> for (i <- Option(5); j = {println(i); i*i} if j < 50) yield j 5 res1: Option[Int] = Some(25) Btw, you can always check what code the compiler generates: $ scala -Xprint:typer -e "for (i <- Option(5) if {println(i); i*i} < 50) yield {println(i); i*i}" [[syntax trees at end of typer]] // scalacmd5404327798073027065.scala package &

Categories : Scala

How to turn a list of objects into a map of two fields in Scala
I would suggest: map { org => (org.id, org.name) } toMap e.g. scala> case class T(val a : Int, val b : String) defined class T scala> List(T(1, "A"), T(2, "B")) res0: List[T] = List(T(1,A), T(2,B)) scala> res0.map(t => (t.a, t.b)) res1: List[(Int, String)] = List((1,A), (2,B)) scala> res0.map(t => (t.a, t.b)).toMap res2: scala.collection.immutable.Map[Int,String] = Map(1 -> A, 2 -> B)

Categories : Scala

Updating Fields using Case Qquery
You need to do this with a join or union because you want more rows in the output than in the input: Select a.channel_name, p.package_name From TableA a left outer join (select 'bbc' as channel_name, 'entertainment_pack' as package union all select 'bbc' as channel_name, 'extra_pack' as package ) p on a.channel_name = p.channel_name; This will return NULL for non-BBC channels. You can add additional packages into the p subquery.

Categories : SQL

Salesforce web to case required Fields
I don't fully understand your question, however, after reading you have already got the form field value when you did the DOM lookup, that makes the if statement wrong, I believe this may be the correct code: function checkform (form) { var name = document.getElementById('00NC0000005KA85'); if (name.value == "") { alert( "Please enter your full name." ); name.focus(); return false ; } return true; } Also, are you sure the form field will always have the ID "00NC0000005KA85"? This looks generated, and if the DOM node is missing, again the form will not submit.

Categories : Javascript



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.