w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
While Sending Html Mails from my web application Recieved Mails contains Symbols like &ldquo,&rdquo, ‘
Check with another constructor for htmlView: ContentType mimeType = new System.Net.Mime.ContentType("text/html"); var htmlView = AlternateView.CreateAlternateViewFromString(bodyMessage, mimeType);

Categories : Asp Net Mvc

Scala interpreter says object is not a member of package, when it is
Assuming your classpath is correct... This is caused by a bug in the scalac compile server. You need to kill all processes (there may be more than one) with command lines that end with scala.tools.nsc.CompileServer.

Categories : Scala

Play Framework 2.1.1 cannot find play object in multi-project setup Build.scala
Are you sure the Play plugin is correctly loaded ? Without it, the Play library cannot be used in the Build file (or anywhere else). As explained here, the project/plugins.sbt file must contain the plugin definition. You can look at these samples to have working examples of this file: // The Typesafe repository resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/" // Use the Play sbt plugin for Play projects addSbtPlugin("com.typesafe.play" % "sbt-plugin" % Option(System.getProperty("play.version")).getOrElse("2.0"))

Categories : Scala

How to mavenize a Scala / Akka / Play project?
Don't use Maven - use SBT - it's the build tool of choice. Note maven is now squarely in the thoughtworks radar Hold section meaning nobody should be building new projects on it if you trust Fowler's advice: http://www.thoughtworks.com/radar Play comes with sbt under the hood already so you shouldn't have to look to far from where you are now: http://www.playframework.com/documentation/2.0/Build

Categories : Scala

How to use Scala Virtualized in a Maven project with Scala-2.10?
the groupId of scala-library, scala-compiler is hard-coded into the plugin. The informations (version, ...) of scala-compiler are computed from the scala-library dependencies. You can open a ticket and ask to support other groupId (may be configurable one or not hard-coded). You can fork, made the change, and submit a patch / pull request. UPDATE : scala-mavent-plugin 3.1.6 include the patch from evantill (thanks) So you can override the default scalaOrganization

Categories : Scala

Scala: How to transform a POJO like object into a SQL insert statement using Scala reflection
In your case, you can use the following codes: val o = new MyDataObj val attributes = o.getClass.getDeclaredMethods.filter { _.getReturnType != Void.TYPE }.map { method => (method.getName, method.getReturnType, method.invoke(o)) } Here I use getDeclaredMethods to get the public methods in the MyDataObj. You need to notice that getDeclaredMethods can not get methods in its parent class. For MyDataObj, getDeclaredMethods will return the following methods: public double MyDataObj.c() public boolean MyDataObj.b() public java.lang.String MyDataObj.d() public int MyDataObj.a() public void MyDataObj.c_$eq(double) public void MyDataObj.d_$eq(java.lang.String) public void MyDataObj.b_$eq(boolean) public void MyDataObj.a_$eq(int) So I add a filter to filter out irrelevant methods.

Categories : SQL

Dynamic HTML ID with Bootstrap, Play framework and Scala templates
Example from one of my projects, just do it in the same way: @countries.byRegion.zipWithIndex.map { p => <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href=@("#collapse" + p._2)> @p._1._1 <span class="pull-right">@p._1._2</span> </a> </div> <div id=@("collapse" + p._2) class="accordion-body collapse"> <div class="accordion-inner"> @data.programs.map { prog => @if(prog.region == p._1._1) { <p>@prog.level</p> } } </div> </div> </div> } to make it work you have to make "dynamic" href's and id's: href=@("#collap

Categories : Scala

Convert Java Object (that is really a Scala Map) to Scala Map
You are probably trying to cast across class loaders. You can't do this--each class loader maintains its own hierarchy (for those classes not passed off to a common parent loader). Try calling getClassLoader on both your returned map and on a freshly-created one. Incidentally, Map$Map2 is just an implementation detail--a subclass of Map for dealing with two-element maps. It casts just fine normally: scala> val m = Map(1->"one", 2 -> "two"): Object m: Object = Map(1 -> one, 2 -> two) scala> m.getClass res0: Class[_ <: Object] = class scala.collection.immutable.Map$Map2 scala> m.asInstanceOf[scala.collection.immutable.Map[Int,String]] res1: scala.collection.immutable.Map[Int,String] = Map(1 -> one, 2 -> two)

Categories : Scala

scala value toInt is not a member of Any
edit: Ok, with the new information I would suggest you to create a case class that holds the data instead of using a Map, this way you will preserve type information. I know it is common to use hashes/maps for that in dynamically typed languages, but in statically typed languages as scala data types are the preferred way. orig: As I neither know what e is, nor what signature top10Tweets has, I can only assume. But from your code and the error I assume that e is a Map[String, String] and you are trying to get the string representation of an integer for the key "retweets" and convert it to an Int. As a default value you pass in an Int, so the type inferencer infers type Any, because that is the most common super type of String and Int. However Any does not have a toInt method and thus you

Categories : Scala

Scala opening write to stdout or file
Why not rewrite the function as: def writeToFileOrStdout(fname: Option[String] = None) = { val outStream = fname match{ case Some(name) => new java.io.FileOutputStream(new java.io.File(name)) case None => System.out } ... } It's always a good idea to use Option for an optional input as opposed to using null. That's basically what it's there for. In good scala code, you will not see explicit references to null. In fact, your code doesn't even compile for me. Nil is used to represent an empty list, not a null or non supplied String.

Categories : Java

Error opening `routes` file in Scala IDE
As mentioned in your comment, you had installed the play plugin for Eclipse Indigo, running on Eclipse Juno. To avoid that kind of problem, select very carefully the correct update-site on the Scala-IDE download page, and then only compatible plugins will be suggested for you.

Categories : Scala

Scala - how to go resolve "Value is not a member of Nothing" error
Nothing is the type name. It's the subtype of all other types. You can't call methods from Nothing itself, you have to specify exact type ((bc: ExactType).broadcast(message)). Nothing has no instances. Method, that returns Nothing will, actually, never return value. It will throw an exception eventually. Type inference Definition of lookup: abstract public <T extends Broadcaster> T lookup(Object id); in scala this definition looks this way: def lookup[T <: Broadcaster](Object id): T There is not specified type parameter in lookup method. In this case compiler will infer this type parameter as the most specific type - Nothing: scala> def test[T](i: Int): T = ??? test: [T](i: Int)T scala> lazy val x = test(1) x: Nothing = <lazy>

Categories : Scala

Diagnosing Scala compile error "value to is not a member of Int"
how did this ever compile/run in the first place? By default, the contents of scala.Predef is imported. There you have method intWrapper which produces a RichInt with method to. You probably have shadowed symbol intWrapper. Does the following work: implicitly[scala.Int => scala.runtime.RichInt] or this: intWrapper(3) to 4 ...if not, there lies your problem. EDIT: So, since you say that compiles, what happens is you replace cColumn with a constant, e.g. for (i <- 0 to 33 -1) { ... } ? It would also help to post the complete compiler message with indicated line etc.

Categories : Scala

How to use jQuery UI with Play Scala
first of all you need to define an endpoint for your data in the controller. Simething like this: def autocompleteSearch(a: String) = Action { request => val data = List("apple", "apple iphone", "apple ipad", "microsoft windows", "microsot office"); val filteredData = data.filter(_.startsWith(a)) Ok(Json.toJson(filteredData)) } Then you need to add this endpoint to your routes: GET /some-ajax controllers.Application.autocompleteSearch Then in your .scala.html file you can write a script that will do a get you you, example: var updateTime = function() { $.get("@routes.Application.timeUpdate()", function(data) { display.html(data) }) return false } When you have the var you just pass it to the jQueryUI. My ex

Categories : Jquery

How do you include files from a scala project in eclipse in a java project in netbeans
If you are developing a library in your Scala application, i would suggest to use sbt and package the library as a jar and import that jar to your java project. You will have to define a build file in sbt. I am not sure whether you already defined it and use the sbt package command. sbt package Try using sbt

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.runtime in compiler mirror not found" but working when started with -Xbootclasspath/p:scala-library.jar
The easy way to configure the settings with familiar keystrokes: import scala.tools.nsc.Global import scala.tools.nsc.Settings def main(args: Array[String]) { val s = new Settings s processArgumentString "-usejavacp" val g = new Global(s) val r = new g.Run } That works for your scenario. Even easier: java -Dscala.usejavacp=true -jar ./scall.jar Bonus info, I happened to come across the enabling commit message: Went ahead and implemented classpaths as described in email to scala-internals on the theory that at this point I must know what I'm doing. ** PUBLIC SERVICE ANNOUNCEMENT ** If your code of whatever kind stopped working with this commit (most likely the error is something like "object scala not found") you can get it working again

Categories : Scala

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

Why use template engine in playframework 2 (scala) if we may stay with pure scala
Actually you should ask this question to the dev team, however consider few points: Actually you don't need to use the Play's templating engine at all, you can easily return any string with Ok() method, so according to your link you can just do something like Ok(theDate("John Doe").toString()) Play uses approach which is very typical for other MVC web-frameworks, where views are HTML based files, because... it's web dedicated framework. I can't see nothing wrong about this, sometimes I'm working with other languages/frameworks and can see that only difference in views between them is just a language-specific syntax, that's the goal! Don't also forget, that Play is bilingual system, someone could ask 'why don't use some Java lib for processing the views?' The built-in Scala XML literals a

Categories : Scala

Why can I start the Scala compiler with "java -cp scala-library.jar;. Hello World"?
Short version: you're not using the java compiler, you're using the java runtime. Long version: there's a big difference between javac and java. javac is the java compiler, which takes in java source code and outputs jvm bytecode. java is the java runtime, which takes in jvm bytecode and runs it. But one of the great things about the jvm is that you can generate bytecode for it any which way. Scala generates jvm bytecode without any java source code.

Categories : Java

Scala Def Macros - How do I get the parameterized type member of a symbol?
I am guessing from => IWantThis that paramList is not a val but an arity-0 method without parentheses: def paramList: List[IWantThis] = ??? If so, the member is a method type, and you have to get the return type of the method before extracting arguments from it: val meWantArg = classSymbol.member("paramList": TermName).asMethod.returnType val TypeRef(_,_,args) = meWantArg

Categories : Scala

Can I use Scala List with Slick (Play)?
You can do that by defining a type mapper from let's say List[Int] to String and vice-versa. One possibility: implicit def date2dateTime = MappedTypeMapper.base[List[Int], String]( list => list mkString ",", str => (str split "," map Integer.parseInt).toList ) I say it's a possibility 'cause I haven't tested. Not sure the fact it's returning a list will disrupt Slick. One place where it can be ambiguous are aggregate queries, where you'd want to count the number of , and not do a count(field) (which will obviously be one). But this is completely non-relation. The relational way would be to have a new table with two fields, one foreign key referring one line at table SCORES and another field with one SCORE_PER_TIME. The foreign key should be a non-unique index so searches ar

Categories : Scala

Scala Play Framework 2.1.1 JSON
__ is an alias for JsPath companion object is the operator to parse the symbol to read from the Json object. And tupled just puts them into a tuple so you can do something like case (name, age) => as in the example in the doc you posted.

Categories : Json

play scala json of map with list
You can solve this problem by transforming your Map[User, List[Address]] to a List[User], and the JsonWriter will became easy to write. Something like: list.map { case (user, address) => user.copy(addresses = address.toSeq) }

Categories : Scala

Can't get the id in play framework scala program
The error message tells you what is wrong. Your userprofiles is a list of UserProfile. It does not have a member called id. Yet, you are trying to access it: @for(userprofile <- userprofiles.id) // ^--- this is invalid I think what you are trying to do is: @for(up <- userprofiles){ @if(up.id == userprofile.id) {} else { ... } }

Categories : Scala

Scala Play Json Reads
Just add the business key in the path: implicit val bsnsRds = ( (__ "business" "name").read[String] ~ (__ "business" "preferredUrl").read[String] ~ (__ "business" "businessPhone").read[String] ~ (__ "business" "retailer").read[Retailer](rltRds) )(Business)

Categories : Json

Play Scala Anorm One to Many relationship
A side note about something I have found useful: if youre not sure you will always want to fetch the addresses for a user you can avoid adding that relation as a field and instead use tuples or other datastructures for representing. This would allow you to have a method like this: def allUsersWithAddresses(): Map[User, Seq[Address])] = ... But still have methods that returns only users without having the joined data. To read a join (or subselect) you will have to parse the combined output with a parser, something like this: .as(User ~ Address *).groupBy(_._1) If you really want to put the addresses inside of user you'd have to make the adress list empty from the user parser and then map each distinct user into one with the addresses: .as(User ~ Address *).groupBy(_._1).map { cas

Categories : Mysql

Scala JSON Reads in Play 2.1.1
Try this: import play.api.libs.json._ import play.api.libs.functional.syntax._ implicit val priceReads:Reads[Price] = ( (__ "base").read[Int] ~ (__ "sale").readNullable[Int] )(Price.apply _) Strange that just passing case class is not working ...

Categories : Json

Why is VectorBuilder in the package scala.collections.immutable?
VectorBuilder is not meant to be used directly. If you want to get a builder for a Vector, you only need to call Vector.newBuilder[T], which returns a Builder[T, Vector[T]] (with the underlying instance being a VectorBuilder). So if you want the default builder that would be used to create a Seq, you only need to call Seq.newBuilder: scala> Seq(1,2,3) res0: Seq[Int] = List(1, 2, 3) scala> Seq.newBuilder[Int] res1: scala.collection.mutable.Builder[Int,Seq[Int]] = ListBuffer() scala> Seq.newBuilder[Int].result res2: Seq[Int] = List() The above shows that the default implementation of Seq is list, and, logically, the default builder for a Seq is actually a mutable.ListBuffer. ListBuffer is more than just a List builder, that's why it is in collection.mutable whereas VectorBuil

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 for each loop got error when convert java to scala
override def saveOrUpdateAll(entities: Collection[T]){ import scala.collection.JavaConverters._ val session: Session = getSession() for (entity <- entities.asScala) { session.saveOrUpdate(entity) } } There is no for each loop in scala. You should wrap your collection using JavaConverters and use for-comprehension here. JavaConverters wraps Collection using Wrappers.JCollectionWrapper without memory overhead.

Categories : Java

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

Scala errors "value toInt is not a member of String" and "not found: type"
Importing scala.collection.immutable solved the problems with collections, for the classOf problem I found a workaround - using getClass instead. toInt problem remains unsolved. There is a workaround though - using the exact code from that definition: java.lang.Integer.parseInt. I have a feeling that this is also a problem with imports.

Categories : Scala

Generic way to implement a Pk Writes in Play Scala
The only thing you need to do is ensuring that there is deserializer for type E in scope, because now you can't be sure that each type you use is writeable. You can try it: class Value[A](value: A){ def get[A] = value } implicit def valueWrites[E](implicit longWrites: Writes[E]) = new Writes[Value[E]]{ def writes(value: Value[E]): JsValue = Json.toJson(value.get) } Json.toJson(new Value(5L)) You can shorten implicit method to: implicit def valueToJson[E: Writes] = new Writes[Value[E]]{ def writes(value: Value[E]): JsValue = Json.toJson(value.get) } Edit: These two methods above are exactly the same, it means that method needs implicit value, in your case Pk[Long], so this method knows how to deserialize number. In other words, E: Writes tells the method: search for imp

Categories : Scala

Async Request in (Scala) Play "Hangs"
OK, I figured it out. Oh what a pain that was. The issue was that my "fire and forget" task was a long running task. But the thread pool size on the deployment machine ended up being smaller than my development machine. As a result, this long running task dropped in the thread pool and clogged it up. So the processing of the AsyncResult was presumably preempted by the long running calculation (it was actually blocking on a result from a long running calculation, but the bottom line is that it blocked). After reading a really nice explanation of futures in Scala 2.10 by Heather Miller, I noticed the blocking construct that can be used to temporarily expand the size of the thread pool for a single future. I wrapped my blocking code with a blocking call and that did the trick. Presuma

Categories : Scala

Play framework scala and mysql error
I think it would work if you removed the quotes altogether (or use backticks, as suggested by Carsten). Here is the doc: http://dev.mysql.com/doc/refman/5.0/en/identifiers.html

Categories : Mysql

Serving local images with Play 2 / Scala
Just add an Action in a Controller that provides the image: def picture(name: String) = Action { Ok.sendFile(new java.io.File(name)) // the name should contains the image extensions } Then add the corresponding route in your routes file: GET /picture/:name controllers.MyPictureController.picture(name: String) And your HTML should look like: <img src="/picture/image.png"> or if you use the Scala templates: <img src="@routes.controllers.MyPictureController.picture("image.png")">

Categories : Scala

Scala Play framework 2.1 derived classes
The json API extensively uses implicit parameters which is a feature of Scala where you can provide an "implicit" parameter list and if you don't specify those parameters the compiler will try to find an object in the current scope that is marked as implicit and matches that signature. So if you for example would write: implicit val s = "my implicit string" def magicPrint(implicit message: String) { println(message) } // and then call it magicPrint The compiler would select s for the parameter message since it is in scope and has the correct type (String), so after the implicit resolution the last line of code would actually look more like this magicPrint(s) The Format/Writer is selected by the compiler, at compile time, with an implicit parameter. If you look at the signature of

Categories : Scala

What's the conventional way to handle a transaction in Play 2 Scala?
I'm not sure that there is a best practice for this yet. I look forward to reading other people's answers. This page should show you how to do what you want to do. Basically in Global you either extend WithFilters or override doFilter. You're still just wrapping the Action, but you're doing it from a central place. Now, whether or not this is a better idea than doing the action compsoition as suggested here, I don't know.

Categories : Database

Run scala compiler with options from play console
You can add scalac options in the project/Build.scala file. Open this file and add your own project settings into the Play project object at the bottom of the file. For example: val main = play.Project(appName, appVersion, appDependencies).settings( // Add your own project settings here scalacOptions += "-feature" )

Categories : Scala



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