How to JSON serialize sets?

I have a Python set that contains objects with __hash__ and __eq__ methods in order to make certain no duplicates are included in the collection. I need to json encode this result set, but passing even an empty set to the json.dumps method raises a TypeError. File “/usr/lib/python2.7/json/encoder.py”, line 201, in encode chunks = self.iterencode(o, … Read more

Set value of hidden field in a form using jQuery’s “.val()” doesn’t work

I’ve been trying to set the value of a hidden field in a form using jQuery, but without success. Here is a sample code that explains the problem. If I keep the input type to “text”, it works without any trouble. But, changing the input type to “hidden”, doesn’t work ! <html> <head> <script type=”text/javascript” … Read more

Picking a random element from a set

How do I pick a random element from a set? I’m particularly interested in picking a random element from a HashSet or a LinkedHashSet, in Java. Solutions for other languages are also welcome. 34 Answers 34 int size = myHashSet.size(); int item = new Random().nextInt(size); // In real life, the Random object should be rather … Read more

How to map/reduce/filter a Set in JavaScript?

Is there any way to map/reduce/filter/etc a Set in JavaScript or will I have to write my own? Here’s some sensible Set.prototype extensions Set.prototype.map = function map(f) { var newSet = new Set(); for (var v of this.values()) newSet.add(f(v)); return newSet; }; Set.prototype.reduce = function(f,initial) { var result = initial; for (var v of this) … Read more

Java Set retain order?

Does a Java Set retain order? A method is returning a Set to me and supposedly the data is ordered but iterating over the Set, the data is unordered. Is there a better way to manage this? Does the method need to be changed to return something other than a Set? 13 Answers 13