w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How do I create JSON objects programmatically in playframework 2.1 scala
You've misspelt your import statement; it should be import play.api.libs.json.Json (it's important to remember Scala is case-sensitive). Fixing that, the code works: scala> :paste // Entering paste mode (ctrl-D to finish) import play.api.libs.json.Json Json.obj("key" -> "value") // Exiting paste mode, now interpreting. import play.api.libs.json.Json res0: play.api.libs.json.JsObject = {"key":"value"} scala>

Categories : Json

Scala using JSON and/or XML templates
unfortunately I don't know any really good library to do this in XML (although Anti-Xml is worth taking a look). But there are such library for Json and it's the PlayJson With play json you can do basically everything you can do with Ruby's JsBuilder, except some paradigm difference: Scala tries to be as functional as possible and many many libraries operate with unmutable data structures. Play json is not an exception. This means that you cannot just change some value deep in the json tree, you need to reconstruct the whole json object Scala is a statically typed language. Which is great, because compiler checks all type-signatures for correctness, except we must provide those signatures. Here's example code: import org.joda.time.DateTime import org.joda.time.format.DateTimeFormat

Categories : Xml

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

Using Atlassian Bamboo CI with Scala Playframework 2.X
You must add the following to your sbt build file to generate JUnit output for your Specs. testOptions in Test += Tests.Argument("junitxml", "console") Then you can define the SBT Task to execute the tests.

Categories : Scala

Usage of Scala Future in Playframework?
You can use Async: def index = Action{ val myFunction:Future[Option[String]] = // Async{ myFunction.map{ case Some(x) => Ok(x) case None => InternalServerError } } } Basically you tell play that: Whenever myFunction is evaluated, return the result back to User. The trick here is to map on the Future content instead of using a callback, this lets you operate on the result. The wonderful part is that it is still asynchronous. In the sense that the http request thread evaluation index will not get blocked. Some documentation on it here.

Categories : Scala

How to add GeoSlick library in my Playframework scala Application
For many SBT projects (which GeoSlick obviously is, because it has the typical SBT files like build.sbt) the following procedure gets you an jar you can import in your project. Clone the GIT repository with git clone https://github.com/ahinz/GeoSlick Move into the directory and run sbt. This will download all dependencies defined in the project definitions. If everything was downloaded correctly, type into the sbt shell package and enter. This last step will compile a SNAPSHOT-jar file and puts it into the directory target/scala-2.10/ I did this for the project you named and it worked fine, producing a file *geoslick_2.10-0.1.0-SNAPSHOT.jar*.

Categories : Postgresql

Getting scala's template loop index in playframework
You should combine it in one for loop: @if(list != null) { @for{a <- 0 to list.size()/5 b <- a*5 to a*5+5} yield html } } And use option instead of null checking. Also you can use map function to transform your list. See details in Play documentation - http://www.playframework.com/documentation/2.0/ScalaTemplates

Categories : Scala

Generalization and reuse of a part of template in scala (in playframework)?
That function is called a tag in Play and is nothing else than mini-view, which you can call /include with params from other 'normal' views: check the Tags (they are just functions, right?) section in the doc. For JS... afaik, there's still no good way for escape the JS in the Play views, so most secure way is avoiding placing JS directly in it. Instead import them as a common JS file in the document's head with <script src="...

Categories : Scala

Playframework scala, how to asynchronous convert a web service call to a response without Async
If you look at http://www.playframework.com/documentation/2.1.3/ScalaAsync you are told to use the Async method. When you look at the signature you will see how the magic works: def Async(promise : scala.concurrent.Future[play.api.mvc.Result]) : play.api.mvc.AsyncResult The method returns AsyncResult, which is a subclass of Result. That means we need to do our work of generating our normal Result within a Future. We can then pass the future result to this method, return it in our action method, and Play will take care of the rest. def Authenticated[A](p: BodyParser[A])(f: AuthenticatedRequest[A] => Result) = { request => { case class UserPair(userId: String, user: User) val userPair: Option[UserPair] = for { userId <- request.session.get(use

Categories : Scala

Scala PlayFramework and Angular JS - too much effort in terms of duplication and mixing concetps
For now this seems could help me: https://github.com/nau/jscala or this : https://github.com/lampepfl/scala-js But this is not necessary an answer. UPDATE: The only one way I see for scala developers who do not want jump too deep in JS, is: Wait until solutions like JScala or Scala-JS become ready to use (or contribute) in order to substitute CoffeScript in Play2. Before that day we just have to live with that. Here you we can see: https://github.com/typesafehub/angular-seed-play The play app with no app / view directory in it. Aslo the "routes" file is almost empty- because Angular cares about it on client side. So we do not need them. Kind of RIA way. So if one day we decide to to make this app available for Google (to be googlable), we will put view & routes there. UP

Categories : Javascript

Intellij IDEA 12 doesn't recognize Playframework 2.1 (java) dependencies set in Build.scala
You have to rerun the play idea command in order to get IntelliJ to know that there are new dependencies added. I normally enter the play CLI and then run: idea no-sbt-build-module with-sources=yes This will download the sources for the dependencies (if they exist) and also make sure that the output path will be correct and that modules are not loaded several times.

Categories : Intellij Idea

Scala + Playframework + JClouds: java.lang.IllegalArgumentException: Can not set javax.inject.Provider field
Very strange, it works when I move the two dependencies "org.apache.jclouds" % "jclouds-allblobstore" % "1.6.1-incubating", "com.google.code.findbugs" % "jsr305" % "1.3.+" to the top of the list. When they are at the bottom, it doesn't work. So "mysql" % "mysql-connector-java" % "5.1.25", "org.squeryl" %% "squeryl" % "0.9.5-6", "net.sf.jasperreports" % "jasperreports" % "4.7.1", "com.typesafe" %% "play-plugins-mailer" % "2.1.0", "org.scalatest" %% "scalatest" % "2.0.M5b" % "test", "jp.t2v" %% "play2.auth" % "0.9", "jp.t2v" %% "play2.auth.test" % "0.9" % "test", "org.scala-lang" % "scala-actors" % "2.10.0" % "test", "com.unboundid" % "unboundid-ldapsdk" % "2.3.1", "net.sf.uadetector" % "uadetector-resources" % "2013.06", "org.apache.commons" % "commons-email" % "1.3.1", "org.ap

Categories : Scala

data.table subsetting for bootstrapping
In addition to @DWin's comment: If you profile your code you will see that the most costly repeated function calls are those to seq (which is necessary at most once) and sample. Rprof() median(sapply(seq(2000), function(y) { dt.samp() })) Rprof(NULL) summaryRprof() # $by.self # self.time self.pct total.time total.pct # "seq.default" 3.70 35.10 3.70 35.10 # "sample.int" 2.84 26.94 2.84 26.94 # "[.data.table" 1.84 17.46 10.52 99.81 # "sample" 0.34 3.23 6.90 65.46 # "[[.data.frame" 0.16 1.52 0.34 3.23 # "length" 0.14 1.33 0.14 1.33 # "cor" 0.10 0.95 0.26 2.47 #<snip> Faster subs

Categories : R

Passing an implicit to a playframework JSON Reads
You can't change Reads[T], it's clear. I would simply create my own reads function such as? def customReads[T](json:JsValue)(implicit reads: Reads[T], configuration: TenantConfiguration): JsResult[T] = ...

Categories : Json

Bootstrapping data to a page rendered with handlebars
As it worked out, it was a problem on the client-side. Previously, my code had been: var bootstrap = {{{bootstrap}}};. The bootstrap variable here isn't being received as a string: it's being received as an object. Putting the variable between single quotes solved the issue: var bootstrap = '{{{bootstrap}}}'; There's still a mysterious limit on the length of the string: past 150 or so objects, the JSON parse fails-on-load. Otherwise: works great.

Categories : Backbone Js

How to convert List to JSON on playframework 2.1 Java
sorry, I defeniere false return-type rather than String json = play.libs.Json.toJson(plzs); must be org.codehaus.jackson.JsonNode json = Json.toJson(plzs);

Categories : Java

Does scala provide anything like C++ templates?
Use Numeric, available as an implicit. import scala.math.Numeric; case class Point2[T](x: T, y: T)(implicit num: Numeric[T]) Look at Numeric in the API, does what you need.

Categories : C++

scala play 2.1.1 json functional syntax mapping data to a different format
I managed to get this one figured out, I was using the wrong type of functor map operations and had the types I was working with backwards. Here are working reads/writes implementations in the much nicer functional syntax. implicit val writesBanner = ( (__ "id").write[Int] and (__ "ownerId").write[Int] and (__ "licenseeId").writeNullable[Int] and (__ "statusColor").writeNullable[String] and (__ "content").writeNullable[String] and (__ "displayStart").write[String].contramap[DateTime](dt => userDateFormatter.print(dt)) and (__ "displayEnd").write[String].contramap[DateTime](dt => userDateFormatter.print(dt)) and (__ "created").write[DateTime] and (__ "updated").write[DateTime] )(unlift(Banner.unapply)) implicit val readsBanner = ( (

Categories : Json

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

Access mysql data base remotely from playframework 1.2.4
In your example you define a mysql URL but set the driver to postgresql... Try to comment the driver setting, or set it to: 'com.mysql.jdbc.Driver' You can alos try to connect to your mysql server using the mysql command line: mysql -h xxx.xxx.47.78 -u root -p Then enter the root password (mysql root password). This will test the network connection to the mysql server.

Categories : Mysql

AngularJS templates can't use JSON that contains hyphen
try {{item.link['xx-test'].href}} For further reading on bracket notation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

Categories : Angularjs

Binding hierarchical data with templates using a generic Tree data structure
You're going to need to use a DataTemplateSelector. MSDN describes how to use one. Even though the example is for a ListBox, you can do this with a TreeView.

Categories : Wpf

How to Manipulate JSON AST in Scala
When I was implementing some very specific json diff using lift json I used a lot of recursive functions to get to the jpath where I need to modify value, and modified json was constructed when recursion "collapsed". LiftJson is immutable after all. You mentioned lenses as another approach, which is very interesting by itself. But my current favourite is play-json library that is working like a charm in a situation when you need to do json-to-json transformation: from Mandubian Blog: val gizmo2gremlin = ( (__ 'name).json.put(JsString("gremlin")) and (__ 'description).json.pickBranch( (__ 'size).json.update( of[JsNumber].map{ case JsNumber(size) => JsNumber(size * 3) } ) and (__ 'features).json.put( Json.arr("skinny", "ugly", "evil") ) and (__ 'danger).json.p

Categories : Scala

Decoding JSON to a Map in Scala
scala.util.parsing.json.JSONObject has an obj method that returns a Map[String, Any]. scala> val map = Map("zero" -> 0, "one" -> 1, "two" -> 2) map: scala.collection.immutable.Map[String,Int] = Map(zero -> 0, one -> 1, two -> 2) scala> scala.util.parsing.json.JSONObject(map) res0: scala.util.parsing.json.JSONObject = {"zero" : 0, "one" : 1, "two" : 2} scala> res0.obj res1: Map[String,Any] = Map(zero -> 0, one -> 1, two -> 2)

Categories : Json

Extracting json in Scala
scala> val jsonStr = """ | { | "data1": { | "field1": "data1", | "field2": 1.0, | "field3": true | }, | "data211": { | "field1": "data211", | "field2": 4343.0, | "field3": false | }, | "data344": { | "field1": "data344", | "field2": 436778.51, | "field3": true | }, | "data41": { | "field1": "data41", | "field2": 14348.0, | "field3": true | } | } | """ jsonStr: java.lang.String = " { "data1": { "field1": "data1", "field2": 1.0, "field3": true }, "data211": { "field1":

Categories : Json

Is init.php bootstrapping?
In the context of web-applications and PHP, the concepts "bootstrapping" and "application initialization" are more or less the same. The filename doesn't matter. As for the details of what such an implementation should contain, that is completely dependant on the architecture of the application.

Categories : PHP

json database get image setting data for json using while loop carousel type jquery json
Look for a jquery carousel plugin. http://vandelaydesign.com/blog/tools/jquery-carousel-plugins/ http://www.webdesigntunes.com/freebies/30-amazing-free-jquery-slider-and-carousel-plugins-of-2013/ Edit: does this help? $data = array(); $x = 0; while ($test = mysql_fetch_array($query)) { $data[$x]['content'] = "<div class='slide_inner'><a class='photo_link' href='#'><img class='photo' src='{$test['image']}' alt='Bike'></a><a class='caption' href='#'>Sample Carousel Pic Goes Here And The Best Part is that...</a></div>"; $data[$x]['content_button'] = "<div class='thumb'><img src='{$test['thumb']}' alt='bike is nice'></div><p>Agile Carousel Place Holder</p>"; $x++; } echo json_encode($data);

Categories : PHP

Large amounts of json data, slow browser evaluation of json data
Firstly, I dont really understand your idea of using for(;;) to break down a huge json. Also, adding something, parsing, removing and splitting the data before using it would just be an extra overhead on the browser. Also, if you are preparing a html string inside a for loop before rendering it, just make sure you dont render it all at once after the loop ends. But keep on rendering it inside the loop so that you dont keep the user waiting till the loop finishes the execution. This should help you deliver a quick html output when there is a huge json for the browser to work on. Hope this might help you.

Categories : Javascript

Get data from JSON, store in IsolatedStorageSettings.ApplicationSettings, retrieve data when JSON is retrieved
The way you are thinking with await and async is correct but you destroyed its concept by calling another method just when the page loads. What Wilfred Wee said is also wrong. The correct way would be to declare an event handler in your App.xamls.cs like this: public event EventHandler<bool> SettingsReady; Then change your Application_Launching() method to the following: private async void Application_Launching(object sender, LaunchingEventArgs e) { var settings = IsolatedStorageSettings.ApplicationSettings; settings.Add("listofCurrency", await CurrencyHelpers.getJsonCurrency()); if (SettingsReady!= null) SettingsReady(this, true); } And now in your MainPage.xaml.cs (CONSTRUCTOR - NOT WHEN LOADED) declare the call back function to be called when the data wi

Categories : C#

Scala - Querying lists, XML, Json
Slick is a Functional-Relational mapper and as such is meant to be used with databases. I'd advise you watch out if choosing slick for your orm of choice because it has brutal and expensive licensing for commercial databases such as oracle and ms sql however if you're hacking away on open source stacks it's fine. Scala has nice xml support without any additional libraries being needed. eg this is perfectly legal syntax in scala without any dependencies: scala> <test fart="stinky">hello</test> res0: scala.xml.Elem = <test fart="stinky">hello</test> There are several json libraries for scala now that can handle json for you. The lift one is relatively popular. I'd maybe look at json4s https://github.com/json4s/json4s If you have xml data or json data in your

Categories : Scala

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

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

Producing json in a Scala app using json4s
What you're seeing in the output is a reflectively serialized tuple, which has fields _1 and _2. This is because the return type that the compiler has inferred for JsonStub.getPeople is Tuple2[String, JObject]. The json4s DSL uses implicit conversions to turn values like the tuple into a JValue. But, if you don't tell the compiler you wanted a JValue, it won't apply the conversion. Ideally, this would result in a compile error, because you tried to produce JSON from something that isn't the right type. Unfortunately, because your web framework assumes you want to fall back to reflection-based serialization, it means there is another way to turn the tuple into JSON, which isn't what you wanted. If you explicitly tell the compiler that you want a JValue and not a Tuple2, the DSL's implici

Categories : Json

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

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

AngularJS and ASP.NET MVC integration and bootstrapping
If you are unable to use a REST service (best option) you can easily do exactly what you suggest in your question but perhaps in more modular way. You can encode your view's model and place it in a global variable and then have a service that pulls this out: Here is an example: <body ng-controller="MainCtrl"> <div>ID: {{data.id}}</div> <div>Name: {{data.name}}</div> <script type='text/javascript'> // mystuff = @Html.Raw(Json.Encode(Model)); Encode the model to json mystuff = { id: 1, name: 'the name'}; </script> </body> app.controller('MainCtrl', function($scope, DataService) { $scope.data = DataService.getData('mystuff'); }); app.factory('DataService', function($window) { var service = {}

Categories : Asp Net Mvc

Angular JS tutorial bootstrapping 2
Typically the directory c:users is your user home directory - are you logged in as user name supersonicseattle? If so, you don't want to create your project there, you want to create it one level down. Have you cloned the git repository yet? It so, it's probably one level down from the directory you're trying to run from.

Categories : Node Js

Error with self-bootstrapping Ant build
I normally create a single "boostrap" target and use this to install ivy into the "$HOME/.ant/lib" directory. See: Ivy fails to resolve a dependancy, unable to find cause The following is a more complete example that does what you're trying to do: How to include ant-contrib.jar dynamically in ANT In conclusion, it's a shame ivy is not packaged by default with ANT. If you discover your hosted service prevents you from copying files into the home directory, then perhaps the simplest thing to do is ship a copy of the ivy jar alongside your source (and enable it using a taskdef) Update Use the following taskdef for ant-contrib: <taskdef uri="antlib:net.sf.antcontrib" classpathref="build.path"/> The homepage needs update. At some stage in the recent past the library was repac

Categories : Java

Backbone.js Bootstrapping collections: How much is too much?
If all you're doing is displaying the content, just bootstrap enough to fill a generous size page and lazy load the rest. If you're doing something interactive (e.g. sorting or filtering) in the browser, then you might still be able to get away with that strategy, provided that users will typically want to at least glance at the data for a few seconds before activating a sort or filter, and your server is fast enough to fill in the remaining items (after the first "page-full") in that time.

Categories : Backbone Js

How to convert normal class to and from JSON with Scala?
I would strongly advise switching to case classes as it opens up more doors as far as frameworks are concerned. If you don't want to switch though, one option that will work is Jackson via the Jackson Scala Module. Using that library and the following code, I was able to get proper two way serialization of your User class: val mapper = new ObjectMapper() mapper.registerModule(DefaultScalaModule) val sw = new StringWriter val u = new User mapper.writeValue(sw, u) val json = sw.toString() val user = mapper.readValue(json.getBytes, classOf[User]) It's a little less scala friendly then the other frameworks that depend on case classes, but it will get the job done.

Categories : Json



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