w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Model.extend fails to update Collections. Backbone.js bug
I have since solved the issue and written a small plugin for this functionality. https://github.com/allouis/backbone.dynamicCollections

Categories : Javascript

Scala collections contains not using ==?
The problem is, that you don't override, but overload the == method. It has to be defined as def == (a: Any): Boolean, because in java and scala you can compare any two objects. But in case classes this method is final. You can however override equals with the same signature, because == is just an alias for equals. But overriding these methods in case classes should be avoided, because the definition of equality on case classes is, that every single value has to be equal on both instances.

Categories : Scala

Where are the test for Scala collections?
This is a good question that has been asked before on SO. There are some collections tests under test/files/scalacheck and others under test/files/run/*coll* in the source repository. There is no conformance test or TCK per se for custom collections. Integration with collections usually involves a specific implementation requirement. For example, the ScalaDoc for immutable.MapLike tells you to implement get, iterator and + and -. In theory, if you test the template methods, you can rely on everything you get for free from the library. But the doc adds: It is also good idea to override methods foreach and size for efficiency. So if you care about that, you'll be adding performance tests too. The standard library doesn't include automated performance testing.

Categories : Scala

Using the Scala collections (immutable) from Java
Yes, you just need to put scala-library.jar in the classpath. See this thread for an example using Scala immutable lists in Java As an alternative, Clojure also offers persistent data structures e.g. a PersistentHashMap that come with Java source code, so your method names won't look as odd

Categories : Java

Nil object in mutable Scala collections
Nil is the zero-length (empty) immutable List, not a general empty marker for collection types. It looks like you simply want new ResourceMap, or (if you want to clear the current map and then return it rather than just return a new empty instance): clear; this

Categories : Scala

Scala immutable operations on mutable collections
No, since such sharing would violate either of the two: returning a new object with modified contents and not modifying the original collection when the new object is modified. Sharing structure only works well with immutable collections since immutability eliminates the risk of changing one object when the other one changes. Of course there is sharing at the level of contents, e.g. in a mutable.List[String], the new list uses references to the same String instances as the original, but that's where it ends.

Categories : Scala

Scala collections support for SpringEL/Thymeleaf
You could remove @BeanProperty, and add a getter for Interoperability: case class User(emails: List[String]) { def getEmails = JavaConversions.asJavaIterable(emails) } Far more elegant is to use a Scala EL resolver Update As for the resolver: Somewhere in Thymeleaf/SpringEL, an expression parser resolves properties of beans: So in your example: ${user.emails[0]} it possibly uses reflection to see if there is a getter method getEmails in the user object. This is the place where you could add the same code as in the linked Scala EL resolver: If the getter returns a Scala collection, wrap it in a Java iterable (or convert it to an array) before.

Categories : Scala

Scala - Mutable thread safe collections
You're duplicating topics.... As was mentioned by AlexIv in his answer, there's a trait you can mix in if you want thread safety. There's another way though: val synchronizedMap = new scala.collection.mutable.LinkedHashMap[String, Any]() with scala.collection.mutable.SynchronizedMap[String, Any] That should give you the map with synchronization on each access. Easy, but might not meet the performance requirements. If so, it would be probably easier to create a custom class extending the LinkedHashMap, mixing in the concurrent.Map trait (as was suggested) and provide the implementation of relevant methods, i.e: putIfAbsent, remove replace (2 overloads).

Categories : Multithreading

Write performance scala immutable collections
It would help if you'd post the relevant snippet and which operations you call on the sequence -- immutable.Seq is represented using a List (see https://github.com/scala/scala/blob/v2.10.2/src/library/scala/collection/immutable/Seq.scala#L42). My guess is that you've been using :+ on the immutable.Seq, which under the hood appends to the end of the list by copying it (probably giving you quadratic overall performance), and when you switched to using immutable.List directly, you've been attaching to the beginning using :: (giving you linear performance). Since Seq is just a List under the hood, you should use it when you attach to the beginning of the sequence -- the cons operator :: only creates a one node and links it to the rest of the list, which is as fast as it can get when it comes

Categories : Scala

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

What is the best way to extend a Java Exception in Scala properly?
It looks to me like you should be able to just change the cause-only constructor to: def this(cause: Throwable) = this(cause.toString, cause) EDIT: To handle null cause: def this(cause: Throwable) = this(if (cause == null) "(no message)" else cause.toString, cause) Replace "(no message)" with null (not recommended) or whatever text you feel is appropriate.

Categories : Scala

Scala mutable collections and "Reference must be prefixed warnings"
I tried it in the 2.10.2 shell and didn't see any warnings. One way of "aliasing" the mutable.LinkedList extractor is doing: scala> MutableLinkedList(1,2,3,4,5) res0: scala.collection.mutable.LinkedList[Int] = LinkedList(1, 2, 3, 4, 5) scala> val LL = MutableLinkedList LL: scala.collection.mutable.LinkedList.type = scala.collection.mutable.LinkedList$@5798795f scala> res0 match { case LL(1,2, _*) => "yey"; case _ => "bad" } res3: String = yey See? Now LL points to the MutableLinkedList companion object

Categories : Scala

How do I set the default number of threads for Scala 2.10 parallel collections?
I know that the question is over a month old, but I've just had exactly the same question. Googling wasn't helpful and I couldn't find anything that looked halfway sane in the new API. Setting -Dscala.concurrent.context.maxThreads=n as suggested here: Set the parallelism level for all collections in Scala 2.10? seemingly had no effect at all, but I'm not sure if I used it correctly (I run my application with 'java' in an environment without 'scala' installed explicitly, it might be the cause). I don't know why scala-people removed this essential setter from the appropriate package object. However, it's often possible to use reflection to work around an incomplete/weird interface: def setParallelismGlobally(numThreads: Int): Unit = { val parPkgObj = scala.collection.parallel.`package`

Categories : Scala

Making more "functional" code in Scala to use immutable collections
This is what I would consider a more functional approach: val emptySet = Set[TObject]() def search(node: VPNode[TPoint, TObject], query: TPoint, radius: Double): Set[TObject] = { val dist = distance(query, node.point) val left = Option(node.left) // avoid nulls .filter(_ => dist <= radius + node.radius) // do nothing if predicate fails .fold(emptySet)(l => search(l, query, radius)) // continue your search val right = Option(node.right) .filter(_ => dist >= radius + node.radius) .fold(emptySet)(r => search(r, query, radius)) left ++ right ++ (if (dist < radius) Set(node.obj) else emptySet) } Instead of passing around your mutable.Set to each search function, the search function returns a Set[TObject] which it then concatenates onto other s

Categories : Scala

Ruby's inject method like for Scala collections: any idea?
You can use List's (actually, TraversableLike's) map function, as follows: list.map(_.id). There are a wealth of useful methods like this available to the Scala collection classes - well worth learning.

Categories : Scala

Why google-collections AbstractMultimap class use transient keyword for member variable?
That's because the AbstractMultimap class doesn't actually contain the backing Map implementation; that's provided by the concrete subclass, which is responsible for managing serialization: For serialization to work, the subclass must specify explicit readObject and writeObject methods.

Categories : Java

How to extend an object in Scala with an abstract class with constructor?
I have no idea why should Wood extend AbstractResource, but this works: class AbstractResource(val amount:Int) { def getAmount = amount } case object Wood extends AbstractResource(0) { def apply(amount: Int) = { new AbstractResource(amount) } }

Categories : Scala

Single iteration => Multiple output collections from Java to Scala
One purely functional and immutable way would be to have a generic function that separates collections into buckets, by predicate: case class Person(name: String, age: Int, gender: String) def bucketsByPredicate(people: Seq[Person], predicates: Seq[Person => Boolean]) = { people.foldLeft(predicates.map(predicate => (predicate, List.empty[Person]) )) { case (predicates, person) => predicates.map { case (predicate, members) => (predicate, if(predicate(person)) person :: members else members) } }.map(_._2) } Then an example usage could be: val olderThan60 = (p: Person) => p.age >= 60 val male = (p: Person) => p.gender == "m" val Seq(olderThan60People, malePeople) = bucketsByPredicate(people, Seq(olderThan60, male))

Categories : Java

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 - 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

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

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

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

set in collections allows duplicate values?
Set#add returns true if this set did not already contain the specified element else false. It does not thorw Exception if value is duplicate. Adds the specified element to this set if it is not already present (optional operation). More formally, adds the specified element e to this set if the set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false. In combination with the restriction on constructors, this ensures that sets never contain duplicate elements. Find more on Documentation boolean result = s.add("Mac"); // would be true boolean result1 = s.add("Mac");// would be false

Categories : Java

C# compare values of properies in different collections
I have this code, maybe it's overkill but it's generic: public static bool IsEquivalent<T, TU>(this ICollection<T> collection, ICollection<TU> sourceCollection, Func<T, TU, bool> predicate) where T : class { var copyCollection = collection.Clone(); if (copyCollection.Count == 0 && !sourceCollection.Any()) return true; foreach (var source in sourceCollection) { var element = copyCollection.FirstOrDefault(x => predicate(x, source)); if (element == null) return false; copyCollection.Remove(element); } return !copyCollection.Any(); } public static ICollection<T> Clone<T>(this ICollection<T> listToClone) { var array = new T[listT

Categories : C#

Java collections - How to add multiple values in the collection?
This code will print the values many times int itemCount = list.size(); for (int z = 0; z < itemCount; z++) { String values = ""; for(int j=0;j<list.size();j++) { values += list.get(j); } System.out.println(me.getKey() + ": value :" + values); } You probably want something like this: String values = ""; for(int j=0;j<list.size();j++) { values += list.get(j) + " "; } System.out.println(me.getKey() + ": value :" + values);

Categories : Java

Creating a JAX-RS object that contains collections and primatives as values of a map
Couple of ideas: Jackson can use JAXB annotations as well as its own: support may or may not be enabled by default by your JAX-RS container, but even if not, enabling is easy Jackson can also output XML with its XML module, from https://github.com/FasterXML/jackson-dataformat-xml -- can use Jackson and/or JAXB annotations One thing to note with respect to XML is that whereas with JSON you can generally get any sensible JSON to map to Java objects, XML has its own idiosyncracies, and it may be more difficult to get exact structure on both sides. So if at all possible, it is good to focus on data you are passing, and figuring out good Object representation, and then see what kinds of XML representations can be produced. I realize that this may not always be an option, when dealing with X

Categories : Xml

jQuery extend overwrites wrong values
You are right, this is obviously happening because jQuery's extend is "shallow extending" the object.. thus replacing the entire "animation" property. To fix this, use your brandy dandy deepExtend: Object.deepExtend = function(destination, source) { for (var property in source) { // loop through the objects properties if (typeof source[property] === "object") { // if this is an object destination[property] = destination[property] || {}; Object.deepExtend(destination[property], source[property]); // recursively deep extend } else { destination[property] = source[property]; // otherwise just copy } } return destination; }; You can use it as follows: slider.settings = Object.deepExtend(slider.settings, options);

Categories : Javascript

java sorting to findout lowest values using collections
private class BallsComparator implements Comparator<Ball> { public int compare(Ball o1, Ball o2) { return new Integer(o1.getWeight()).compareTo(o2.getWeight); } } Collections.sort(myBallsList, new BallsComparator()); This assumes that your balls have a getWeight() method that gives an int or Integer value. If not, adjust accordingly.

Categories : Java

scala type error for class with map member typed with existential type
Unless you explicitly require getting the keys back out as the statically correct subtype (which seems unlikely), then the following will work: case class DictVariant1(data: Map[MyBaseType, Double]) val d = List((Concrete1() : MyBaseType, 3.5)).toMap val dv1 = DictVariant1(d) Using a type ascription forces Concrete1() to be seen as an instance of the base type; you'd get the same effect if you added an explicit type to d: val d : Map[MyBaseType, Double] = .... Or if you put multiple entries in such that the type inferencer picks the base type: val d = List((Concrete1(), 3.5), (Concrete2(), 4.5)).toMap The 'get' you use is always going to fail, however, because you're trying to use the whole Map as an index: it works fine if you provide a sensible key: dv1.data.get(Concrete1())

Categories : Scala

How to sum values in list of csv values in Scala?
You could first use a groupBy to collect the values into a map, then use mapValues to compute the answer you need, which is just sum in this example. Also note that here the team names is key and the sum is value, but that should not really matter (?) .

Categories : Java

Coffeescript class extend more bloat than Backbone extend
Since you're asking just about the bloat, let's have a look at some code. JavaScript with Backbone.Model.extend If you open up the Backbone source code, you'll see the extend function is the following: var extend = function(protoProps, staticProps) { var parent = this; var child; if (protoProps && _.has(protoProps, 'constructor')) { // _.has comes from child = protoProps.constructor; // underscore, even } else { // more 'bloat' child = function(){ return parent.apply(this, arguments); }; } _.extend(child, parent, staticProps); // more underscore var Surrogate = function(){ this.constructor = child; }; Surrogate.prototype = parent.prototype; child.pr

Categories : Javascript

How to create Nested Models & Collections (sub collections)
you are almost there. You can use parse method on the model where you can write up your logic of associating the words collection to the vocabulary model.. Something in these lines. // This would be your main Model // Set the idAttribute on it // Use the parse method here which hits before initialize // where you attach the words collection on each Vocabulary Model Entities.Vocabulary = Backbone.Model.extend({ idAttribute : 'id', parse: function (response) { // If theresponse has wods in response // attach it words collection to the Vocabulary Model if (response.words) { this.words = new Entities.Vocabulary.Words(response.words || null, { parse: true }); } // Delete the words object from response as the

Categories : Backbone Js

get an data member values using FieldInfo class
You have access to a GetValue method of the FieldInfo instance. That should give you the value of that field for a specific instance of the class to which the field belongs to.

Categories : C#

LINQ JOIN for Collections in Collections
You could use the Aggregate function in Linq: var users = new List<User>(); var roles = new List<Role>(); //Populate users and roles var rolesAndUsers = new Dictionary<Role, List<User>>(); users.Aggregate(rolesAndUsers, (d, u) => { ICollection<Role> userRoles = u.UserRoles; foreach (var userRole in userRoles) { if (!d.ContainsKey(userRole)) d.Add(userRole, new List<User>());

Categories : C#

How to transpose a map with list values in Scala
val m = Map ( 10 -> List("10a", "10b", "10c"), 29 -> List("29a", "29b", "29c") ) m.map{ case (k, vs) => vs.map(k -> _) }.toList.transpose.map(_.toMap) Note that this also handles your "empty list" case

Categories : Scala

How to detect Infinity values in Scala?
Scala's Double has an isInfinite method, and Neg/Pos variants: scala> val a = 22.0 a: Double = 22.0 scala> a.isInfinite res0: Boolean = false scala> val b = 2.0/0 b: Double = Infinity scala> b.isInfinite res1: Boolean = true scala> b.isPosInfinity res4: Boolean = true

Categories : Scala

Using Scala Separator and iterate the values
You're printing out the array p at each iteration. You want to print out the contents of the array that contains the strings. I simplified it to this version. object SeparatorDemo { def main(args: Array[String]) { var stmt:String=("a,number,of,words") var words=stmt.split(",") for(word <- words){ println(word) } } } Even more concise is to chain the splitting and the iteration into one statement: stmt.split(",").foreach(println(_)) Either way gives this output: scala> SeparatorDemo.main(Array()) a number of words

Categories : Scala

Scala XML - passing down values using the .map method in XML
See if this works for you: object TestXml { def main(args: Array[String]) { val xml = <root> <here> <dealID>foo</dealID> </here> </root> println(insertRefIntoXml(2, xml)) } def insertRefIntoXml(ref: Int, entry: Node): Node = { def doInsertRef(n:Node):Node = { n match { case <root>{ mainRoot @ _* }</root> => <root>{ mainRoot.map(doInsertRef)}</root> case <here><dealID>{ contents }</dealID></here> => <here><dealID>{ ref }</dealID></here> case other @ _ => other } } doInsertRef(scala.xml.Utility.trim(entry)) } } There were a couple of issues. First, in ord

Categories : Xml



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