What Is This Dart Method Called? - list

I figure this must be a pretty common method in Dart. I couldn't find it anywhere, so I created my own. It adds the contents of an arbitrary number of Iterable<T>s together. I called it aggregate
extension IterableExtensions<T> on Iterable<Iterable<T>> {
List<T> aggregate() {
final list = <T>[];
forEach((element) {
element.forEach(list.add);
});
return list;
}
}
Does this method exist in another library? If so, what is the method called and what do I import?

You could solve the problem of flattening an iterable in two ways:
Either
Import dart expansion pack for collection API and use flattened:
https://pub.dev/documentation/collection/latest/collection/IterableIterableExtension.html
import 'package:collection/collection.dart';
// [...]
iterable.flattened.toList();
Use expand (aka flatMap in other languages) method on the outer iterable
iterable.expand((nested) => nested).toList();
https://pub.dev/packages/collection

I'd just call it flattening a list. A simpler way to do it is:
List<T> flatten<T>(Iterable<Iterable<T>> iterables) =>
[for (var iterable in iterables) ...iterable];
package:collection provides CombinedIterableView and CombinedListView classes that do the same thing but lazily. It also provides an IterableZip class that is similar but iterates over items in a breadth-first manner instead of depth-first.
package:quiver also provides concat and zip functions.

Related

Running same set of parameterized tests on multiple Interface implementations

I'm implementing families of algorithms in Java and want to run the same set of algorithm family tests on each algorithm implementation. Let's look at the sorting algorithm case.
I have a few implementations of sorting algorithms. I want to run the same suite of parameterized tests on each implementation without copy/pasting the tests for each interface implementation.
An answer I've seen a few times to "how do I run the same set of tests on multiple class implementations" is to use a parameterized test with a list of the implementation classes to be tested as the input. However, these examples use the class as the only parameter. I want to run parameterized tests on the class under test.
The online examples of parameterized tests I've encountered use simple parameters (a single object/primitive or list of objects/primitives). In my case, I would want to provide the class to be tested and an array of values. I think this is possible, but it feels ugly and I would have to repeat the same test cases for each class type like so (not actual java syntax):
BubbleSorter.class, [1,2,3]
BubbleSorter.class, [3,2,1]
BubbleSorter.class, [-1,2,0]
MergeSorter.class, [1,2,3]
MergeSorter.class, [3,2,1]
MergeSorter.class, [-1,2,0]
InsertionSorter.class, [1,2,3]
...
Ideally, there would be some way to set the sort implementation once and let all of the parameterized tests worry only about the lists of values to be sorted and not which sort class to use.
My gut feeling says to use a parent abstract SorterTest containing the parameterized tests and use a factory method to allow each subclass (ex: MergeSorterTest) to decide which sorter implementation is used. However, a quick google about this seems to imply using inheritance to re-use tests cases in test code is frowned upon.
What is the recommended method for this situation? Is inheritance in test code allowable in some circumstances like this, or is there always a better alternative?
Also I'm using JUnit 5.
In my case, I would want to provide the class to be tested and an array of values.
You can combine multiple sources within e.g. a #MethodSource. Let's assume you have something like a common Sorter interface:
class SorterTest {
#ParameterizedTest
#MethodSource("args")
void test(Sorter sorter, List<Integer> list) {
// ...
}
static Stream<Arguments> args() {
// Combines each sorter implementation with each list to be sorted.
return sorters().flatMap(sorter -> lists().map(list -> Arguments.of(sorter, list)));
}
static Stream<Sorter> sorters() {
return Stream.of(new BubbleSorter(), new MergeSorter(), new InsertionSorter());
}
static Stream<List<Integer>> lists() {
return Stream.of(List.of(1, 2, 3), List.of(3, 2, 1), List.of(-1, 2, 0));
}
}
If you don't want to use a test oracle that provides the expected results (i.e. the sorted lists via a reference implementation), you can also combine three streams: sorters(), unsorted(), sorted(). Moreover, you can use Suppliers if you want to create your classes under test lazily:
static Stream<Supplier<Sorter>> sorters() {
return Stream.of(BubbleSorter::new, MergeSorter::new, InsertionSorter::new);
}

How can I implement Collection/List interface or abstract class in Kotlin?

I'm having trouble implementing the iterator and get set functions. (Edit: By trouble I mean that I don't know how to do it and I need help)
In the past, I've inherited from ArrayList even though I need a fixed-size collection.
I've also used an Array property in my class and added a get and a set operator funcions, but these two solutions just feel like unnecessary workarounds.
Edit: I just found out that Kotlin itself doesn't have a List implementation yet (it uses ArrayList instead), So maybe I'm not supposed to be able to Implement it. I'm going to keep this open just in case.
There is a very neat feature in Kotlin that allows you to easily implement the List interface by Delegation. Just use the by operator on a list property, then the class will delegate all methods of the List interface to that property. So, for example, instead of,
class Cars {
private val cars = ArrayList<Car>()
}
you write:
class Cars(
private val cars: MutableList<Car> = ArrayList<Car>()
): MutableList<Car> by cars
Now Cars implements List, and can be used just as such:
val cars = Cars()
cars.add(Car())
for (car in cars)
car.vroom()

Drools rule validating objects within Scala Option type

(Mandatory Newbie Disclaimer)
I'm trying to write a rule that fires whenever an object within a (scala) list matches a condition. The issue here is that the list is actually an Option(List[TypeA])... (Also, I realise it isn't best practice to store lists in working memory, but I can't do otherwise given the circumstances)
The case classes I'm using have the following sort of structure:
TypeA {
arg1 : Option[List[TypeB]]
}
with
TypeB {
value : String
}
I've written a rule similar to this:
when
$a : TypeA($l : arg1)
$b : TypeB() from $l.get()
then
System.out.println($b)
I've tried this out without the ".get()" only to get an object of type Some().
Using the ".get()", I have managed to return the contents of the Option but it doesn't seem to match the expected type (List[TypeB]). Instead the type of the value returned seems to be scala.collection.immutable.$colon$colon
Any ideas on what the problem is? And if there is any proper way to handle Options in Drools?
Since you are doing a lot of Java and Scala interop, I suggest you make yourself very familiar with the Scala's javaconverters functionality. This handy collection of utilities allows you to convert Scala collections to Java collection and vice versa.
In your case, I think you need to convert from a Java collection to a Scala collection. Try the following:
import scala.collection.JavaConverters._
val myScalaList = $b.asScala.toList
Example from the documentations:
import scala.collection.JavaConverters._
val sl = new scala.collection.mutable.ListBuffer[Int]
val jl : java.util.List[Int] = sl.asJava
val sl2 : scala.collection.mutable.Buffer[Int] = jl.asScala
assert(sl eq sl2)
An additional problem you have is that of mutable and immutable data structures. The standard list structure in Java is mutable but by default Scala offers you an immutable list unless you explicitly indicate that you want a mutable list. Therefore, there will be some impedance mismatch when doing naive conversions between the two worlds.
As I have mentioned in an earlier post, you can avoid yourself many issues by creating Java classes for the entities that you need to push into Drools. Mixing Java classes with Scala classes in Scala based projects is not an issue.
An alternative method is to create a function in your Scala case class which converts the Scala collection to a Java collection using the asJava method and returns it. In your DRL file whenever you need to reference that scala collection, call this method so that you get a Java collection instead.
Ideally, JBoss Drools, if they so choose, need to either enhance their current compiler to deal with Scala types better or make a dedicated Drools Scala compiler which will not mangle the Scala types.
The only thing I can think of to try:
when
$a : TypeA($l : arg)
$b : TypeB() from (ArrayList)$l.get() // or some other Java *-List
then
System.out.println($b)
Worth another try:
when
$a : TypeA($l : arg)
$b : TypeB() from $l.get()asJava()*-List
then
System.out.println($b)

Execute a js function with a cpp object as argument in v8

Is it possible to execute a js function with a cpp object as argument in v8?
if yes then how?
Lets say there is a function in javascript to traverse a Node tree .
function traverse_tree(root) /* root is type of Node */
{
no_of_node++; /* no_of_node is a global variable in js */
for(var i=0;i<root.children.length;i++)
{
traverse_tree(root.children[i]);
}
}
and the Node tree is created in C++;
class Node
{
public:
std::vector<Node*> children;
}
how can I pass the root of the tree structure created in cpp in the function calling argument?
Short Answer
No, it won't be possible for you to access the actual C++ object from javascript.
Webkit bridge works by making methods of a C++ object available in javascript under a particular name.
Simple variables such as strings or integers can be passed as parameters to these function calls.
Passing more complex objects is possible as long as they are HashMaps (key-value pairs).
This means that it's not possible to pass a reference so that the javascript and C++ "share" the object.
Possible Implementations
You could create a method in your C++ application (either as a separate class or as part of Node) and expose that object to javascript. Then any implementation you require (such as searching for a particular item) can be done in C++. In this manner you've created a javascript API to your C++ applications functionality.
If you really need to do the processing in javascript then you'd have to figure out a way to convert your tree into some kind of HashMap (so that it's meaningful as a JSON object) and then return it as a parameter to javascript.

Scala empty a list

I have a member variable in a class:
val options = mutable.LinkedList[SelectOption]()
I latter then populate this list from the database.
At some point I want to refresh the list. How do I empty it?
In java:
options.clear();
Is there an equivalent in Scala?
Do not use LinkedList. That is a low level collection which provides a data structure that can be manipulated at user's will... and responsibility.
Instead, use one of the Buffer classes, which have the clear method. This method, by the way, is inherited from the Clearable trait, so you can just look at classes that extend Clearable.